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 normal files called ' banckup ' from /usr directory downward and print them.
find /usr -type f -name backup -print
['find']
Output a Bash command to accomplish the following task. Task: search normal files called ' banckup ' from /usr directory downward and print them. Bash Command:<START>find /usr -type f -name backup -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 normal files called ' banckup ' from /usr directory downward and print them. Bash Command:<START>find /usr -type f -name backup -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 normal files called ' banckup ' from /usr directory downward and print them. Bash Command:<START>find /usr -type f -name backup -print<END>
search the entire file system for the file "jan92.rpt"
find / -name jan92.rpt -print
['find']
Output a Bash command to accomplish the following task. Task: search the entire file system for the file "jan92.rpt" Bash Command:<START>find / -name jan92.rpt -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 the entire file system for the file "jan92.rpt" Bash Command:<START>find / -name jan92.rpt -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 the entire file system for the file "jan92.rpt" Bash Command:<START>find / -name jan92.rpt -print<END>
search the file "myfile.txt" in home folder
find "$HOME/" -name myfile.txt -print
['find']
Output a Bash command to accomplish the following task. Task: search the file "myfile.txt" in home folder Bash Command:<START>find "$HOME/" -name myfile.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 the file "myfile.txt" in home folder Bash Command:<START>find "$HOME/" -name myfile.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 the file "myfile.txt" in home folder Bash Command:<START>find "$HOME/" -name myfile.txt -print<END>
search the file myfile.txt in the current folder
find . -name myfile.txt -print
['find']
Output a Bash command to accomplish the following task. Task: search the file myfile.txt in the current folder Bash Command:<START>find . -name myfile.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 the file myfile.txt in the current folder Bash Command:<START>find . -name myfile.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 the file myfile.txt in the current folder Bash Command:<START>find . -name myfile.txt -print<END>
search the pattern ^PyErr in all the ".c" files in the folder Lib/
find Lib/ -name '*.c' -print0 | xargs -0 grep ^PyErr
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search the pattern ^PyErr in all the ".c" files in the folder Lib/ Bash Command:<START>find Lib/ -name '*.c' -print0 | xargs -0 grep ^PyErr<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 the pattern ^PyErr in all the ".c" files in the folder Lib/ Bash Command:<START>find Lib/ -name '*.c' -print0 | xargs -0 grep ^PyErr<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 the pattern ^PyErr in all the ".c" files in the folder Lib/ Bash Command:<START>find Lib/ -name '*.c' -print0 | xargs -0 grep ^PyErr<END>
search the word "MySearchStr" in all the regular/normal files in the current folder and display the line number and the file name
find . -type f -print0 | xargs -0 -e grep -nH -e MySearchStr
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search the word "MySearchStr" in all the regular/normal files in the current folder and display the line number and the file name Bash Command:<START>find . -type f -print0 | xargs -0 -e grep -nH -e MySearchStr<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 the word "MySearchStr" in all the regular/normal files in the current folder and display the line number and the file name Bash Command:<START>find . -type f -print0 | xargs -0 -e grep -nH -e MySearchStr<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 the word "MySearchStr" in all the regular/normal files in the current folder and display the line number and the file name Bash Command:<START>find . -type f -print0 | xargs -0 -e grep -nH -e MySearchStr<END>
search the word NEEDLE and substitute it with REPLACEMENT in all the php files of the current folder
find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;
['find', 'sed']
Output a Bash command to accomplish the following task. Task: search the word NEEDLE and substitute it with REPLACEMENT in all the php files of the current folder Bash Command:<START>find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;<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 # 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 the word NEEDLE and substitute it with REPLACEMENT in all the php files of the current folder Bash Command:<START>find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;<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. 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 the word NEEDLE and substitute it with REPLACEMENT in all the php files of the current folder Bash Command:<START>find ./ -type f -exec sed -i '' 's#NEEDLE#REPLACEMENT#' *.php {} \;<END>
search through only the /usr and /home directories for any file named Chapter1.txt
find /usr /home -name Chapter1.txt -type f
['find']
Output a Bash command to accomplish the following task. Task: search through only the /usr and /home directories for any file named Chapter1.txt Bash Command:<START>find /usr /home -name Chapter1.txt -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 through only the /usr and /home directories for any file named Chapter1.txt Bash Command:<START>find /usr /home -name Chapter1.txt -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 through only the /usr and /home directories for any file named Chapter1.txt Bash Command:<START>find /usr /home -name Chapter1.txt -type f<END>
searches through the /usr directory for the regular file named 'Chapter1*'
find /usr -name "Chapter*" -type f
['find']
Output a Bash command to accomplish the following task. Task: searches through the /usr directory for the regular file named 'Chapter1*' Bash Command:<START>find /usr -name "Chapter*" -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: searches through the /usr directory for the regular file named 'Chapter1*' Bash Command:<START>find /usr -name "Chapter*" -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: searches through the /usr directory for the regular file named 'Chapter1*' Bash Command:<START>find /usr -name "Chapter*" -type f<END>
searches through the /usr/local directory for files that end with the extension .html
find /usr/local -name "*.html" -type f
['find']
Output a Bash command to accomplish the following task. Task: searches through the /usr/local directory for files that end with the extension .html Bash Command:<START>find /usr/local -name "*.html" -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: searches through the /usr/local directory for files that end with the extension .html Bash Command:<START>find /usr/local -name "*.html" -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: searches through the /usr/local directory for files that end with the extension .html Bash Command:<START>find /usr/local -name "*.html" -type f<END>
searches through the root filesystem ("/") for the file named Chapter1, and prints the location
find / -name Chapter1 -type f
['find']
Output a Bash command to accomplish the following task. Task: searches through the root filesystem ("/") for the file named Chapter1, and prints the location 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: searches through the root filesystem ("/") for the file named Chapter1, and prints the location 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: searches through the root filesystem ("/") for the file named Chapter1, and prints the location Bash Command:<START>find / -name Chapter1 -type f<END>
searches through the root filesystem ("/") for the file named Chapter1, and prints the location
find / -name Chapter1 -type f -print
['find']
Output a Bash command to accomplish the following task. Task: searches through the root filesystem ("/") for the file named Chapter1, and prints the location Bash Command:<START>find / -name Chapter1 -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: searches through the root filesystem ("/") for the file named Chapter1, and prints the location Bash Command:<START>find / -name Chapter1 -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: searches through the root filesystem ("/") for the file named Chapter1, and prints the location Bash Command:<START>find / -name Chapter1 -type f -print<END>
searches through the root filesystem ("/") for the file named Chapter1.
find / -name Chapter1 -type f
['find']
Output a Bash command to accomplish the following task. Task: searches through the root filesystem ("/") for the file named Chapter1. 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: searches through the root filesystem ("/") for the file named Chapter1. 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: searches through the root filesystem ("/") for the file named Chapter1. Bash Command:<START>find / -name Chapter1 -type f<END>
searches through the root filesystem ("/") for the file named Chapter1.
find / -name Chapter1 -type f -print
['find']
Output a Bash command to accomplish the following task. Task: searches through the root filesystem ("/") for the file named Chapter1. Bash Command:<START>find / -name Chapter1 -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: searches through the root filesystem ("/") for the file named Chapter1. Bash Command:<START>find / -name Chapter1 -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: searches through the root filesystem ("/") for the file named Chapter1. Bash Command:<START>find / -name Chapter1 -type f -print<END>
searching for all files with the extension mp3
find / -name *.mp3
['find']
Output a Bash command to accomplish the following task. Task: searching for all files with the extension mp3 Bash Command:<START>find / -name *.mp3<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: searching for all files with the extension mp3 Bash Command:<START>find / -name *.mp3<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: searching for all files with the extension mp3 Bash Command:<START>find / -name *.mp3<END>
set MyVariable to the value of VARIABLE_NAME
myVariable=$(env | grep VARIABLE_NAME | grep -oe '[^=]*$');
['grep', 'env']
Output a Bash command to accomplish the following task. Task: set MyVariable to the value of VARIABLE_NAME Bash Command:<START>myVariable=$(env | grep VARIABLE_NAME | grep -oe '[^=]*$');<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # env\n\n> Show the environment or run a program in a modified environment.\n> More information: <https://www.gnu.org/software/coreutils/env>.\n\n- Show the environment:\n\n`env`\n\n- Run a program. Often used in scripts after the shebang (#!) for looking up the path to the program:\n\n`env {{program}}`\n\n- Clear the environment and run a program:\n\n`env -i {{program}}`\n\n- Remove variable from the environment and run a program:\n\n`env -u {{variable}} {{program}}`\n\n- Set a variable and run a program:\n\n`env {{variable}}={{value}} {{program}}`\n\n- Set one or more variables and run a program:\n\n`env {{variable1}}={{value}} {{variable2}}={{value}} {{variable3}}={{value}} {{program}}`\n Task: set MyVariable to the value of VARIABLE_NAME Bash Command:<START>myVariable=$(env | grep VARIABLE_NAME | grep -oe '[^=]*$');<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. env(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training env(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | NOTES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON ENV(1) User Commands ENV(1) NAME top env - run a program in a modified environment SYNOPSIS top env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...] DESCRIPTION top Set each NAME to VALUE in the environment and run COMMAND. Mandatory arguments to long options are mandatory for short options too. -i, --ignore-environment start with an empty environment -0, --null end each output line with NUL, not newline -u, --unset=NAME remove variable from the environment -C, --chdir=DIR change working directory to DIR -S, --split-string=S process and split S into separate arguments; used to pass multiple arguments on shebang lines --block-signal[=SIG] block delivery of SIG signal(s) to COMMAND --default-signal[=SIG] reset handling of SIG signal(s) to the default --ignore-signal[=SIG] set handling of SIG signal(s) to do nothing --list-signal-handling list non default signal handling to stderr -v, --debug print verbose information for each processing step --help display this help and exit --version output version information and exit A mere - implies -i. If no COMMAND, print the resulting environment. SIG may be a signal name like 'PIPE', or a signal number like '13'. Without SIG, all known signals are included. Multiple signals can be comma-separated. An empty SIG argument is a no-op. Exit status: 125 if the env command itself fails 126 if COMMAND is found but cannot be invoked 127 if COMMAND cannot be found - the exit status of COMMAND otherwise OPTIONS top -S/--split-string usage in scripts The -S option allows specifying multiple parameters in a script. Running a script named 1.pl containing the following first line: #!/usr/bin/env -S perl -w -T ... Will execute perl -w -T 1.pl . Without the '-S' parameter the script will likely fail with: /usr/bin/env: 'perl -w -T': No such file or directory See the full documentation for more details. --default-signal[=SIG] usage This option allows setting a signal handler to its default action, which is not possible using the traditional shell trap command. The following example ensures that seq will be terminated by SIGPIPE no matter how this signal is being handled in the process invoking the command. sh -c 'env --default-signal=PIPE seq inf | head -n1' NOTES top POSIX's exec(3p) pages says: "many existing applications wrongly assume that they start with certain signals set to the default action and/or unblocked.... Therefore, it is best not to block or ignore signals across execs without explicit reason to do so, and especially not to block signals across execs of arbitrary (not closely cooperating) programs." AUTHOR top Written by Richard Mlynarik, David MacKenzie, and Assaf Gordon. 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 sigaction(2), sigprocmask(2), signal(7) Full documentation <https://www.gnu.org/software/coreutils/env> or available locally via: info '(coreutils) env 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 ENV(1) Pages that refer to this page: pmpython(1), 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. Task: set MyVariable to the value of VARIABLE_NAME Bash Command:<START>myVariable=$(env | grep VARIABLE_NAME | grep -oe '[^=]*$');<END>
set a crontab to create or update the timestamp of "washere1" in the current directory every minute.
echo "* * * * * touch $(pwd)/washere1" | crontab
['pwd', 'echo', 'crontab']
Output a Bash command to accomplish the following task. Task: set a crontab to create or update the timestamp of "washere1" in the current directory every minute. Bash Command:<START>echo "* * * * * touch $(pwd)/washere1" | crontab<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # pwd\n\n> Print name of current/working directory.\n> More information: <https://www.gnu.org/software/coreutils/pwd>.\n\n- Print the current directory:\n\n`pwd`\n\n- Print the current directory, and resolve all symlinks (i.e. show the "physical" path):\n\n`pwd --physical`\n\n- Print the current logical directory:\n\n`pwd --logical`\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 # crontab\n\n> Schedule cron jobs to run on a time interval for the current user.\n> More information: <https://crontab.guru/>.\n\n- Edit the crontab file for the current user:\n\n`crontab -e`\n\n- Edit the crontab file for a specific user:\n\n`sudo crontab -e -u {{user}}`\n\n- Replace the current crontab with the contents of the given file:\n\n`crontab {{path/to/file}}`\n\n- View a list of existing cron jobs for current user:\n\n`crontab -l`\n\n- Remove all cron jobs for the current user:\n\n`crontab -r`\n\n- Sample job which runs at 10:00 every day (* means any value):\n\n`0 10 * * * {{command_to_execute}}`\n\n- Sample crontab entry, which runs a command every 10 minutes:\n\n`*/10 * * * * {{command_to_execute}}`\n\n- Sample crontab entry, which runs a certain script at 02:30 every Friday:\n\n`30 2 * * Fri {{/absolute/path/to/script.sh}}`\n Task: set a crontab to create or update the timestamp of "washere1" in the current directory every minute. Bash Command:<START>echo "* * * * * touch $(pwd)/washere1" | crontab<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: pwd(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training pwd(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON PWD(1) User Commands PWD(1) NAME top pwd - print name of current/working directory SYNOPSIS top pwd [OPTION]... DESCRIPTION top Print the full filename of the current working directory. -L, --logical use PWD from environment, even if it contains symlinks -P, --physical avoid all symlinks --help display this help and exit --version output version information and exit If no option is specified, -P is assumed. NOTE: your shell may have its own version of pwd, 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 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 getcwd(3) Full documentation <https://www.gnu.org/software/coreutils/pwd> or available locally via: info '(coreutils) pwd 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 PWD(1) Pages that refer to this page: getcwd(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. 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. crontab(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training crontab(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | CAVEATS | SEE ALSO | FILES | STANDARDS | DIAGNOSTICS | AUTHOR | COLOPHON CRONTAB(1) User Commands CRONTAB(1) NAME top crontab - maintains crontab files for individual users SYNOPSIS top crontab [-u user] <file | -> crontab [-T] <file | -> crontab [-u user] <-l | -r | -e> [-i] [-s] crontab -n [ hostname ] crontab -c crontab -V DESCRIPTION top Crontab is the program used to install a crontab table file, remove or list the existing tables used to serve the cron(8) daemon. Each user can have their own crontab, and though these are files in /var/spool/, they are not intended to be edited directly. For SELinux in MLS mode, you can define more crontabs for each range. For more information, see selinux(8). In this version of Cron it is possible to use a network-mounted shared /var/spool/cron across a cluster of hosts and specify that only one of the hosts should run the crontab jobs in the particular directory at any one time. You may also use crontab from any of these hosts to edit the same shared set of crontab files, and to set and query which host should run the crontab jobs. Scheduling cron jobs with crontab can be allowed or disallowed for different users. For this purpose, use the cron.allow and cron.deny files. If the cron.allow file exists, a user must be listed in it to be allowed to use crontab. If the cron.allow file does not exist but the cron.deny file does exist, then a user must not be listed in the cron.deny file in order to use crontab. If neither of these files exist, then only the super user is allowed to use crontab. Another way to restrict the scheduling of cron jobs beyond crontab is to use PAM authentication in /etc/security/access.conf to set up users, which are allowed or disallowed to use crontab or modify system cron jobs in the /etc/cron.d/ directory. The temporary directory can be set in an environment variable. If it is not set by the user, the /tmp directory is used. When listing a crontab on a terminal the output will be colorized unless an environment variable NO_COLOR is set. On edition or deletion of the crontab, a backup of the last crontab will be saved to $XDG_CACHE_HOME/crontab/crontab.bak or $XDG_CACHE_HOME/crontab/crontab.<user>.bak if -u is used. If the XDG_CACHE_HOME environment variable is not set, $HOME/.cache will be used instead. OPTIONS top -u Specifies the name of the user whose crontab is to be modified. If this option is not used, crontab examines "your" crontab, i.e., the crontab of the person executing the command. If no crontab exists for a particular user, it is created for them the first time the crontab -u command is used under their username. -T Test the crontab file syntax without installing it. Once an issue is found, the validation is interrupted, so this will not return all the existing issues at the same execution. -l Displays the current crontab on standard output. -r Removes the current crontab. -e Edits the current crontab using the editor specified by the VISUAL or EDITOR environment variables. After you exit from the editor, the modified crontab will be installed automatically. -i This option modifies the -r option to prompt the user for a 'y/Y' response before actually removing the crontab. -s Appends the current SELinux security context string as an MLS_LEVEL setting to the crontab file before editing / replacement occurs - see the documentation of MLS_LEVEL in crontab(5). -n This option is relevant only if cron(8) was started with the -c option, to enable clustering support. It is used to set the host in the cluster which should run the jobs specified in the crontab files in the /var/spool/cron directory. If a hostname is supplied, the host whose hostname returned by gethostname(2) matches the supplied hostname, will be selected to run the selected cron jobs subsequently. If there is no host in the cluster matching the supplied hostname, or you explicitly specify an empty hostname, then the selected jobs will not be run at all. If the hostname is omitted, the name of the local host returned by gethostname(2) is used. Using this option has no effect on the /etc/crontab file and the files in the /etc/cron.d directory, which are always run, and considered host-specific. For more information on clustering support, see cron(8). -c This option is only relevant if cron(8) was started with the -c option, to enable clustering support. It is used to query which host in the cluster is currently set to run the jobs specified in the crontab files in the directory /var/spool/cron , as set using the -n option. -V Print version and exit. CAVEATS top The files cron.allow and cron.deny cannot be used to restrict the execution of cron jobs; they only restrict the use of crontab. In particular, restricting access to crontab has no effect on an existing crontab of a user. Its jobs will continue to be executed until the crontab is removed. The files cron.allow and cron.deny must be readable by the user invoking crontab. If this is not the case, then they are treated as non-existent. SEE ALSO top crontab(5), cron(8) FILES top /etc/cron.allow /etc/cron.deny STANDARDS top The crontab command conforms to IEEE Std1003.2-1992 (``POSIX'') with one exception: For replacing the current crontab with data from standard input the - has to be specified on the command line if the standard input is a TTY. This new command syntax differs from previous versions of Vixie Cron, as well as from the classic SVR3 syntax. DIAGNOSTICS top An informative usage message appears if you run a crontab with a faulty command defined in it. AUTHOR top Paul Vixie vixie@isc.org Colin Dean colin@colin-dean.org COLOPHON top This page is part of the cronie (crond daemon) project. Information about the project can be found at https://github.com/cronie-crond/cronie. If you have a bug report for this manual page, see https://github.com/cronie-crond/cronie/issues. This page was obtained from the project's upstream Git repository https://github.com/cronie-crond/cronie.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-16.) 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 cronie 2019-10-29 CRONTAB(1) Pages that refer to this page: cronnext(1), pmsnap(1), anacrontab(5), crontab(5), systemd.exec(5), cron(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: set a crontab to create or update the timestamp of "washere1" in the current directory every minute. Bash Command:<START>echo "* * * * * touch $(pwd)/washere1" | crontab<END>
set a crontab to create or update the timestamp of "washere2" in the current directory every 30 minutes.
echo "30 * * * * touch $(pwd)/washere2" | crontab
['crontab', 'pwd', 'echo']
Output a Bash command to accomplish the following task. Task: set a crontab to create or update the timestamp of "washere2" in the current directory every 30 minutes. Bash Command:<START>echo "30 * * * * touch $(pwd)/washere2" | crontab<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # crontab\n\n> Schedule cron jobs to run on a time interval for the current user.\n> More information: <https://crontab.guru/>.\n\n- Edit the crontab file for the current user:\n\n`crontab -e`\n\n- Edit the crontab file for a specific user:\n\n`sudo crontab -e -u {{user}}`\n\n- Replace the current crontab with the contents of the given file:\n\n`crontab {{path/to/file}}`\n\n- View a list of existing cron jobs for current user:\n\n`crontab -l`\n\n- Remove all cron jobs for the current user:\n\n`crontab -r`\n\n- Sample job which runs at 10:00 every day (* means any value):\n\n`0 10 * * * {{command_to_execute}}`\n\n- Sample crontab entry, which runs a command every 10 minutes:\n\n`*/10 * * * * {{command_to_execute}}`\n\n- Sample crontab entry, which runs a certain script at 02:30 every Friday:\n\n`30 2 * * Fri {{/absolute/path/to/script.sh}}`\n # pwd\n\n> Print name of current/working directory.\n> More information: <https://www.gnu.org/software/coreutils/pwd>.\n\n- Print the current directory:\n\n`pwd`\n\n- Print the current directory, and resolve all symlinks (i.e. show the "physical" path):\n\n`pwd --physical`\n\n- Print the current logical directory:\n\n`pwd --logical`\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: set a crontab to create or update the timestamp of "washere2" in the current directory every 30 minutes. Bash Command:<START>echo "30 * * * * touch $(pwd)/washere2" | crontab<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: crontab(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training crontab(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | CAVEATS | SEE ALSO | FILES | STANDARDS | DIAGNOSTICS | AUTHOR | COLOPHON CRONTAB(1) User Commands CRONTAB(1) NAME top crontab - maintains crontab files for individual users SYNOPSIS top crontab [-u user] <file | -> crontab [-T] <file | -> crontab [-u user] <-l | -r | -e> [-i] [-s] crontab -n [ hostname ] crontab -c crontab -V DESCRIPTION top Crontab is the program used to install a crontab table file, remove or list the existing tables used to serve the cron(8) daemon. Each user can have their own crontab, and though these are files in /var/spool/, they are not intended to be edited directly. For SELinux in MLS mode, you can define more crontabs for each range. For more information, see selinux(8). In this version of Cron it is possible to use a network-mounted shared /var/spool/cron across a cluster of hosts and specify that only one of the hosts should run the crontab jobs in the particular directory at any one time. You may also use crontab from any of these hosts to edit the same shared set of crontab files, and to set and query which host should run the crontab jobs. Scheduling cron jobs with crontab can be allowed or disallowed for different users. For this purpose, use the cron.allow and cron.deny files. If the cron.allow file exists, a user must be listed in it to be allowed to use crontab. If the cron.allow file does not exist but the cron.deny file does exist, then a user must not be listed in the cron.deny file in order to use crontab. If neither of these files exist, then only the super user is allowed to use crontab. Another way to restrict the scheduling of cron jobs beyond crontab is to use PAM authentication in /etc/security/access.conf to set up users, which are allowed or disallowed to use crontab or modify system cron jobs in the /etc/cron.d/ directory. The temporary directory can be set in an environment variable. If it is not set by the user, the /tmp directory is used. When listing a crontab on a terminal the output will be colorized unless an environment variable NO_COLOR is set. On edition or deletion of the crontab, a backup of the last crontab will be saved to $XDG_CACHE_HOME/crontab/crontab.bak or $XDG_CACHE_HOME/crontab/crontab.<user>.bak if -u is used. If the XDG_CACHE_HOME environment variable is not set, $HOME/.cache will be used instead. OPTIONS top -u Specifies the name of the user whose crontab is to be modified. If this option is not used, crontab examines "your" crontab, i.e., the crontab of the person executing the command. If no crontab exists for a particular user, it is created for them the first time the crontab -u command is used under their username. -T Test the crontab file syntax without installing it. Once an issue is found, the validation is interrupted, so this will not return all the existing issues at the same execution. -l Displays the current crontab on standard output. -r Removes the current crontab. -e Edits the current crontab using the editor specified by the VISUAL or EDITOR environment variables. After you exit from the editor, the modified crontab will be installed automatically. -i This option modifies the -r option to prompt the user for a 'y/Y' response before actually removing the crontab. -s Appends the current SELinux security context string as an MLS_LEVEL setting to the crontab file before editing / replacement occurs - see the documentation of MLS_LEVEL in crontab(5). -n This option is relevant only if cron(8) was started with the -c option, to enable clustering support. It is used to set the host in the cluster which should run the jobs specified in the crontab files in the /var/spool/cron directory. If a hostname is supplied, the host whose hostname returned by gethostname(2) matches the supplied hostname, will be selected to run the selected cron jobs subsequently. If there is no host in the cluster matching the supplied hostname, or you explicitly specify an empty hostname, then the selected jobs will not be run at all. If the hostname is omitted, the name of the local host returned by gethostname(2) is used. Using this option has no effect on the /etc/crontab file and the files in the /etc/cron.d directory, which are always run, and considered host-specific. For more information on clustering support, see cron(8). -c This option is only relevant if cron(8) was started with the -c option, to enable clustering support. It is used to query which host in the cluster is currently set to run the jobs specified in the crontab files in the directory /var/spool/cron , as set using the -n option. -V Print version and exit. CAVEATS top The files cron.allow and cron.deny cannot be used to restrict the execution of cron jobs; they only restrict the use of crontab. In particular, restricting access to crontab has no effect on an existing crontab of a user. Its jobs will continue to be executed until the crontab is removed. The files cron.allow and cron.deny must be readable by the user invoking crontab. If this is not the case, then they are treated as non-existent. SEE ALSO top crontab(5), cron(8) FILES top /etc/cron.allow /etc/cron.deny STANDARDS top The crontab command conforms to IEEE Std1003.2-1992 (``POSIX'') with one exception: For replacing the current crontab with data from standard input the - has to be specified on the command line if the standard input is a TTY. This new command syntax differs from previous versions of Vixie Cron, as well as from the classic SVR3 syntax. DIAGNOSTICS top An informative usage message appears if you run a crontab with a faulty command defined in it. AUTHOR top Paul Vixie vixie@isc.org Colin Dean colin@colin-dean.org COLOPHON top This page is part of the cronie (crond daemon) project. Information about the project can be found at https://github.com/cronie-crond/cronie. If you have a bug report for this manual page, see https://github.com/cronie-crond/cronie/issues. This page was obtained from the project's upstream Git repository https://github.com/cronie-crond/cronie.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-16.) 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 cronie 2019-10-29 CRONTAB(1) Pages that refer to this page: cronnext(1), pmsnap(1), anacrontab(5), crontab(5), systemd.exec(5), cron(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. pwd(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training pwd(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON PWD(1) User Commands PWD(1) NAME top pwd - print name of current/working directory SYNOPSIS top pwd [OPTION]... DESCRIPTION top Print the full filename of the current working directory. -L, --logical use PWD from environment, even if it contains symlinks -P, --physical avoid all symlinks --help display this help and exit --version output version information and exit If no option is specified, -P is assumed. NOTE: your shell may have its own version of pwd, 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 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 getcwd(3) Full documentation <https://www.gnu.org/software/coreutils/pwd> or available locally via: info '(coreutils) pwd 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 PWD(1) Pages that refer to this page: getcwd(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. 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: set a crontab to create or update the timestamp of "washere2" in the current directory every 30 minutes. Bash Command:<START>echo "30 * * * * touch $(pwd)/washere2" | crontab<END>
set variable "uname_m" to machine architecture, ie. x86_64
uname_m=`uname -m`
['uname']
Output a Bash command to accomplish the following task. Task: set variable "uname_m" to machine architecture, ie. x86_64 Bash Command:<START>uname_m=`uname -m`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # uname\n\n> Uname prints information about the machine and operating system it is run on.\n> More information: <https://www.gnu.org/software/coreutils/manual/html_node/uname-invocation.html>.\n\n- Print all information:\n\n`uname --all`\n\n- Print the current kernel name:\n\n`uname --kernel-name`\n\n- Print the current network node host name:\n\n`uname --nodename`\n\n- Print the current kernel release:\n\n`uname --kernel-release`\n\n- Print the current kernel version:\n\n`uname --kernel-version`\n\n- Print the current machine hardware name:\n\n`uname --machine`\n\n- Print the current processor type:\n\n`uname --processor`\n\n- Print the current operating system name:\n\n`uname --operating-system`\n Task: set variable "uname_m" to machine architecture, ie. x86_64 Bash Command:<START>uname_m=`uname -m`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: uname(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training uname(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON UNAME(1) User Commands UNAME(1) NAME top uname - print system information SYNOPSIS top uname [OPTION]... DESCRIPTION top Print certain system information. With no OPTION, same as -s. -a, --all print all information, in the following order, except omit -p and -i if unknown: -s, --kernel-name print the kernel name -n, --nodename print the network node hostname -r, --kernel-release print the kernel release -v, --kernel-version print the kernel version -m, --machine print the machine hardware name -p, --processor print the processor type (non-portable) -i, --hardware-platform print the hardware platform (non-portable) -o, --operating-system print the operating system --help display this help and exit --version output version information and exit AUTHOR top Written by 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 arch(1), uname(2) Full documentation <https://www.gnu.org/software/coreutils/uname> or available locally via: info '(coreutils) uname 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 UNAME(1) Pages that refer to this page: arch(1), uname(2), systemd.unit(5), lsof(8), ovs-l3ping(8), ovs-test(8), ovs-vlan-test(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: set variable "uname_m" to machine architecture, ie. x86_64 Bash Command:<START>uname_m=`uname -m`<END>
set variable r to currently running kernel release, ie. 4.4.0-81-generic
r="$(uname -r)"
['uname']
Output a Bash command to accomplish the following task. Task: set variable r to currently running kernel release, ie. 4.4.0-81-generic Bash Command:<START>r="$(uname -r)"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # uname\n\n> Uname prints information about the machine and operating system it is run on.\n> More information: <https://www.gnu.org/software/coreutils/manual/html_node/uname-invocation.html>.\n\n- Print all information:\n\n`uname --all`\n\n- Print the current kernel name:\n\n`uname --kernel-name`\n\n- Print the current network node host name:\n\n`uname --nodename`\n\n- Print the current kernel release:\n\n`uname --kernel-release`\n\n- Print the current kernel version:\n\n`uname --kernel-version`\n\n- Print the current machine hardware name:\n\n`uname --machine`\n\n- Print the current processor type:\n\n`uname --processor`\n\n- Print the current operating system name:\n\n`uname --operating-system`\n Task: set variable r to currently running kernel release, ie. 4.4.0-81-generic Bash Command:<START>r="$(uname -r)"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: uname(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training uname(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON UNAME(1) User Commands UNAME(1) NAME top uname - print system information SYNOPSIS top uname [OPTION]... DESCRIPTION top Print certain system information. With no OPTION, same as -s. -a, --all print all information, in the following order, except omit -p and -i if unknown: -s, --kernel-name print the kernel name -n, --nodename print the network node hostname -r, --kernel-release print the kernel release -v, --kernel-version print the kernel version -m, --machine print the machine hardware name -p, --processor print the processor type (non-portable) -i, --hardware-platform print the hardware platform (non-portable) -o, --operating-system print the operating system --help display this help and exit --version output version information and exit AUTHOR top Written by 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 arch(1), uname(2) Full documentation <https://www.gnu.org/software/coreutils/uname> or available locally via: info '(coreutils) uname 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 UNAME(1) Pages that refer to this page: arch(1), uname(2), systemd.unit(5), lsof(8), ovs-l3ping(8), ovs-test(8), ovs-vlan-test(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: set variable r to currently running kernel release, ie. 4.4.0-81-generic Bash Command:<START>r="$(uname -r)"<END>
show all .cpp, .c, .h, .hpp files in the folder ~/src
find ~/src -type f \( -iname '*.cpp' -or -iname '*.h' -or -iname '*.c' -or -iname '*.hpp' \) -exec echo {} \;
['find', 'echo']
Output a Bash command to accomplish the following task. Task: show all .cpp, .c, .h, .hpp files in the folder ~/src Bash Command:<START>find ~/src -type f \( -iname '*.cpp' -or -iname '*.h' -or -iname '*.c' -or -iname '*.hpp' \) -exec 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 # 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: show all .cpp, .c, .h, .hpp files in the folder ~/src Bash Command:<START>find ~/src -type f \( -iname '*.cpp' -or -iname '*.h' -or -iname '*.c' -or -iname '*.hpp' \) -exec 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. 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: show all .cpp, .c, .h, .hpp files in the folder ~/src Bash Command:<START>find ~/src -type f \( -iname '*.cpp' -or -iname '*.h' -or -iname '*.c' -or -iname '*.hpp' \) -exec echo {} \;<END>
show all directories in the current folder excluding those that are present in the sub directories of media, images and backups
find . -type d \( -name media -o -name images -o -name backups \) -prune -o -print
['find']
Output a Bash command to accomplish the following task. Task: show all directories in the current folder excluding those that are present in the sub directories of media, images and backups Bash Command:<START>find . -type d \( -name media -o -name images -o -name backups \) -prune -o -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: show all directories in the current folder excluding those that are present in the sub directories of media, images and backups Bash Command:<START>find . -type d \( -name media -o -name images -o -name backups \) -prune -o -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: show all directories in the current folder excluding those that are present in the sub directories of media, images and backups Bash Command:<START>find . -type d \( -name media -o -name images -o -name backups \) -prune -o -print<END>
show all directories in the current folder excluding those that are present only in the paths ./media, ./images and ./backups
find . -path './media' -prune -o -path './images' -prune -o -path './backups' -prune -o -print
['find']
Output a Bash command to accomplish the following task. Task: show all directories in the current folder excluding those that are present only in the paths ./media, ./images and ./backups Bash Command:<START>find . -path './media' -prune -o -path './images' -prune -o -path './backups' -prune -o -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: show all directories in the current folder excluding those that are present only in the paths ./media, ./images and ./backups Bash Command:<START>find . -path './media' -prune -o -path './images' -prune -o -path './backups' -prune -o -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: show all directories in the current folder excluding those that are present only in the paths ./media, ./images and ./backups Bash Command:<START>find . -path './media' -prune -o -path './images' -prune -o -path './backups' -prune -o -print<END>
show all files in /usr/tom and display only files ending with ".pl" or ".pm"
find /usr/tom | egrep '*.pl| *.pm'
['find']
Output a Bash command to accomplish the following task. Task: show all files in /usr/tom and display only files ending with ".pl" or ".pm" Bash Command:<START>find /usr/tom | egrep '*.pl| *.pm'<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: show all files in /usr/tom and display only files ending with ".pl" or ".pm" Bash Command:<START>find /usr/tom | egrep '*.pl| *.pm'<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: show all files in /usr/tom and display only files ending with ".pl" or ".pm" Bash Command:<START>find /usr/tom | egrep '*.pl| *.pm'<END>
show all files in the current directory and all subdirectories
find .
['find']
Output a Bash command to accomplish the following task. Task: show all files in the current directory and all subdirectories Bash Command:<START>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: show all files in the current directory and all subdirectories Bash Command:<START>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: show all files in the current directory and all subdirectories Bash Command:<START>find .<END>
show all files in the current directory and all subdirectories
find . -print
['find']
Output a Bash command to accomplish the following task. Task: show all files in the current directory and all subdirectories Bash Command:<START>find . -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: show all files in the current directory and all subdirectories Bash Command:<START>find . -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: show all files in the current directory and all subdirectories Bash Command:<START>find . -print<END>
show all regular/normal the files in the current folder whose size is bigger than 0 bytes excluding everything
find * -prune -type f -size +0c -print
['find']
Output a Bash command to accomplish the following task. Task: show all regular/normal the files in the current folder whose size is bigger than 0 bytes excluding everything Bash Command:<START>find * -prune -type f -size +0c -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: show all regular/normal the files in the current folder whose size is bigger than 0 bytes excluding everything Bash Command:<START>find * -prune -type f -size +0c -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: show all regular/normal the files in the current folder whose size is bigger than 0 bytes excluding everything Bash Command:<START>find * -prune -type f -size +0c -print<END>
show all the ".acc" files in the folder /home
find /home -type f -name '*.aac'
['find']
Output a Bash command to accomplish the following task. Task: show all the ".acc" files in the folder /home Bash Command:<START>find /home -type f -name '*.aac'<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: show all the ".acc" files in the folder /home Bash Command:<START>find /home -type f -name '*.aac'<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: show all the ".acc" files in the folder /home Bash Command:<START>find /home -type f -name '*.aac'<END>
show all the ".flac" files in the current folder and do not search in the sub directories
find . -maxdepth 1 -type f -name '*.flac'
['find']
Output a Bash command to accomplish the following task. Task: show all the ".flac" files in the current folder and do not search in the sub directories Bash Command:<START>find . -maxdepth 1 -type f -name '*.flac'<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: show all the ".flac" files in the current folder and do not search in the sub directories Bash Command:<START>find . -maxdepth 1 -type f -name '*.flac'<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: show all the ".flac" files in the current folder and do not search in the sub directories Bash Command:<START>find . -maxdepth 1 -type f -name '*.flac'<END>
show all the directories in the current folder
find . -type d
['find']
Output a Bash command to accomplish the following task. Task: show all the directories in the current folder Bash Command:<START>find . -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: show all the directories in the current folder Bash Command:<START>find . -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: show all the directories in the current folder Bash Command:<START>find . -type d<END>
show all the files in current directory
find .
['find']
Output a Bash command to accomplish the following task. Task: show all the files in current directory Bash Command:<START>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: show all the files in current directory Bash Command:<START>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: show all the files in current directory Bash Command:<START>find .<END>
show all the files in the current folder excluding those from the directories whose name starts with "git"
find . -type d -name '.git*' -prune -o -type f -print
['find']
Output a Bash command to accomplish the following task. Task: show all the files in the current folder excluding those from the directories whose name starts with "git" Bash Command:<START>find . -type d -name '.git*' -prune -o -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: show all the files in the current folder excluding those from the directories whose name starts with "git" Bash Command:<START>find . -type d -name '.git*' -prune -o -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: show all the files in the current folder excluding those from the directories whose name starts with "git" Bash Command:<START>find . -type d -name '.git*' -prune -o -type f -print<END>
show all the files in the current folder which has the word "ITM"
find . -name ‘*ITM*’
['find']
Output a Bash command to accomplish the following task. Task: show all the files in the current folder which has the word "ITM" Bash Command:<START>find . -name ‘*ITM*’<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: show all the files in the current folder which has the word "ITM" Bash Command:<START>find . -name ‘*ITM*’<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: show all the files in the current folder which has the word "ITM" Bash Command:<START>find . -name ‘*ITM*’<END>
show all the files in the entire file system which are bigger than 1.1GB
find / -size +1.1G
['find']
Output a Bash command to accomplish the following task. Task: show all the files in the entire file system which are bigger than 1.1GB Bash Command:<START>find / -size +1.1G<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: show all the files in the entire file system which are bigger than 1.1GB Bash Command:<START>find / -size +1.1G<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: show all the files in the entire file system which are bigger than 1.1GB Bash Command:<START>find / -size +1.1G<END>
show all the files in the entire file system which are bigger than 100MB
find / -size +100M
['find']
Output a Bash command to accomplish the following task. Task: show all the files in the entire file system which are bigger than 100MB Bash Command:<START>find / -size +100M<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: show all the files in the entire file system which are bigger than 100MB Bash Command:<START>find / -size +100M<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: show all the files in the entire file system which are bigger than 100MB Bash Command:<START>find / -size +100M<END>
show all the files in the folder /etc which have been modified in the last 24 hours
find /etc -mtime -1
['find']
Output a Bash command to accomplish the following task. Task: show all the files in the folder /etc which have been modified in the last 24 hours Bash Command:<START>find /etc -mtime -1<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: show all the files in the folder /etc which have been modified in the last 24 hours Bash Command:<START>find /etc -mtime -1<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: show all the files in the folder /etc which have been modified in the last 24 hours Bash Command:<START>find /etc -mtime -1<END>
show all the mp3 files in the folder /home
find /home -type f -name '*.mp3'
['find']
Output a Bash command to accomplish the following task. Task: show all the mp3 files in the folder /home Bash Command:<START>find /home -type f -name '*.mp3'<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: show all the mp3 files in the folder /home Bash Command:<START>find /home -type f -name '*.mp3'<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: show all the mp3 files in the folder /home Bash Command:<START>find /home -type f -name '*.mp3'<END>
show all the regular files in current folder
find . -type f -print0
['find']
Output a Bash command to accomplish the following task. Task: show all the regular files in current folder Bash Command:<START>find . -type f -print0<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: show all the regular files in current folder Bash Command:<START>find . -type f -print0<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: show all the regular files in current folder Bash Command:<START>find . -type f -print0<END>
show all the regular/normal files in the folder /home/user/demo
find /home/user/demo -type f -print
['find']
Output a Bash command to accomplish the following task. Task: show all the regular/normal files in the folder /home/user/demo Bash Command:<START>find /home/user/demo -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: show all the regular/normal files in the folder /home/user/demo Bash Command:<START>find /home/user/demo -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: show all the regular/normal files in the folder /home/user/demo Bash Command:<START>find /home/user/demo -type f -print<END>
show the disk use of all the regular/normal files in the current folder which are bigger than 50MB
find . -type f -size +50000k | xargs du -sh
['find', 'du', 'xargs']
Output a Bash command to accomplish the following task. Task: show the disk use of all the regular/normal files in the current folder which are bigger than 50MB Bash Command:<START>find . -type f -size +50000k | xargs du -sh<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 # du\n\n> Disk usage: estimate and summarize file and directory space usage.\n> More information: <https://www.gnu.org/software/coreutils/du>.\n\n- List the sizes of a directory and any subdirectories, in the given unit (B/KiB/MiB):\n\n`du -{{b|k|m}} {{path/to/directory}}`\n\n- List the sizes of a directory and any subdirectories, in human-readable form (i.e. auto-selecting the appropriate unit for each size):\n\n`du -h {{path/to/directory}}`\n\n- Show the size of a single directory, in human-readable units:\n\n`du -sh {{path/to/directory}}`\n\n- List the human-readable sizes of a directory and of all the files and directories within it:\n\n`du -ah {{path/to/directory}}`\n\n- List the human-readable sizes of a directory and any subdirectories, up to N levels deep:\n\n`du -h --max-depth=N {{path/to/directory}}`\n\n- List the human-readable size of all `.jpg` files in subdirectories of the current directory, and show a cumulative total at the end:\n\n`du -ch {{*/*.jpg}}`\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 Task: show the disk use of all the regular/normal files in the current folder which are bigger than 50MB Bash Command:<START>find . -type f -size +50000k | xargs du -sh<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. du(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training du(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | PATTERNS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON DU(1) User Commands DU(1) NAME top du - estimate file space usage SYNOPSIS top du [OPTION]... [FILE]... du [OPTION]... --files0-from=F DESCRIPTION top Summarize device usage of the set of FILEs, recursively for directories. Mandatory arguments to long options are mandatory for short options too. -0, --null end each output line with NUL, not newline -a, --all write counts for all files, not just directories --apparent-size print apparent sizes rather than device usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like -B, --block-size=SIZE scale sizes by SIZE before printing them; e.g., '-BM' prints sizes in units of 1,048,576 bytes; see SIZE format below -b, --bytes equivalent to '--apparent-size --block-size=1' -c, --total produce a grand total -D, --dereference-args dereference only symlinks that are listed on the command line -d, --max-depth=N print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize --files0-from=F summarize device usage of the NUL-terminated file names specified in file F; if F is -, then read names from standard input -H equivalent to --dereference-args (-D) -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G) --inodes list inode usage information instead of block usage -k like --block-size=1K -L, --dereference dereference all symbolic links -l, --count-links count sizes many times if hard linked -m like --block-size=1M -P, --no-dereference don't follow any symbolic links (this is the default) -S, --separate-dirs for directories do not include size of subdirectories --si like -h, but use powers of 1000 not 1024 -s, --summarize display only a total for each argument -t, --threshold=SIZE exclude entries smaller than SIZE if positive, or entries greater than SIZE if negative --time show time of the last modification of any file in the directory, or any of its subdirectories --time=WORD show time as WORD instead of modification time: atime, access, use, ctime or status --time-style=STYLE show times using STYLE, which can be: full-iso, long-iso, iso, or +FORMAT; FORMAT is interpreted like in 'date' -X, --exclude-from=FILE exclude files that match any pattern in FILE --exclude=PATTERN exclude files that match PATTERN -x, --one-file-system skip directories on different file systems --help display this help and exit --version output version information and exit Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. PATTERNS top PATTERN is a shell pattern (not a regular expression). The pattern ? matches any one character, whereas * matches any string (composed of zero, one or multiple characters). For example, *.o will match any files whose names end in .o. Therefore, the command du --exclude='*.o' will skip all files and subdirectories ending in .o (including the file .o itself). AUTHOR top Written by Torbjorn Granlund, David MacKenzie, Paul Eggert, 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 Full documentation <https://www.gnu.org/software/coreutils/du> or available locally via: info '(coreutils) du 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 DU(1) Pages that refer to this page: tmpfs(5), 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. Task: show the disk use of all the regular/normal files in the current folder which are bigger than 50MB Bash Command:<START>find . -type f -size +50000k | xargs du -sh<END>
show the disk use of all the regular/normal files in the file system which are bigger than 100MB
find / -type f -size +100M | xargs du -sh
['find', 'du', 'xargs']
Output a Bash command to accomplish the following task. Task: show the disk use of all the regular/normal files in the file system which are bigger than 100MB Bash Command:<START>find / -type f -size +100M | xargs du -sh<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 # du\n\n> Disk usage: estimate and summarize file and directory space usage.\n> More information: <https://www.gnu.org/software/coreutils/du>.\n\n- List the sizes of a directory and any subdirectories, in the given unit (B/KiB/MiB):\n\n`du -{{b|k|m}} {{path/to/directory}}`\n\n- List the sizes of a directory and any subdirectories, in human-readable form (i.e. auto-selecting the appropriate unit for each size):\n\n`du -h {{path/to/directory}}`\n\n- Show the size of a single directory, in human-readable units:\n\n`du -sh {{path/to/directory}}`\n\n- List the human-readable sizes of a directory and of all the files and directories within it:\n\n`du -ah {{path/to/directory}}`\n\n- List the human-readable sizes of a directory and any subdirectories, up to N levels deep:\n\n`du -h --max-depth=N {{path/to/directory}}`\n\n- List the human-readable size of all `.jpg` files in subdirectories of the current directory, and show a cumulative total at the end:\n\n`du -ch {{*/*.jpg}}`\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 Task: show the disk use of all the regular/normal files in the file system which are bigger than 100MB Bash Command:<START>find / -type f -size +100M | xargs du -sh<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. du(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training du(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | PATTERNS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON DU(1) User Commands DU(1) NAME top du - estimate file space usage SYNOPSIS top du [OPTION]... [FILE]... du [OPTION]... --files0-from=F DESCRIPTION top Summarize device usage of the set of FILEs, recursively for directories. Mandatory arguments to long options are mandatory for short options too. -0, --null end each output line with NUL, not newline -a, --all write counts for all files, not just directories --apparent-size print apparent sizes rather than device usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like -B, --block-size=SIZE scale sizes by SIZE before printing them; e.g., '-BM' prints sizes in units of 1,048,576 bytes; see SIZE format below -b, --bytes equivalent to '--apparent-size --block-size=1' -c, --total produce a grand total -D, --dereference-args dereference only symlinks that are listed on the command line -d, --max-depth=N print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize --files0-from=F summarize device usage of the NUL-terminated file names specified in file F; if F is -, then read names from standard input -H equivalent to --dereference-args (-D) -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G) --inodes list inode usage information instead of block usage -k like --block-size=1K -L, --dereference dereference all symbolic links -l, --count-links count sizes many times if hard linked -m like --block-size=1M -P, --no-dereference don't follow any symbolic links (this is the default) -S, --separate-dirs for directories do not include size of subdirectories --si like -h, but use powers of 1000 not 1024 -s, --summarize display only a total for each argument -t, --threshold=SIZE exclude entries smaller than SIZE if positive, or entries greater than SIZE if negative --time show time of the last modification of any file in the directory, or any of its subdirectories --time=WORD show time as WORD instead of modification time: atime, access, use, ctime or status --time-style=STYLE show times using STYLE, which can be: full-iso, long-iso, iso, or +FORMAT; FORMAT is interpreted like in 'date' -X, --exclude-from=FILE exclude files that match any pattern in FILE --exclude=PATTERN exclude files that match PATTERN -x, --one-file-system skip directories on different file systems --help display this help and exit --version output version information and exit Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. PATTERNS top PATTERN is a shell pattern (not a regular expression). The pattern ? matches any one character, whereas * matches any string (composed of zero, one or multiple characters). For example, *.o will match any files whose names end in .o. Therefore, the command du --exclude='*.o' will skip all files and subdirectories ending in .o (including the file .o itself). AUTHOR top Written by Torbjorn Granlund, David MacKenzie, Paul Eggert, 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 Full documentation <https://www.gnu.org/software/coreutils/du> or available locally via: info '(coreutils) du 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 DU(1) Pages that refer to this page: tmpfs(5), 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. Task: show the disk use of all the regular/normal files in the file system which are bigger than 100MB Bash Command:<START>find / -type f -size +100M | xargs du -sh<END>
show the list of all the files in the current folder which have been modified within the 24 hours
find . -mtime 0 -print
['find']
Output a Bash command to accomplish the following task. Task: show the list of all the files in the current folder which have been modified within the 24 hours Bash Command:<START>find . -mtime 0 -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: show the list of all the files in the current folder which have been modified within the 24 hours Bash Command:<START>find . -mtime 0 -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: show the list of all the files in the current folder which have been modified within the 24 hours Bash Command:<START>find . -mtime 0 -print<END>
show the sum of disk used by all the files that belong to the user "test1" in the entire file system
find / -user test1 -exec du -sm {} \;|awk '{s+=$1}END{print s}'
['find', 'awk', 'du']
Output a Bash command to accomplish the following task. Task: show the sum of disk used by all the files that belong to the user "test1" in the entire file system Bash Command:<START>find / -user test1 -exec du -sm {} \;|awk '{s+=$1}END{print s}'<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 # awk\n\n> A versatile programming language for working on files.\n> More information: <https://github.com/onetrueawk/awk>.\n\n- Print the fifth column (a.k.a. field) in a space-separated file:\n\n`awk '{print $5}' {{path/to/file}}`\n\n- Print the second column of the lines containing "foo" in a space-separated file:\n\n`awk '/{{foo}}/ {print $2}' {{path/to/file}}`\n\n- Print the last column of each line in a file, using a comma (instead of space) as a field separator:\n\n`awk -F ',' '{print $NF}' {{path/to/file}}`\n\n- Sum the values in the first column of a file and print the total:\n\n`awk '{s+=$1} END {print s}' {{path/to/file}}`\n\n- Print every third line starting from the first line:\n\n`awk 'NR%3==1' {{path/to/file}}`\n\n- Print different values based on conditions:\n\n`awk '{if ($1 == "foo") print "Exact match foo"; else if ($1 ~ "bar") print "Partial match bar"; else print "Baz"}' {{path/to/file}}`\n\n- Print all lines where the 10th column value equals the specified value:\n\n`awk '($10 == {{value}})'`\n\n- Print all the lines which the 10th column value is between a min and a max:\n\n`awk '($10 >= {{min_value}} && $10 <= {{max_value}})'`\n # du\n\n> Disk usage: estimate and summarize file and directory space usage.\n> More information: <https://www.gnu.org/software/coreutils/du>.\n\n- List the sizes of a directory and any subdirectories, in the given unit (B/KiB/MiB):\n\n`du -{{b|k|m}} {{path/to/directory}}`\n\n- List the sizes of a directory and any subdirectories, in human-readable form (i.e. auto-selecting the appropriate unit for each size):\n\n`du -h {{path/to/directory}}`\n\n- Show the size of a single directory, in human-readable units:\n\n`du -sh {{path/to/directory}}`\n\n- List the human-readable sizes of a directory and of all the files and directories within it:\n\n`du -ah {{path/to/directory}}`\n\n- List the human-readable sizes of a directory and any subdirectories, up to N levels deep:\n\n`du -h --max-depth=N {{path/to/directory}}`\n\n- List the human-readable size of all `.jpg` files in subdirectories of the current directory, and show a cumulative total at the end:\n\n`du -ch {{*/*.jpg}}`\n Task: show the sum of disk used by all the files that belong to the user "test1" in the entire file system Bash Command:<START>find / -user test1 -exec du -sm {} \;|awk '{s+=$1}END{print s}'<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. awk(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training awk(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 AWK(1P) POSIX Programmer's Manual AWK(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 awk pattern scanning and processing language SYNOPSIS top awk [-F sepstring] [-v assignment]... program [argument...] awk [-F sepstring] -f progfile [-f progfile]... [-v assignment]... [argument...] DESCRIPTION top The awk utility shall execute programs written in the awk programming language, which is specialized for textual data manipulation. An awk program is a sequence of patterns and corresponding actions. When input is read that matches a pattern, the action associated with that pattern is carried out. Input shall be interpreted as a sequence of records. By default, a record is a line, less its terminating <newline>, but this can be changed by using the RS built-in variable. Each record of input shall be matched in turn against each pattern in the program. For each pattern matched, the associated action shall be executed. The awk utility shall interpret each input record as a sequence of fields where, by default, a field is a string of non-<blank> non-<newline> characters. This default <blank> and <newline> field delimiter can be changed by using the FS built-in variable or the -F sepstring option. The awk utility shall denote the first field in a record $1, the second $2, and so on. The symbol $0 shall refer to the entire record; setting any other field causes the re-evaluation of $0. Assigning to $0 shall reset the values of all other fields and the NF built-in variable. OPTIONS top The awk utility shall conform to the Base Definitions volume of POSIX.12017, Section 12.2, Utility Syntax Guidelines. The following options shall be supported: -F sepstring Define the input field separator. This option shall be equivalent to: -v FS=sepstring except that if -F sepstring and -v FS=sepstring are both used, it is unspecified whether the FS assignment resulting from -F sepstring is processed in command line order or is processed after the last -v FS=sepstring. See the description of the FS built-in variable, and how it is used, in the EXTENDED DESCRIPTION section. -f progfile Specify the pathname of the file progfile containing an awk program. A pathname of '-' shall denote the standard input. If multiple instances of this option are specified, the concatenation of the files specified as progfile in the order specified shall be the awk program. The awk program can alternatively be specified in the command line as a single argument. -v assignment The application shall ensure that the assignment argument is in the same form as an assignment operand. The specified variable assignment shall occur prior to executing the awk program, including the actions associated with BEGIN patterns (if any). Multiple occurrences of this option can be specified. OPERANDS top The following operands shall be supported: program If no -f option is specified, the first operand to awk shall be the text of the awk program. The application shall supply the program operand as a single argument to awk. If the text does not end in a <newline>, awk shall interpret the text as if it did. argument Either of the following two types of argument can be intermixed: file A pathname of a file that contains the input to be read, which is matched against the set of patterns in the program. If no file operands are specified, or if a file operand is '-', the standard input shall be used. assignment An operand that begins with an <underscore> or alphabetic character from the portable character set (see the table in the Base Definitions volume of POSIX.12017, Section 6.1, Portable Character Set), followed by a sequence of underscores, digits, and alphabetics from the portable character set, followed by the '=' character, shall specify a variable assignment rather than a pathname. The characters before the '=' represent the name of an awk variable; if that name is an awk reserved word (see Grammar) the behavior is undefined. The characters following the <equals-sign> shall be interpreted as if they appeared in the awk program preceded and followed by a double-quote ('"') character, as a STRING token (see Grammar), except that if the last character is an unescaped <backslash>, it shall be interpreted as a literal <backslash> rather than as the first character of the sequence "\"". The variable shall be assigned the value of that STRING token and, if appropriate, shall be considered a numeric string (see Expressions in awk), the variable shall also be assigned its numeric value. Each such variable assignment shall occur just prior to the processing of the following file, if any. Thus, an assignment before the first file argument shall be executed after the BEGIN actions (if any), while an assignment after the last file argument shall occur before the END actions (if any). If there are no file arguments, assignments shall be executed before processing the standard input. STDIN top The standard input shall be used only if no file operands are specified, or if a file operand is '-', or if a progfile option- argument is '-'; see the INPUT FILES section. If the awk program contains no actions and no patterns, but is otherwise a valid awk program, standard input and any file operands shall not be read and awk shall exit with a return status of zero. INPUT FILES top Input files to the awk program from any of the following sources shall be text files: * Any file operands or their equivalents, achieved by modifying the awk variables ARGV and ARGC * Standard input in the absence of any file operands * Arguments to the getline function Whether the variable RS is set to a value other than a <newline> or not, for these files, implementations shall support records terminated with the specified separator up to {LINE_MAX} bytes and may support longer records. If -f progfile is specified, the application shall ensure that the files named by each of the progfile option-arguments are text files and their concatenation, in the same order as they appear in the arguments, is an awk program. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of awk: 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_COLLATE Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions and in comparisons of string values. 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 and input files), the behavior of character classes within regular expressions, the identification of characters as letters, and the mapping of uppercase and lowercase characters for the toupper and tolower functions. LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. LC_NUMERIC Determine the radix character used when interpreting numeric input, performing conversions between numeric and string values, and formatting numeric output. Regardless of locale, the <period> character (the decimal-point character of the POSIX locale) is the decimal-point character recognized in processing awk programs (including assignments in command line arguments). NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. PATH Determine the search path when looking for commands executed by system(expr), or input and output pipes; see the Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables. In addition, all environment variables shall be visible via the awk variable ENVIRON. ASYNCHRONOUS EVENTS top Default. STDOUT top The nature of the output files depends on the awk program. STDERR top The standard error shall be used only for diagnostic messages. OUTPUT FILES top The nature of the output files depends on the awk program. EXTENDED DESCRIPTION top Overall Program Structure An awk program is composed of pairs of the form: pattern { action } Either the pattern or the action (including the enclosing brace characters) can be omitted. A missing pattern shall match any record of input, and a missing action shall be equivalent to: { print } Execution of the awk program shall start by first executing the actions associated with all BEGIN patterns in the order they occur in the program. Then each file operand (or standard input if no files were specified) shall be processed in turn by reading data from the file until a record separator is seen (<newline> by default). Before the first reference to a field in the record is evaluated, the record shall be split into fields, according to the rules in Regular Expressions, using the value of FS that was current at the time the record was read. Each pattern in the program then shall be evaluated in the order of occurrence, and the action associated with each pattern that matches the current record executed. The action for a matching pattern shall be executed before evaluating subsequent patterns. Finally, the actions associated with all END patterns shall be executed in the order they occur in the program. Expressions in awk Expressions describe computations used in patterns and actions. In the following table, valid expression operations are given in groups from highest precedence first to lowest precedence last, with equal-precedence operators grouped between horizontal lines. In expression evaluation, where the grammar is formally ambiguous, higher precedence operators shall be evaluated before lower precedence operators. In this table expr, expr1, expr2, and expr3 represent any expression, while lvalue represents any entity that can be assigned to (that is, on the left side of an assignment operator). The precise syntax of expressions is given in Grammar. Table 4-1: Expressions in Decreasing Precedence in awk Syntax Name Type of Result Associativity ( expr ) Grouping Type of expr N/A $expr Field reference String N/A lvalue ++ Post-increment Numeric N/A lvalue -- Post-decrement Numeric N/A ++ lvalue Pre-increment Numeric N/A -- lvalue Pre-decrement Numeric N/A expr ^ expr Exponentiation Numeric Right ! expr Logical not Numeric N/A + expr Unary plus Numeric N/A - expr Unary minus Numeric N/A expr * expr Multiplication Numeric Left expr / expr Division Numeric Left expr % expr Modulus Numeric Left expr + expr Addition Numeric Left expr - expr Subtraction Numeric Left expr expr String concatenation String Left expr < expr Less than Numeric None expr <= expr Less than or equal to Numeric None expr != expr Not equal to Numeric None expr == expr Equal to Numeric None expr > expr Greater than Numeric None expr >= expr Greater than or equal to Numeric None expr ~ expr ERE match Numeric None expr !~ expr ERE non-match Numeric None expr in array Array membership Numeric Left ( index ) in array Multi-dimension array Numeric Left membership expr && expr Logical AND Numeric Left expr || expr Logical OR Numeric Left expr1 ? expr2 : expr3Conditional expression Type of selectedRight expr2 or expr3 lvalue ^= expr Exponentiation assignmentNumeric Right lvalue %= expr Modulus assignment Numeric Right lvalue *= expr Multiplication assignmentNumeric Right lvalue /= expr Division assignment Numeric Right lvalue += expr Addition assignment Numeric Right lvalue -= expr Subtraction assignment Numeric Right lvalue = expr Assignment Type of expr Right Each expression shall have either a string value, a numeric value, or both. Except as stated for specific contexts, the value of an expression shall be implicitly converted to the type needed for the context in which it is used. A string value shall be converted to a numeric value either by the equivalent of the following calls to functions defined by the ISO C standard: setlocale(LC_NUMERIC, ""); numeric_value = atof(string_value); or by converting the initial portion of the string to type double representation as follows: The input string is decomposed into two parts: an initial, possibly empty, sequence of white-space characters (as specified by isspace()) and a subject sequence interpreted as a floating-point constant. The expected form of the subject sequence is an optional '+' or '-' sign, then a non-empty sequence of digits optionally containing a <period>, then an optional exponent part. An exponent part consists of 'e' or 'E', followed by an optional sign, followed by one or more decimal digits. The sequence starting with the first digit or the <period> (whichever occurs first) is interpreted as a floating constant of the C language, and if neither an exponent part nor a <period> appears, a <period> is assumed to follow the last digit in the string. If the subject sequence begins with a <hyphen-minus>, the value resulting from the conversion is negated. A numeric value that is exactly equal to the value of an integer (see Section 1.1.2, Concepts Derived from the ISO C Standard) shall be converted to a string by the equivalent of a call to the sprintf function (see String Functions) with the string "%d" as the fmt argument and the numeric value being converted as the first and only expr argument. Any other numeric value shall be converted to a string by the equivalent of a call to the sprintf function with the value of the variable CONVFMT as the fmt argument and the numeric value being converted as the first and only expr argument. The result of the conversion is unspecified if the value of CONVFMT is not a floating-point format specification. This volume of POSIX.12017 specifies no explicit conversions between numbers and strings. An application can force an expression to be treated as a number by adding zero to it, or can force it to be treated as a string by concatenating the null string ("") to it. A string value shall be considered a numeric string if it comes from one of the following: 1. Field variables 2. Input from the getline() function 3. FILENAME 4. ARGV array elements 5. ENVIRON array elements 6. Array elements created by the split() function 7. A command line variable assignment 8. Variable assignment from another numeric string variable and an implementation-dependent condition corresponding to either case (a) or (b) below is met. a. After the equivalent of the following calls to functions defined by the ISO C standard, string_value_end would differ from string_value, and any characters before the terminating null character in string_value_end would be <blank> characters: char *string_value_end; setlocale(LC_NUMERIC, ""); numeric_value = strtod (string_value, &string_value_end); b. After all the following conversions have been applied, the resulting string would lexically be recognized as a NUMBER token as described by the lexical conventions in Grammar: -- All leading and trailing <blank> characters are discarded. -- If the first non-<blank> is '+' or '-', it is discarded. -- Each occurrence of the decimal point character from the current locale is changed to a <period>. In case (a) the numeric value of the numeric string shall be the value that would be returned by the strtod() call. In case (b) if the first non-<blank> is '-', the numeric value of the numeric string shall be the negation of the numeric value of the recognized NUMBER token; otherwise, the numeric value of the numeric string shall be the numeric value of the recognized NUMBER token. Whether or not a string is a numeric string shall be relevant only in contexts where that term is used in this section. When an expression is used in a Boolean context, if it has a numeric value, a value of zero shall be treated as false and any other value shall be treated as true. Otherwise, a string value of the null string shall be treated as false and any other value shall be treated as true. A Boolean context shall be one of the following: * The first subexpression of a conditional expression * An expression operated on by logical NOT, logical AND, or logical OR * The second expression of a for statement * The expression of an if statement * The expression of the while clause in either a while or do...while statement * An expression used as a pattern (as in Overall Program Structure) All arithmetic shall follow the semantics of floating-point arithmetic as specified by the ISO C standard (see Section 1.1.2, Concepts Derived from the ISO C Standard). The value of the expression: expr1 ^ expr2 shall be equivalent to the value returned by the ISO C standard function call: pow(expr1, expr2) The expression: lvalue ^= expr shall be equivalent to the ISO C standard expression: lvalue = pow(lvalue, expr) except that lvalue shall be evaluated only once. The value of the expression: expr1 % expr2 shall be equivalent to the value returned by the ISO C standard function call: fmod(expr1, expr2) The expression: lvalue %= expr shall be equivalent to the ISO C standard expression: lvalue = fmod(lvalue, expr) except that lvalue shall be evaluated only once. Variables and fields shall be set by the assignment statement: lvalue = expression and the type of expression shall determine the resulting variable type. The assignment includes the arithmetic assignments ("+=", "-=", "*=", "/=", "%=", "^=", "++", "--") all of which shall produce a numeric result. The left-hand side of an assignment and the target of increment and decrement operators can be one of a variable, an array with index, or a field selector. The awk language supplies arrays that are used for storing numbers or strings. Arrays need not be declared. They shall initially be empty, and their sizes shall change dynamically. The subscripts, or element identifiers, are strings, providing a type of associative array capability. An array name followed by a subscript within square brackets can be used as an lvalue and thus as an expression, as described in the grammar; see Grammar. Unsubscripted array names can be used in only the following contexts: * A parameter in a function definition or function call * The NAME token following any use of the keyword in as specified in the grammar (see Grammar); if the name used in this context is not an array name, the behavior is undefined A valid array index shall consist of one or more <comma>-separated expressions, similar to the way in which multi- dimensional arrays are indexed in some programming languages. Because awk arrays are really one-dimensional, such a <comma>-separated list shall be converted to a single string by concatenating the string values of the separate expressions, each separated from the other by the value of the SUBSEP variable. Thus, the following two index operations shall be equivalent: var[expr1, expr2, ... exprn] var[expr1 SUBSEP expr2 SUBSEP ... SUBSEP exprn] The application shall ensure that a multi-dimensioned index used with the in operator is parenthesized. The in operator, which tests for the existence of a particular array element, shall not cause that element to exist. Any other reference to a nonexistent array element shall automatically create it. Comparisons (with the '<', "<=", "!=", "==", '>', and ">=" operators) shall be made numerically if both operands are numeric, if one is numeric and the other has a string value that is a numeric string, or if one is numeric and the other has the uninitialized value. Otherwise, operands shall be converted to strings as required and a string comparison shall be made as follows: * For the "!=" and "==" operators, the strings should be compared to check if they are identical but may be compared using the locale-specific collation sequence to check if they collate equally. * For the other operators, the strings shall be compared using the locale-specific collation sequence. The value of the comparison expression shall be 1 if the relation is true, or 0 if the relation is false. Variables and Special Variables Variables can be used in an awk program by referencing them. With the exception of function parameters (see User-Defined Functions), they are not explicitly declared. Function parameter names shall be local to the function; all other variable names shall be global. The same name shall not be used as both a function parameter name and as the name of a function or a special awk variable. The same name shall not be used both as a variable name with global scope and as the name of a function. The same name shall not be used within the same scope both as a scalar variable and as an array. Uninitialized variables, including scalar variables, array elements, and field variables, shall have an uninitialized value. An uninitialized value shall have both a numeric value of zero and a string value of the empty string. Evaluation of variables with an uninitialized value, to either string or numeric, shall be determined by the context in which they are used. Field variables shall be designated by a '$' followed by a number or numerical expression. The effect of the field number expression evaluating to anything other than a non-negative integer is unspecified; uninitialized variables or string values need not be converted to numeric values in this context. New field variables can be created by assigning a value to them. References to nonexistent fields (that is, fields after $NF), shall evaluate to the uninitialized value. Such references shall not create new fields. However, assigning to a nonexistent field (for example, $(NF+2)=5) shall increase the value of NF; create any intervening fields with the uninitialized value; and cause the value of $0 to be recomputed, with the fields being separated by the value of OFS. Each field variable shall have a string value or an uninitialized value when created. Field variables shall have the uninitialized value when created from $0 using FS and the variable does not contain any characters. If appropriate, the field variable shall be considered a numeric string (see Expressions in awk). Implementations shall support the following other special variables that are set by awk: ARGC The number of elements in the ARGV array. ARGV An array of command line arguments, excluding options and the program argument, numbered from zero to ARGC-1. The arguments in ARGV can be modified or added to; ARGC can be altered. As each input file ends, awk shall treat the next non-null element of ARGV, up to the current value of ARGC-1, inclusive, as the name of the next input file. Thus, setting an element of ARGV to null means that it shall not be treated as an input file. The name '-' indicates the standard input. If an argument matches the format of an assignment operand, this argument shall be treated as an assignment rather than a file argument. CONVFMT The printf format for converting numbers to strings (except for output statements, where OFMT is used); "%.6g" by default. ENVIRON An array representing the value of the environment, as described in the exec functions defined in the System Interfaces volume of POSIX.12017. The indices of the array shall be strings consisting of the names of the environment variables, and the value of each array element shall be a string consisting of the value of that variable. If appropriate, the environment variable shall be considered a numeric string (see Expressions in awk); the array element shall also have its numeric value. In all cases where the behavior of awk is affected by environment variables (including the environment of any commands that awk executes via the system function or via pipeline redirections with the print statement, the printf statement, or the getline function), the environment used shall be the environment at the time awk began executing; it is implementation-defined whether any modification of ENVIRON affects this environment. FILENAME A pathname of the current input file. Inside a BEGIN action the value is undefined. Inside an END action the value shall be the name of the last input file processed. FNR The ordinal number of the current record in the current file. Inside a BEGIN action the value shall be zero. Inside an END action the value shall be the number of the last record processed in the last file processed. FS Input field separator regular expression; a <space> by default. NF The number of fields in the current record. Inside a BEGIN action, the use of NF is undefined unless a getline function without a var argument is executed previously. Inside an END action, NF shall retain the value it had for the last record read, unless a subsequent, redirected, getline function without a var argument is performed prior to entering the END action. NR The ordinal number of the current record from the start of input. Inside a BEGIN action the value shall be zero. Inside an END action the value shall be the number of the last record processed. OFMT The printf format for converting numbers to strings in output statements (see Output Statements); "%.6g" by default. The result of the conversion is unspecified if the value of OFMT is not a floating-point format specification. OFS The print statement output field separator; <space> by default. ORS The print statement output record separator; a <newline> by default. RLENGTH The length of the string matched by the match function. RS The first character of the string value of RS shall be the input record separator; a <newline> by default. If RS contains more than one character, the results are unspecified. If RS is null, then records are separated by sequences consisting of a <newline> plus one or more blank lines, leading or trailing blank lines shall not result in empty records at the beginning or end of the input, and a <newline> shall always be a field separator, no matter what the value of FS is. RSTART The starting position of the string matched by the match function, numbering from 1. This shall always be equivalent to the return value of the match function. SUBSEP The subscript separator string for multi-dimensional arrays; the default value is implementation-defined. Regular Expressions The awk utility shall make use of the extended regular expression notation (see the Base Definitions volume of POSIX.12017, Section 9.4, Extended Regular Expressions) except that it shall allow the use of C-language conventions for escaping special characters within the EREs, as specified in the table in the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v') and the following table; these escape sequences shall be recognized both inside and outside bracket expressions. Note that records need not be separated by <newline> characters and string constants can contain <newline> characters, so even the "\n" sequence is valid in awk EREs. Using a <slash> character within an ERE requires the escaping shown in the following table. Table 4-2: Escape Sequences in awk Escape Sequence Description Meaning \" <backslash> <quotation-mark> <quotation-mark> character \/ <backslash> <slash> <slash> character \ddd A <backslash> character followed The character whose encoding is by the longest sequence of one, represented by the one, two, or two, or three octal-digit three-digit octal integer. Multi- characters (01234567). If all of byte characters require multiple, the digits are 0 (that is, concatenated escape sequences of representation of the NUL this type, including the leading character), the behavior is <backslash> for each byte. undefined. \c A <backslash> character followed Undefined by any character not described in this table or in the table in the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v'). A regular expression can be matched against a specific field or string by using one of the two regular expression matching operators, '~' and "!~". These operators shall interpret their right-hand operand as a regular expression and their left-hand operand as a string. If the regular expression matches the string, the '~' expression shall evaluate to a value of 1, and the "!~" expression shall evaluate to a value of 0. (The regular expression matching operation is as defined by the term matched in the Base Definitions volume of POSIX.12017, Section 9.1, Regular Expression Definitions, where a match occurs on any part of the string unless the regular expression is limited with the <circumflex> or <dollar-sign> special characters.) If the regular expression does not match the string, the '~' expression shall evaluate to a value of 0, and the "!~" expression shall evaluate to a value of 1. If the right-hand operand is any expression other than the lexical token ERE, the string value of the expression shall be interpreted as an extended regular expression, including the escape conventions described above. Note that these same escape conventions shall also be applied in determining the value of a string literal (the lexical token STRING), and thus shall be applied a second time when a string literal is used in this context. When an ERE token appears as an expression in any context other than as the right-hand of the '~' or "!~" operator or as one of the built-in function arguments described below, the value of the resulting expression shall be the equivalent of: $0 ~ /ere/ The ere argument to the gsub, match, sub functions, and the fs argument to the split function (see String Functions) shall be interpreted as extended regular expressions. These can be either ERE tokens or arbitrary expressions, and shall be interpreted in the same manner as the right-hand side of the '~' or "!~" operator. An extended regular expression can be used to separate fields by assigning a string containing the expression to the built-in variable FS, either directly or as a consequence of using the -F sepstring option. The default value of the FS variable shall be a single <space>. The following describes FS behavior: 1. If FS is a null string, the behavior is unspecified. 2. If FS is a single character: a. If FS is <space>, skip leading and trailing <blank> and <newline> characters; fields shall be delimited by sets of one or more <blank> or <newline> characters. b. Otherwise, if FS is any other character c, fields shall be delimited by each single occurrence of c. 3. Otherwise, the string value of FS shall be considered to be an extended regular expression. Each occurrence of a sequence matching the extended regular expression shall delimit fields. Except for the '~' and "!~" operators, and in the gsub, match, split, and sub built-in functions, ERE matching shall be based on input records; that is, record separator characters (the first character of the value of the variable RS, <newline> by default) cannot be embedded in the expression, and no expression shall match the record separator character. If the record separator is not <newline>, <newline> characters embedded in the expression can be matched. For the '~' and "!~" operators, and in those four built-in functions, ERE matching shall be based on text strings; that is, any character (including <newline> and the record separator) can be embedded in the pattern, and an appropriate pattern shall match any character. However, in all awk ERE matching, the use of one or more NUL characters in the pattern, input record, or text string produces undefined results. Patterns A pattern is any valid expression, a range specified by two expressions separated by a comma, or one of the two special patterns BEGIN or END. Special Patterns The awk utility shall recognize two special patterns, BEGIN and END. Each BEGIN pattern shall be matched once and its associated action executed before the first record of input is readexcept possibly by use of the getline function (see Input/Output and General Functions) in a prior BEGIN actionand before command line assignment is done. Each END pattern shall be matched once and its associated action executed after the last record of input has been read. These two patterns shall have associated actions. BEGIN and END shall not combine with other patterns. Multiple BEGIN and END patterns shall be allowed. The actions associated with the BEGIN patterns shall be executed in the order specified in the program, as are the END actions. An END pattern can precede a BEGIN pattern in a program. If an awk program consists of only actions with the pattern BEGIN, and the BEGIN action contains no getline function, awk shall exit without reading its input when the last statement in the last BEGIN action is executed. If an awk program consists of only actions with the pattern END or only actions with the patterns BEGIN and END, the input shall be read before the statements in the END actions are executed. Expression Patterns An expression pattern shall be evaluated as if it were an expression in a Boolean context. If the result is true, the pattern shall be considered to match, and the associated action (if any) shall be executed. If the result is false, the action shall not be executed. Pattern Ranges A pattern range consists of two expressions separated by a comma; in this case, the action shall be performed for all records between a match of the first expression and the following match of the second expression, inclusive. At this point, the pattern range can be repeated starting at input records subsequent to the end of the matched range. Actions An action is a sequence of statements as shown in the grammar in Grammar. Any single statement can be replaced by a statement list enclosed in curly braces. The application shall ensure that statements in a statement list are separated by <newline> or <semicolon> characters. Statements in a statement list shall be executed sequentially in the order that they appear. The expression acting as the conditional in an if statement shall be evaluated and if it is non-zero or non-null, the following statement shall be executed; otherwise, if else is present, the statement following the else shall be executed. The if, while, do...while, for, break, and continue statements are based on the ISO C standard (see Section 1.1.2, Concepts Derived from the ISO C Standard), except that the Boolean expressions shall be treated as described in Expressions in awk, and except in the case of: for (variable in array) which shall iterate, assigning each index of array to variable in an unspecified order. The results of adding new elements to array within such a for loop are undefined. If a break or continue statement occurs outside of a loop, the behavior is undefined. The delete statement shall remove an individual array element. Thus, the following code deletes an entire array: for (index in array) delete array[index] The next statement shall cause all further processing of the current input record to be abandoned. The behavior is undefined if a next statement appears or is invoked in a BEGIN or END action. The exit statement shall invoke all END actions in the order in which they occur in the program source and then terminate the program without reading further input. An exit statement inside an END action shall terminate the program without further execution of END actions. If an expression is specified in an exit statement, its numeric value shall be the exit status of awk, unless subsequent errors are encountered or a subsequent exit statement with an expression is executed. Output Statements Both print and printf statements shall write to standard output by default. The output shall be written to the location specified by output_redirection if one is supplied, as follows: > expression >> expression | expression In all cases, the expression shall be evaluated to produce a string that is used as a pathname into which to write (for '>' or ">>") or as a command to be executed (for '|'). Using the first two forms, if the file of that name is not currently open, it shall be opened, creating it if necessary and using the first form, truncating the file. The output then shall be appended to the file. As long as the file remains open, subsequent calls in which expression evaluates to the same string value shall simply append output to the file. The file remains open until the close function (see Input/Output and General Functions) is called with an expression that evaluates to the same string value. The third form shall write output onto a stream piped to the input of a command. The stream shall be created if no stream is currently open with the value of expression as its command name. The stream created shall be equivalent to one created by a call to the popen() function defined in the System Interfaces volume of POSIX.12017 with the value of expression as the command argument and a value of w as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall write output to the existing stream. The stream shall remain open until the close function (see Input/Output and General Functions) is called with an expression that evaluates to the same string value. At that time, the stream shall be closed as if by a call to the pclose() function defined in the System Interfaces volume of POSIX.12017. As described in detail by the grammar in Grammar, these output statements shall take a <comma>-separated list of expressions referred to in the grammar by the non-terminal symbols expr_list, print_expr_list, or print_expr_list_opt. This list is referred to here as the expression list, and each member is referred to as an expression argument. The print statement shall write the value of each expression argument onto the indicated output stream separated by the current output field separator (see variable OFS above), and terminated by the output record separator (see variable ORS above). All expression arguments shall be taken as strings, being converted if necessary; this conversion shall be as described in Expressions in awk, with the exception that the printf format in OFMT shall be used instead of the value in CONVFMT. An empty expression list shall stand for the whole input record ($0). The printf statement shall produce output based on a notation similar to the File Format Notation used to describe file formats in this volume of POSIX.12017 (see the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation). Output shall be produced as specified with the first expression argument as the string format and subsequent expression arguments as the strings arg1 to argn, inclusive, with the following exceptions: 1. The format shall be an actual character string rather than a graphical representation. Therefore, it cannot contain empty character positions. The <space> in the format string, in any context other than a flag of a conversion specification, shall be treated as an ordinary character that is copied to the output. 2. If the character set contains a '' character and that character appears in the format string, it shall be treated as an ordinary character that is copied to the output. 3. The escape sequences beginning with a <backslash> character shall be treated as sequences of ordinary characters that are copied to the output. Note that these same sequences shall be interpreted lexically by awk when they appear in literal strings, but they shall not be treated specially by the printf statement. 4. A field width or precision can be specified as the '*' character instead of a digit string. In this case the next argument from the expression list shall be fetched and its numeric value taken as the field width or precision. 5. The implementation shall not precede or follow output from the d or u conversion specifier characters with <blank> characters not specified by the format string. 6. The implementation shall not precede output from the o conversion specifier character with leading zeros not specified by the format string. 7. For the c conversion specifier character: if the argument has a numeric value, the character whose encoding is that value shall be output. If the value is zero or is not the encoding of any character in the character set, the behavior is undefined. If the argument does not have a numeric value, the first character of the string value shall be output; if the string does not contain any characters, the behavior is undefined. 8. For each conversion specification that consumes an argument, the next expression argument shall be evaluated. With the exception of the c conversion specifier character, the value shall be converted (according to the rules specified in Expressions in awk) to the appropriate type for the conversion specification. 9. If there are insufficient expression arguments to satisfy all the conversion specifications in the format string, the behavior is undefined. 10. If any character sequence in the format string begins with a '%' character, but does not form a valid conversion specification, the behavior is unspecified. Both print and printf can output at least {LINE_MAX} bytes. Functions The awk language has a variety of built-in functions: arithmetic, string, input/output, and general. Arithmetic Functions The arithmetic functions, except for int, shall be based on the ISO C standard (see Section 1.1.2, Concepts Derived from the ISO C Standard). The behavior is undefined in cases where the ISO C standard specifies that an error be returned or that the behavior is undefined. Although the grammar (see Grammar) permits built-in functions to appear with no arguments or parentheses, unless the argument or parentheses are indicated as optional in the following list (by displaying them within the "[]" brackets), such use is undefined. atan2(y,x) Return arctangent of y/x in radians in the range [-,]. cos(x) Return cosine of x, where x is in radians. sin(x) Return sine of x, where x is in radians. exp(x) Return the exponential function of x. log(x) Return the natural logarithm of x. sqrt(x) Return the square root of x. int(x) Return the argument truncated to an integer. Truncation shall be toward 0 when x>0. rand() Return a random number n, such that 0n<1. srand([expr]) Set the seed value for rand to expr or use the time of day if expr is omitted. The previous seed value shall be returned. String Functions The string functions in the following list shall be supported. Although the grammar (see Grammar) permits built-in functions to appear with no arguments or parentheses, unless the argument or parentheses are indicated as optional in the following list (by displaying them within the "[]" brackets), such use is undefined. gsub(ere, repl[, in]) Behave like sub (see below), except that it shall replace all occurrences of the regular expression (like the ed utility global substitute) in $0 or in the in argument, when specified. index(s, t) Return the position, in characters, numbering from 1, in string s where string t first occurs, or zero if it does not occur at all. length[([s])] Return the length, in characters, of its argument taken as a string, or of the whole record, $0, if there is no argument. match(s, ere) Return the position, in characters, numbering from 1, in string s where the extended regular expression ere occurs, or zero if it does not occur at all. RSTART shall be set to the starting position (which is the same as the returned value), zero if no match is found; RLENGTH shall be set to the length of the matched string, -1 if no match is found. split(s, a[, fs ]) Split the string s into array elements a[1], a[2], ..., a[n], and return n. All elements of the array shall be deleted before the split is performed. The separation shall be done with the ERE fs or with the field separator FS if fs is not given. Each array element shall have a string value when created and, if appropriate, the array element shall be considered a numeric string (see Expressions in awk). The effect of a null string as the value of fs is unspecified. sprintf(fmt, expr, expr, ...) Format the expressions according to the printf format given by fmt and return the resulting string. sub(ere, repl[, in ]) Substitute the string repl in place of the first instance of the extended regular expression ERE in string in and return the number of substitutions. An <ampersand> ('&') appearing in the string repl shall be replaced by the string from in that matches the ERE. An <ampersand> preceded with a <backslash> shall be interpreted as the literal <ampersand> character. An occurrence of two consecutive <backslash> characters shall be interpreted as just a single literal <backslash> character. Any other occurrence of a <backslash> (for example, preceding any other character) shall be treated as a literal <backslash> character. Note that if repl is a string literal (the lexical token STRING; see Grammar), the handling of the <ampersand> character occurs after any lexical processing, including any lexical <backslash>-escape sequence processing. If in is specified and it is not an lvalue (see Expressions in awk), the behavior is undefined. If in is omitted, awk shall use the current record ($0) in its place. substr(s, m[, n ]) Return the at most n-character substring of s that begins at position m, numbering from 1. If n is omitted, or if n specifies more characters than are left in the string, the length of the substring shall be limited by the length of the string s. tolower(s) Return a string based on the string s. Each character in s that is an uppercase letter specified to have a tolower mapping by the LC_CTYPE category of the current locale shall be replaced in the returned string by the lowercase letter specified by the mapping. Other characters in s shall be unchanged in the returned string. toupper(s) Return a string based on the string s. Each character in s that is a lowercase letter specified to have a toupper mapping by the LC_CTYPE category of the current locale is replaced in the returned string by the uppercase letter specified by the mapping. Other characters in s are unchanged in the returned string. All of the preceding functions that take ERE as a parameter expect a pattern or a string valued expression that is a regular expression as defined in Regular Expressions. Input/Output and General Functions The input/output and general functions are: close(expression) Close the file or pipe opened by a print or printf statement or a call to getline with the same string- valued expression. The limit on the number of open expression arguments is implementation-defined. If the close was successful, the function shall return zero; otherwise, it shall return non-zero. expression | getline [var] Read a record of input from a stream piped from the output of a command. The stream shall be created if no stream is currently open with the value of expression as its command name. The stream created shall be equivalent to one created by a call to the popen() function with the value of expression as the command argument and a value of r as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall read subsequent records from the stream. The stream shall remain open until the close function is called with an expression that evaluates to the same string value. At that time, the stream shall be closed as if by a call to the pclose() function. If var is omitted, $0 and NF shall be set; otherwise, var shall be set and, if appropriate, it shall be considered a numeric string (see Expressions in awk). The getline operator can form ambiguous constructs when there are unparenthesized operators (including concatenate) to the left of the '|' (to the beginning of the expression containing getline). In the context of the '$' operator, '|' shall behave as if it had a lower precedence than '$'. The result of evaluating other operators is unspecified, and conforming applications shall parenthesize properly all such usages. getline Set $0 to the next input record from the current input file. This form of getline shall set the NF, NR, and FNR variables. getline var Set variable var to the next input record from the current input file and, if appropriate, var shall be considered a numeric string (see Expressions in awk). This form of getline shall set the FNR and NR variables. getline [var] < expression Read the next record of input from a named file. The expression shall be evaluated to produce a string that is used as a pathname. If the file of that name is not currently open, it shall be opened. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall read subsequent records from the file. The file shall remain open until the close function is called with an expression that evaluates to the same string value. If var is omitted, $0 and NF shall be set; otherwise, var shall be set and, if appropriate, it shall be considered a numeric string (see Expressions in awk). The getline operator can form ambiguous constructs when there are unparenthesized binary operators (including concatenate) to the right of the '<' (up to the end of the expression containing the getline). The result of evaluating such a construct is unspecified, and conforming applications shall parenthesize properly all such usages. system(expression) Execute the command given by expression in a manner equivalent to the system() function defined in the System Interfaces volume of POSIX.12017 and return the exit status of the command. All forms of getline shall return 1 for successful input, zero for end-of-file, and -1 for an error. Where strings are used as the name of a file or pipeline, the application shall ensure that the strings are textually identical. The terminology ``same string value'' implies that ``equivalent strings'', even those that differ only by <space> characters, represent different files. User-Defined Functions The awk language also provides user-defined functions. Such functions can be defined as: function name([parameter, ...]) { statements } A function can be referred to anywhere in an awk program; in particular, its use can precede its definition. The scope of a function is global. Function parameters, if present, can be either scalars or arrays; the behavior is undefined if an array name is passed as a parameter that the function uses as a scalar, or if a scalar expression is passed as a parameter that the function uses as an array. Function parameters shall be passed by value if scalar and by reference if array name. The number of parameters in the function definition need not match the number of parameters in the function call. Excess formal parameters can be used as local variables. If fewer arguments are supplied in a function call than are in the function definition, the extra parameters that are used in the function body as scalars shall evaluate to the uninitialized value until they are otherwise initialized, and the extra parameters that are used in the function body as arrays shall be treated as uninitialized arrays where each element evaluates to the uninitialized value until otherwise initialized. When invoking a function, no white space can be placed between the function name and the opening parenthesis. Function calls can be nested and recursive calls can be made upon functions. Upon return from any nested or recursive function call, the values of all of the calling function's parameters shall be unchanged, except for array parameters passed by reference. The return statement can be used to return a value. If a return statement appears outside of a function definition, the behavior is undefined. In the function definition, <newline> characters shall be optional before the opening brace and after the closing brace. Function definitions can appear anywhere in the program where a pattern-action pair is allowed. Grammar The grammar in this section and the lexical conventions in the following section shall together describe the syntax for awk programs. The general conventions for this style of grammar are described in Section 1.3, Grammar Conventions. A valid program can be represented as the non-terminal symbol program in the grammar. This formal syntax shall take precedence over the preceding text syntax description. %token NAME NUMBER STRING ERE %token FUNC_NAME /* Name followed by '(' without white space. */ /* Keywords */ %token Begin End /* 'BEGIN' 'END' */ %token Break Continue Delete Do Else /* 'break' 'continue' 'delete' 'do' 'else' */ %token Exit For Function If In /* 'exit' 'for' 'function' 'if' 'in' */ %token Next Print Printf Return While /* 'next' 'print' 'printf' 'return' 'while' */ /* Reserved function names */ %token BUILTIN_FUNC_NAME /* One token for the following: * atan2 cos sin exp log sqrt int rand srand * gsub index length match split sprintf sub * substr tolower toupper close system */ %token GETLINE /* Syntactically different from other built-ins. */ /* Two-character tokens. */ %token ADD_ASSIGN SUB_ASSIGN MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN POW_ASSIGN /* '+=' '-=' '*=' '/=' '%=' '^=' */ %token OR AND NO_MATCH EQ LE GE NE INCR DECR APPEND /* '||' '&&' '!~' '==' '<=' '>=' '!=' '++' '--' '>>' */ /* One-character tokens. */ %token '{' '}' '(' ')' '[' ']' ',' ';' NEWLINE %token '+' '-' '*' '%' '^' '!' '>' '<' '|' '?' ':' '~' '$' '=' %start program %% program : item_list | item_list item ; item_list : /* empty */ | item_list item terminator ; item : action | pattern action | normal_pattern | Function NAME '(' param_list_opt ')' newline_opt action | Function FUNC_NAME '(' param_list_opt ')' newline_opt action ; param_list_opt : /* empty */ | param_list ; param_list : NAME | param_list ',' NAME ; pattern : normal_pattern | special_pattern ; normal_pattern : expr | expr ',' newline_opt expr ; special_pattern : Begin | End ; action : '{' newline_opt '}' | '{' newline_opt terminated_statement_list '}' | '{' newline_opt unterminated_statement_list '}' ; terminator : terminator NEWLINE | ';' | NEWLINE ; terminated_statement_list : terminated_statement | terminated_statement_list terminated_statement ; unterminated_statement_list : unterminated_statement | terminated_statement_list unterminated_statement ; terminated_statement : action newline_opt | If '(' expr ')' newline_opt terminated_statement | If '(' expr ')' newline_opt terminated_statement Else newline_opt terminated_statement | While '(' expr ')' newline_opt terminated_statement | For '(' simple_statement_opt ';' expr_opt ';' simple_statement_opt ')' newline_opt terminated_statement | For '(' NAME In NAME ')' newline_opt terminated_statement | ';' newline_opt | terminatable_statement NEWLINE newline_opt | terminatable_statement ';' newline_opt ; unterminated_statement : terminatable_statement | If '(' expr ')' newline_opt unterminated_statement | If '(' expr ')' newline_opt terminated_statement Else newline_opt unterminated_statement | While '(' expr ')' newline_opt unterminated_statement | For '(' simple_statement_opt ';' expr_opt ';' simple_statement_opt ')' newline_opt unterminated_statement | For '(' NAME In NAME ')' newline_opt unterminated_statement ; terminatable_statement : simple_statement | Break | Continue | Next | Exit expr_opt | Return expr_opt | Do newline_opt terminated_statement While '(' expr ')' ; simple_statement_opt : /* empty */ | simple_statement ; simple_statement : Delete NAME '[' expr_list ']' | expr | print_statement ; print_statement : simple_print_statement | simple_print_statement output_redirection ; simple_print_statement : Print print_expr_list_opt | Print '(' multiple_expr_list ')' | Printf print_expr_list | Printf '(' multiple_expr_list ')' ; output_redirection : '>' expr | APPEND expr | '|' expr ; expr_list_opt : /* empty */ | expr_list ; expr_list : expr | multiple_expr_list ; multiple_expr_list : expr ',' newline_opt expr | multiple_expr_list ',' newline_opt expr ; expr_opt : /* empty */ | expr ; expr : unary_expr | non_unary_expr ; unary_expr : '+' expr | '-' expr | unary_expr '^' expr | unary_expr '*' expr | unary_expr '/' expr | unary_expr '%' expr | unary_expr '+' expr | unary_expr '-' expr | unary_expr non_unary_expr | unary_expr '<' expr | unary_expr LE expr | unary_expr NE expr | unary_expr EQ expr | unary_expr '>' expr | unary_expr GE expr | unary_expr '~' expr | unary_expr NO_MATCH expr | unary_expr In NAME | unary_expr AND newline_opt expr | unary_expr OR newline_opt expr | unary_expr '?' expr ':' expr | unary_input_function ; non_unary_expr : '(' expr ')' | '!' expr | non_unary_expr '^' expr | non_unary_expr '*' expr | non_unary_expr '/' expr | non_unary_expr '%' expr | non_unary_expr '+' expr | non_unary_expr '-' expr | non_unary_expr non_unary_expr | non_unary_expr '<' expr | non_unary_expr LE expr | non_unary_expr NE expr | non_unary_expr EQ expr | non_unary_expr '>' expr | non_unary_expr GE expr | non_unary_expr '~' expr | non_unary_expr NO_MATCH expr | non_unary_expr In NAME | '(' multiple_expr_list ')' In NAME | non_unary_expr AND newline_opt expr | non_unary_expr OR newline_opt expr | non_unary_expr '?' expr ':' expr | NUMBER | STRING | lvalue | ERE | lvalue INCR | lvalue DECR | INCR lvalue | DECR lvalue | lvalue POW_ASSIGN expr | lvalue MOD_ASSIGN expr | lvalue MUL_ASSIGN expr | lvalue DIV_ASSIGN expr | lvalue ADD_ASSIGN expr | lvalue SUB_ASSIGN expr | lvalue '=' expr | FUNC_NAME '(' expr_list_opt ')' /* no white space allowed before '(' */ | BUILTIN_FUNC_NAME '(' expr_list_opt ')' | BUILTIN_FUNC_NAME | non_unary_input_function ; print_expr_list_opt : /* empty */ | print_expr_list ; print_expr_list : print_expr | print_expr_list ',' newline_opt print_expr ; print_expr : unary_print_expr | non_unary_print_expr ; unary_print_expr : '+' print_expr | '-' print_expr | unary_print_expr '^' print_expr | unary_print_expr '*' print_expr | unary_print_expr '/' print_expr | unary_print_expr '%' print_expr | unary_print_expr '+' print_expr | unary_print_expr '-' print_expr | unary_print_expr non_unary_print_expr | unary_print_expr '~' print_expr | unary_print_expr NO_MATCH print_expr | unary_print_expr In NAME | unary_print_expr AND newline_opt print_expr | unary_print_expr OR newline_opt print_expr | unary_print_expr '?' print_expr ':' print_expr ; non_unary_print_expr : '(' expr ')' | '!' print_expr | non_unary_print_expr '^' print_expr | non_unary_print_expr '*' print_expr | non_unary_print_expr '/' print_expr | non_unary_print_expr '%' print_expr | non_unary_print_expr '+' print_expr | non_unary_print_expr '-' print_expr | non_unary_print_expr non_unary_print_expr | non_unary_print_expr '~' print_expr | non_unary_print_expr NO_MATCH print_expr | non_unary_print_expr In NAME | '(' multiple_expr_list ')' In NAME | non_unary_print_expr AND newline_opt print_expr | non_unary_print_expr OR newline_opt print_expr | non_unary_print_expr '?' print_expr ':' print_expr | NUMBER | STRING | lvalue | ERE | lvalue INCR | lvalue DECR | INCR lvalue | DECR lvalue | lvalue POW_ASSIGN print_expr | lvalue MOD_ASSIGN print_expr | lvalue MUL_ASSIGN print_expr | lvalue DIV_ASSIGN print_expr | lvalue ADD_ASSIGN print_expr | lvalue SUB_ASSIGN print_expr | lvalue '=' print_expr | FUNC_NAME '(' expr_list_opt ')' /* no white space allowed before '(' */ | BUILTIN_FUNC_NAME '(' expr_list_opt ')' | BUILTIN_FUNC_NAME ; lvalue : NAME | NAME '[' expr_list ']' | '$' expr ; non_unary_input_function : simple_get | simple_get '<' expr | non_unary_expr '|' simple_get ; unary_input_function : unary_expr '|' simple_get ; simple_get : GETLINE | GETLINE lvalue ; newline_opt : /* empty */ | newline_opt NEWLINE ; This grammar has several ambiguities that shall be resolved as follows: * Operator precedence and associativity shall be as described in Table 4-1, Expressions in Decreasing Precedence in awk. * In case of ambiguity, an else shall be associated with the most immediately preceding if that would satisfy the grammar. * In some contexts, a <slash> ('/') that is used to surround an ERE could also be the division operator. This shall be resolved in such a way that wherever the division operator could appear, a <slash> is assumed to be the division operator. (There is no unary division operator.) Each expression in an awk program shall conform to the precedence and associativity rules, even when this is not needed to resolve an ambiguity. For example, because '$' has higher precedence than '++', the string "$x++--" is not a valid awk expression, even though it is unambiguously parsed by the grammar as "$(x++)--". One convention that might not be obvious from the formal grammar is where <newline> characters are acceptable. There are several obvious placements such as terminating a statement, and a <backslash> can be used to escape <newline> characters between any lexical tokens. In addition, <newline> characters without <backslash> characters can follow a comma, an open brace, logical AND operator ("&&"), logical OR operator ("||"), the do keyword, the else keyword, and the closing parenthesis of an if, for, or while statement. For example: { print $1, $2 } Lexical Conventions The lexical conventions for awk programs, with respect to the preceding grammar, shall be as follows: 1. Except as noted, awk shall recognize the longest possible token or delimiter beginning at a given point. 2. A comment shall consist of any characters beginning with the <number-sign> character and terminated by, but excluding the next occurrence of, a <newline>. Comments shall have no effect, except to delimit lexical tokens. 3. The <newline> shall be recognized as the token NEWLINE. 4. A <backslash> character immediately followed by a <newline> shall have no effect. 5. The token STRING shall represent a string constant. A string constant shall begin with the character '"'. Within a string constant, a <backslash> character shall be considered to begin an escape sequence as specified in the table in the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v'). In addition, the escape sequences in Table 4-2, Escape Sequences in awk shall be recognized. A <newline> shall not occur within a string constant. A string constant shall be terminated by the first unescaped occurrence of the character '"' after the one that begins the string constant. The value of the string shall be the sequence of all unescaped characters and values of escape sequences between, but not including, the two delimiting '"' characters. 6. The token ERE represents an extended regular expression constant. An ERE constant shall begin with the <slash> character. Within an ERE constant, a <backslash> character shall be considered to begin an escape sequence as specified in the table in the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation. In addition, the escape sequences in Table 4-2, Escape Sequences in awk shall be recognized. The application shall ensure that a <newline> does not occur within an ERE constant. An ERE constant shall be terminated by the first unescaped occurrence of the <slash> character after the one that begins the ERE constant. The extended regular expression represented by the ERE constant shall be the sequence of all unescaped characters and values of escape sequences between, but not including, the two delimiting <slash> characters. 7. A <blank> shall have no effect, except to delimit lexical tokens or within STRING or ERE tokens. 8. The token NUMBER shall represent a numeric constant. Its form and numeric value shall either be equivalent to the decimal- floating-constant token as specified by the ISO C standard, or it shall be a sequence of decimal digits and shall be evaluated as an integer constant in decimal. In addition, implementations may accept numeric constants with the form and numeric value equivalent to the hexadecimal-constant and hexadecimal-floating-constant tokens as specified by the ISO C standard. If the value is too large or too small to be representable (see Section 1.1.2, Concepts Derived from the ISO C Standard), the behavior is undefined. 9. A sequence of underscores, digits, and alphabetics from the portable character set (see the Base Definitions volume of POSIX.12017, Section 6.1, Portable Character Set), beginning with an <underscore> or alphabetic character, shall be considered a word. 10. The following words are keywords that shall be recognized as individual tokens; the name of the token is the same as the keyword: BEGIN delete END function in printf break do exit getline next return continue else for if print while 11. The following words are names of built-in functions and shall be recognized as the token BUILTIN_FUNC_NAME: atan2 gsub log split sub toupper close index match sprintf substr cos int rand sqrt system exp length sin srand tolower The above-listed keywords and names of built-in functions are considered reserved words. 12. The token NAME shall consist of a word that is not a keyword or a name of a built-in function and is not followed immediately (without any delimiters) by the '(' character. 13. The token FUNC_NAME shall consist of a word that is not a keyword or a name of a built-in function, followed immediately (without any delimiters) by the '(' character. The '(' character shall not be included as part of the token. 14. The following two-character sequences shall be recognized as the named tokens: Token Name Sequence Token Name Sequence ADD_ASSIGN += NO_MATCH !~ SUB_ASSIGN -= EQ == MUL_ASSIGN *= LE <= DIV_ASSIGN /= GE >= MOD_ASSIGN %= NE != POW_ASSIGN ^= INCR ++ OR || DECR -- AND && APPEND >> 15. The following single characters shall be recognized as tokens whose names are the character: <newline> { } ( ) [ ] , ; + - * % ^ ! > < | ? : ~ $ = There is a lexical ambiguity between the token ERE and the tokens '/' and DIV_ASSIGN. When an input sequence begins with a <slash> character in any syntactic context where the token '/' or DIV_ASSIGN could appear as the next token in a valid program, the longer of those two tokens that can be recognized shall be recognized. In any other syntactic context where the token ERE could appear as the next token in a valid program, the token ERE shall be recognized. EXIT STATUS top The following exit values shall be returned: 0 All input files were processed successfully. >0 An error occurred. The exit status can be altered within the program by using an exit expression. CONSEQUENCES OF ERRORS top If any file operand is specified and the named file cannot be accessed, awk shall write a diagnostic message to standard error and terminate without any further action. If the program specified by either the program operand or a progfile operand is not a valid awk program (as specified in the EXTENDED DESCRIPTION section), the behavior is undefined. The following sections are informative. APPLICATION USAGE top The index, length, match, and substr functions should not be confused with similar functions in the ISO C standard; the awk versions deal with characters, while the ISO C standard deals with bytes. Because the concatenation operation is represented by adjacent expressions rather than an explicit operator, it is often necessary to use parentheses to enforce the proper evaluation precedence. When using awk to process pathnames, it is recommended that LC_ALL, or at least LC_CTYPE and LC_COLLATE, are set to POSIX or C in the environment, since pathnames can contain byte sequences that do not form valid characters in some locales, in which case the utility's behavior would be undefined. In the POSIX locale each byte is a valid single-byte character, and therefore this problem is avoided. On implementations where the "==" operator checks if strings collate equally, applications needing to check whether strings are identical can use: length(a) == length(b) && index(a,b) == 1 On implementations where the "==" operator checks if strings are identical, applications needing to check whether strings collate equally can use: a <= b && a >= b EXAMPLES top The awk program specified in the command line is most easily specified within single-quotes (for example, 'program') for applications using sh, because awk programs commonly contain characters that are special to the shell, including double- quotes. In the cases where an awk program contains single-quote characters, it is usually easiest to specify most of the program as strings within single-quotes concatenated by the shell with quoted single-quote characters. For example: awk '/'\''/ { print "quote:", $0 }' prints all lines from the standard input containing a single- quote character, prefixed with quote:. The following are examples of simple awk programs: 1. Write to the standard output all input lines for which field 3 is greater than 5: $3 > 5 2. Write every tenth line: (NR % 10) == 0 3. Write any line with a substring matching the regular expression: /(G|D)(2[0-9][[:alpha:]]*)/ 4. Print any line with a substring containing a 'G' or 'D', followed by a sequence of digits and characters. This example uses character classes digit and alpha to match language- independent digit and alphabetic characters respectively: /(G|D)([[:digit:][:alpha:]]*)/ 5. Write any line in which the second field matches the regular expression and the fourth field does not: $2 ~ /xyz/ && $4 !~ /xyz/ 6. Write any line in which the second field contains a <backslash>: $2 ~ /\\/ 7. Write any line in which the second field contains a <backslash>. Note that <backslash>-escapes are interpreted twice; once in lexical processing of the string and once in processing the regular expression: $2 ~ "\\\\" 8. Write the second to the last and the last field in each line. Separate the fields by a <colon>: {OFS=":";print $(NF-1), $NF} 9. Write the line number and number of fields in each line. The three strings representing the line number, the <colon>, and the number of fields are concatenated and that string is written to standard output: {print NR ":" NF} 10. Write lines longer than 72 characters: length($0) > 72 11. Write the first two fields in opposite order separated by OFS: { print $2, $1 } 12. Same, with input fields separated by a <comma> or <space> and <tab> characters, or both: BEGIN { FS = ",[ \t]*|[ \t]+" } { print $2, $1 } 13. Add up the first column, print sum, and average: {s += $1 } END {print "sum is ", s, " average is", s/NR} 14. Write fields in reverse order, one per line (many lines out for each line in): { for (i = NF; i > 0; --i) print $i } 15. Write all lines between occurrences of the strings start and stop: /start/, /stop/ 16. Write all lines whose first field is different from the previous one: $1 != prev { print; prev = $1 } 17. Simulate echo: BEGIN { for (i = 1; i < ARGC; ++i) printf("%s%s", ARGV[i], i==ARGC-1?"\n":" ") } 18. Write the path prefixes contained in the PATH environment variable, one per line: BEGIN { n = split (ENVIRON["PATH"], path, ":") for (i = 1; i <= n; ++i) print path[i] } 19. If there is a file named input containing page headers of the form: Page # and a file named program that contains: /Page/ { $2 = n++; } { print } then the command line: awk -f program n=5 input prints the file input, filling in page numbers starting at 5. RATIONALE top This description is based on the new awk, ``nawk'', (see the referenced The AWK Programming Language), which introduced a number of new features to the historical awk: 1. New keywords: delete, do, function, return 2. New built-in functions: atan2, close, cos, gsub, match, rand, sin, srand, sub, system 3. New predefined variables: FNR, ARGC, ARGV, RSTART, RLENGTH, SUBSEP 4. New expression operators: ?, :, ,, ^ 5. The FS variable and the third argument to split, now treated as extended regular expressions. 6. The operator precedence, changed to more closely match the C language. Two examples of code that operate differently are: while ( n /= 10 > 1) ... if (!"wk" ~ /bwk/) ... Several features have been added based on newer implementations of awk: * Multiple instances of -f progfile are permitted. * The new option -v assignment. * The new predefined variable ENVIRON. * New built-in functions toupper and tolower. * More formatting capabilities are added to printf to match the ISO C standard. Earlier versions of this standard required implementations to support multiple adjacent <semicolon>s, lines with one or more <semicolon> before a rule (pattern-action pairs), and lines with only <semicolon>(s). These are not required by this standard and are considered poor programming practice, but can be accepted by an implementation of awk as an extension. The overall awk syntax has always been based on the C language, with a few features from the shell command language and other sources. Because of this, it is not completely compatible with any other language, which has caused confusion for some users. It is not the intent of the standard developers to address such issues. A few relatively minor changes toward making the language more compatible with the ISO C standard were made; most of these changes are based on similar changes in recent implementations, as described above. There remain several C-language conventions that are not in awk. One of the notable ones is the <comma> operator, which is commonly used to specify multiple expressions in the C language for statement. Also, there are various places where awk is more restrictive than the C language regarding the type of expression that can be used in a given context. These limitations are due to the different features that the awk language does provide. Regular expressions in awk have been extended somewhat from historical implementations to make them a pure superset of extended regular expressions, as defined by POSIX.12008 (see the Base Definitions volume of POSIX.12017, Section 9.4, Extended Regular Expressions). The main extensions are internationalization features and interval expressions. Historical implementations of awk have long supported <backslash>-escape sequences as an extension to extended regular expressions, and this extension has been retained despite inconsistency with other utilities. The number of escape sequences recognized in both extended regular expressions and strings has varied (generally increasing with time) among implementations. The set specified by POSIX.12008 includes most sequences known to be supported by popular implementations and by the ISO C standard. One sequence that is not supported is hexadecimal value escapes beginning with '\x'. This would allow values expressed in more than 9 bits to be used within awk as in the ISO C standard. However, because this syntax has a non- deterministic length, it does not permit the subsequent character to be a hexadecimal digit. This limitation can be dealt with in the C language by the use of lexical string concatenation. In the awk language, concatenation could also be a solution for strings, but not for extended regular expressions (either lexical ERE tokens or strings used dynamically as regular expressions). Because of this limitation, the feature has not been added to POSIX.12008. When a string variable is used in a context where an extended regular expression normally appears (where the lexical token ERE is used in the grammar) the string does not contain the literal <slash> characters. Some versions of awk allow the form: func name(args, ... ) { statements } This has been deprecated by the authors of the language, who asked that it not be specified. Historical implementations of awk produce an error if a next statement is executed in a BEGIN action, and cause awk to terminate if a next statement is executed in an END action. This behavior has not been documented, and it was not believed that it was necessary to standardize it. The specification of conversions between string and numeric values is much more detailed than in the documentation of historical implementations or in the referenced The AWK Programming Language. Although most of the behavior is designed to be intuitive, the details are necessary to ensure compatible behavior from different implementations. This is especially important in relational expressions since the types of the operands determine whether a string or numeric comparison is performed. From the perspective of an application developer, it is usually sufficient to expect intuitive behavior and to force conversions (by adding zero or concatenating a null string) when the type of an expression does not obviously match what is needed. The intent has been to specify historical practice in almost all cases. The one exception is that, in historical implementations, variables and constants maintain both string and numeric values after their original value is converted by any use. This means that referencing a variable or constant can have unexpected side-effects. For example, with historical implementations the following program: { a = "+2" b = 2 if (NR % 2) c = a + b if (a == b) print "numeric comparison" else print "string comparison" } would perform a numeric comparison (and output numeric comparison) for each odd-numbered line, but perform a string comparison (and output string comparison) for each even-numbered line. POSIX.12008 ensures that comparisons will be numeric if necessary. With historical implementations, the following program: BEGIN { OFMT = "%e" print 3.14 OFMT = "%f" print 3.14 } would output "3.140000e+00" twice, because in the second print statement the constant "3.14" would have a string value from the previous conversion. POSIX.12008 requires that the output of the second print statement be "3.140000". The behavior of historical implementations was seen as too unintuitive and unpredictable. It was pointed out that with the rules contained in early drafts, the following script would print nothing: BEGIN { y[1.5] = 1 OFMT = "%e" print y[1.5] } Therefore, a new variable, CONVFMT, was introduced. The OFMT variable is now restricted to affecting output conversions of numbers to strings and CONVFMT is used for internal conversions, such as comparisons or array indexing. The default value is the same as that for OFMT, so unless a program changes CONVFMT (which no historical program would do), it will receive the historical behavior associated with internal string conversions. The POSIX awk lexical and syntactic conventions are specified more formally than in other sources. Again the intent has been to specify historical practice. One convention that may not be obvious from the formal grammar as in other verbal descriptions is where <newline> characters are acceptable. There are several obvious placements such as terminating a statement, and a <backslash> can be used to escape <newline> characters between any lexical tokens. In addition, <newline> characters without <backslash> characters can follow a comma, an open brace, a logical AND operator ("&&"), a logical OR operator ("||"), the do keyword, the else keyword, and the closing parenthesis of an if, for, or while statement. For example: { print $1, $2 } The requirement that awk add a trailing <newline> to the program argument text is to simplify the grammar, making it match a text file in form. There is no way for an application or test suite to determine whether a literal <newline> is added or whether awk simply acts as if it did. POSIX.12008 requires several changes from historical implementations in order to support internationalization. Probably the most subtle of these is the use of the decimal-point character, defined by the LC_NUMERIC category of the locale, in representations of floating-point numbers. This locale-specific character is used in recognizing numeric input, in converting between strings and numeric values, and in formatting output. However, regardless of locale, the <period> character (the decimal-point character of the POSIX locale) is the decimal-point character recognized in processing awk programs (including assignments in command line arguments). This is essentially the same convention as the one used in the ISO C standard. The difference is that the C language includes the setlocale() function, which permits an application to modify its locale. Because of this capability, a C application begins executing with its locale set to the C locale, and only executes in the environment-specified locale after an explicit call to setlocale(). However, adding such an elaborate new feature to the awk language was seen as inappropriate for POSIX.12008. It is possible to execute an awk program explicitly in any desired locale by setting the environment in the shell. The undefined behavior resulting from NULs in extended regular expressions allows future extensions for the GNU gawk program to process binary data. The behavior in the case of invalid awk programs (including lexical, syntactic, and semantic errors) is undefined because it was considered overly limiting on implementations to specify. In most cases such errors can be expected to produce a diagnostic and a non-zero exit status. However, some implementations may choose to extend the language in ways that make use of certain invalid constructs. Other invalid constructs might be deemed worthy of a warning, but otherwise cause some reasonable behavior. Still other constructs may be very difficult to detect in some implementations. Also, different implementations might detect a given error during an initial parsing of the program (before reading any input files) while others might detect it when executing the program after reading some input. Implementors should be aware that diagnosing errors as early as possible and producing useful diagnostics can ease debugging of applications, and thus make an implementation more usable. The unspecified behavior from using multi-character RS values is to allow possible future extensions based on extended regular expressions used for record separators. Historical implementations take the first character of the string and ignore the others. Unspecified behavior when split(string,array,<null>) is used is to allow a proposed future extension that would split up a string into an array of individual characters. In the context of the getline function, equally good arguments for different precedences of the | and < operators can be made. Historical practice has been that: getline < "a" "b" is parsed as: ( getline < "a" ) "b" although many would argue that the intent was that the file ab should be read. However: getline < "x" + 1 parses as: getline < ( "x" + 1 ) Similar problems occur with the | version of getline, particularly in combination with $. For example: $"echo hi" | getline (This situation is particularly problematic when used in a print statement, where the |getline part might be a redirection of the print.) Since in most cases such constructs are not (or at least should not) be used (because they have a natural ambiguity for which there is no conventional parsing), the meaning of these constructs has been made explicitly unspecified. (The effect is that a conforming application that runs into the problem must parenthesize to resolve the ambiguity.) There appeared to be few if any actual uses of such constructs. Grammars can be written that would cause an error under these circumstances. Where backwards-compatibility is not a large consideration, implementors may wish to use such grammars. Some historical implementations have allowed some built-in functions to be called without an argument list, the result being a default argument list chosen in some ``reasonable'' way. Use of length as a synonym for length($0) is the only one of these forms that is thought to be widely known or widely used; this particular form is documented in various places (for example, most historical awk reference pages, although not in the referenced The AWK Programming Language) as legitimate practice. With this exception, default argument lists have always been undocumented and vaguely defined, and it is not at all clear how (or if) they should be generalized to user-defined functions. They add no useful functionality and preclude possible future extensions that might need to name functions without calling them. Not standardizing them seems the simplest course. The standard developers considered that length merited special treatment, however, since it has been documented in the past and sees possibly substantial use in historical programs. Accordingly, this usage has been made legitimate, but Issue 5 removed the obsolescent marking for XSI-conforming implementations and many otherwise conforming applications depend on this feature. In sub and gsub, if repl is a string literal (the lexical token STRING), then two consecutive <backslash> characters should be used in the string to ensure a single <backslash> will precede the <ampersand> when the resultant string is passed to the function. (For example, to specify one literal <ampersand> in the replacement string, use gsub(ERE, "\\&").) Historically, the only special character in the repl argument of sub and gsub string functions was the <ampersand> ('&') character and preceding it with the <backslash> character was used to turn off its special meaning. The description in the ISO POSIX2:1993 standard introduced behavior such that the <backslash> character was another special character and it was unspecified whether there were any other special characters. This description introduced several portability problems, some of which are described below, and so it has been replaced with the more historical description. Some of the problems include: * Historically, to create the replacement string, a script could use gsub(ERE, "\\&"), but with the ISO POSIX2:1993 standard wording, it was necessary to use gsub(ERE, "\\\\&"). The <backslash> characters are doubled here because all string literals are subject to lexical analysis, which would reduce each pair of <backslash> characters to a single <backslash> before being passed to gsub. * Since it was unspecified what the special characters were, for portable scripts to guarantee that characters are printed literally, each character had to be preceded with a <backslash>. (For example, a portable script had to use gsub(ERE, "\\h\\i") to produce a replacement string of "hi".) The description for comparisons in the ISO POSIX2:1993 standard did not properly describe historical practice because of the way numeric strings are compared as numbers. The current rules cause the following code: if (0 == "000") print "strange, but true" else print "not true" to do a numeric comparison, causing the if to succeed. It should be intuitively obvious that this is incorrect behavior, and indeed, no historical implementation of awk actually behaves this way. To fix this problem, the definition of numeric string was enhanced to include only those values obtained from specific circumstances (mostly external sources) where it is not possible to determine unambiguously whether the value is intended to be a string or a numeric. Variables that are assigned to a numeric string shall also be treated as a numeric string. (For example, the notion of a numeric string can be propagated across assignments.) In comparisons, all variables having the uninitialized value are to be treated as a numeric operand evaluating to the numeric value zero. Uninitialized variables include all types of variables including scalars, array elements, and fields. The definition of an uninitialized value in Variables and Special Variables is necessary to describe the value placed on uninitialized variables and on fields that are valid (for example, < $NF) but have no characters in them and to describe how these variables are to be used in comparisons. A valid field, such as $1, that has no characters in it can be obtained from an input line of "\t\t" when FS='\t'. Historically, the comparison ($1<10) was done numerically after evaluating $1 to the value zero. The phrase ``... also shall have the numeric value of the numeric string'' was removed from several sections of the ISO POSIX2:1993 standard because is specifies an unnecessary implementation detail. It is not necessary for POSIX.12008 to specify that these objects be assigned two different values. It is only necessary to specify that these objects may evaluate to two different values depending on context. Historical implementations of awk did not parse hexadecimal integer or floating constants like "0xa" and "0xap0". Due to an oversight, the 2001 through 2004 editions of this standard required support for hexadecimal floating constants. This was due to the reference to atof(). This version of the standard allows but does not require implementations to use atof() and includes a description of how floating-point numbers are recognized as an alternative to match historic behavior. The intent of this change is to allow implementations to recognize floating-point constants according to either the ISO/IEC 9899:1990 standard or ISO/IEC 9899:1999 standard, and to allow (but not require) implementations to recognize hexadecimal integer constants. Historical implementations of awk did not support floating-point infinities and NaNs in numeric strings; e.g., "-INF" and "NaN". However, implementations that use the atof() or strtod() functions to do the conversion picked up support for these values if they used a ISO/IEC 9899:1999 standard version of the function instead of a ISO/IEC 9899:1990 standard version. Due to an oversight, the 2001 through 2004 editions of this standard did not allow support for infinities and NaNs, but in this revision support is allowed (but not required). This is a silent change to the behavior of awk programs; for example, in the POSIX locale the expression: ("-INF" + 0 < 0) formerly had the value 0 because "-INF" converted to 0, but now it may have the value 0 or 1. FUTURE DIRECTIONS top A future version of this standard may require the "!=" and "==" operators to perform string comparisons by checking if the strings are identical (and not by checking if they collate equally). SEE ALSO top Section 1.3, Grammar Conventions, grep(1p), lex(1p), sed(1p) The Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation, Section 6.1, Portable Character Set, Chapter 8, Environment Variables, Chapter 9, Regular Expressions, Section 12.2, Utility Syntax Guidelines The System Interfaces volume of POSIX.12017, atof(3p), exec(1p), isspace(3p), popen(3p), setlocale(3p), strtod(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 AWK(1P) Pages that refer to this page: bc(1p), colrm(1), join(1p), printf(1p), sed(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. du(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training du(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | PATTERNS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON DU(1) User Commands DU(1) NAME top du - estimate file space usage SYNOPSIS top du [OPTION]... [FILE]... du [OPTION]... --files0-from=F DESCRIPTION top Summarize device usage of the set of FILEs, recursively for directories. Mandatory arguments to long options are mandatory for short options too. -0, --null end each output line with NUL, not newline -a, --all write counts for all files, not just directories --apparent-size print apparent sizes rather than device usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files, internal fragmentation, indirect blocks, and the like -B, --block-size=SIZE scale sizes by SIZE before printing them; e.g., '-BM' prints sizes in units of 1,048,576 bytes; see SIZE format below -b, --bytes equivalent to '--apparent-size --block-size=1' -c, --total produce a grand total -D, --dereference-args dereference only symlinks that are listed on the command line -d, --max-depth=N print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument; --max-depth=0 is the same as --summarize --files0-from=F summarize device usage of the NUL-terminated file names specified in file F; if F is -, then read names from standard input -H equivalent to --dereference-args (-D) -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G) --inodes list inode usage information instead of block usage -k like --block-size=1K -L, --dereference dereference all symbolic links -l, --count-links count sizes many times if hard linked -m like --block-size=1M -P, --no-dereference don't follow any symbolic links (this is the default) -S, --separate-dirs for directories do not include size of subdirectories --si like -h, but use powers of 1000 not 1024 -s, --summarize display only a total for each argument -t, --threshold=SIZE exclude entries smaller than SIZE if positive, or entries greater than SIZE if negative --time show time of the last modification of any file in the directory, or any of its subdirectories --time=WORD show time as WORD instead of modification time: atime, access, use, ctime or status --time-style=STYLE show times using STYLE, which can be: full-iso, long-iso, iso, or +FORMAT; FORMAT is interpreted like in 'date' -X, --exclude-from=FILE exclude files that match any pattern in FILE --exclude=PATTERN exclude files that match PATTERN -x, --one-file-system skip directories on different file systems --help display this help and exit --version output version information and exit Display values are in units of the first available SIZE from --block-size, and the DU_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables. Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set). The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. PATTERNS top PATTERN is a shell pattern (not a regular expression). The pattern ? matches any one character, whereas * matches any string (composed of zero, one or multiple characters). For example, *.o will match any files whose names end in .o. Therefore, the command du --exclude='*.o' will skip all files and subdirectories ending in .o (including the file .o itself). AUTHOR top Written by Torbjorn Granlund, David MacKenzie, Paul Eggert, 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 Full documentation <https://www.gnu.org/software/coreutils/du> or available locally via: info '(coreutils) du 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 DU(1) Pages that refer to this page: tmpfs(5), 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: show the sum of disk used by all the files that belong to the user "test1" in the entire file system Bash Command:<START>find / -user test1 -exec du -sm {} \;|awk '{s+=$1}END{print s}'<END>
simulate a full login of user builder
su -l builder
['su']
Output a Bash command to accomplish the following task. Task: simulate a full login of user builder Bash Command:<START>su -l builder<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # su\n\n> Switch shell to another user.\n> More information: <https://manned.org/su>.\n\n- Switch to superuser (requires the root password):\n\n`su`\n\n- Switch to a given user (requires the user's password):\n\n`su {{username}}`\n\n- Switch to a given user and simulate a full login shell:\n\n`su - {{username}}`\n\n- Execute a command as another user:\n\n`su - {{username}} -c "{{command}}"`\n Task: simulate a full login of user builder Bash Command:<START>su -l builder<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: su(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training Another version of this page is provided by the shadow-utils project su(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | SIGNALS | CONFIG FILES | EXIT STATUS | FILES | NOTES | HISTORY | SEE ALSO | REPORTING BUGS | AVAILABILITY SU(1) User Commands SU(1) NAME top su - run a command with substitute user and group ID SYNOPSIS top su [options] [-] [user [argument...]] DESCRIPTION top su allows commands to be run with a substitute user and group ID. When called with no user specified, su defaults to running an interactive shell as root. When user is specified, additional arguments can be supplied, in which case they are passed to the shell. For backward compatibility, su defaults to not change the current directory and to only set the environment variables HOME and SHELL (plus USER and LOGNAME if the target user is not root). It is recommended to always use the --login option (instead of its shortcut -) to avoid side effects caused by mixing environments. This version of su uses PAM for authentication, account and session management. Some configuration options found in other su implementations, such as support for a wheel group, have to be configured via PAM. su is mostly designed for unprivileged users, the recommended solution for privileged users (e.g., scripts executed by root) is to use non-set-user-ID command runuser(1) that does not require authentication and provides separate PAM configuration. If the PAM session is not required at all then the recommended solution is to use command setpriv(1). Note that su in all cases uses PAM (pam_getenvlist(3)) to do the final environment modification. Command-line options such as --login and --preserve-environment affect the environment before it is modified by PAM. Since version 2.38 su resets process resource limits RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_FSIZE, RLIMIT_AS and RLIMIT_NOFILE. OPTIONS top -c, --command=command Pass command to the shell with the -c option. -f, --fast Pass -f to the shell, which may or may not be useful, depending on the shell. -g, --group=group Specify the primary group. This option is available to the root user only. -G, --supp-group=group Specify a supplementary group. This option is available to the root user only. The first specified supplementary group is also used as a primary group if the option --group is not specified. -, -l, --login Start the shell as a login shell with an environment similar to a real login: clears all the environment variables except TERM and variables specified by --whitelist-environment initializes the environment variables HOME, SHELL, USER, LOGNAME, and PATH changes to the target users home directory sets argv[0] of the shell to '-' in order to make the shell a login shell -m, -p, --preserve-environment Preserve the entire environment, i.e., do not set HOME, SHELL, USER or LOGNAME. This option is ignored if the option --login is specified. -P, --pty Create a pseudo-terminal for the session. The independent terminal provides better security as the user does not share a terminal with the original session. This can be used to avoid TIOCSTI ioctl terminal injection and other security attacks against terminal file descriptors. The entire session can also be moved to the background (e.g., su --pty - username -c application &). If the pseudo-terminal is enabled, then su works as a proxy between the sessions (sync stdin and stdout). This feature is mostly designed for interactive sessions. If the standard input is not a terminal, but for example a pipe (e.g., echo "date" | su --pty), then the ECHO flag for the pseudo-terminal is disabled to avoid messy output. -s, --shell=shell Run the specified shell instead of the default. The shell to run is selected according to the following rules, in order: the shell specified with --shell the shell specified in the environment variable SHELL, if the --preserve-environment option is used the shell listed in the passwd entry of the target user /bin/sh If the target user has a restricted shell (i.e., not listed in /etc/shells), the --shell option and the SHELL environment variables are ignored unless the calling user is root. --session-command=command Same as -c, but do not create a new session. (Discouraged.) -w, --whitelist-environment=list Dont reset the environment variables specified in the comma-separated list when clearing the environment for --login. The whitelist is ignored for the environment variables HOME, SHELL, USER, LOGNAME, and PATH. -h, --help Display help text and exit. -V, --version Print version and exit. SIGNALS top Upon receiving either SIGINT, SIGQUIT or SIGTERM, su terminates its child and afterwards terminates itself with the received signal. The child is terminated by SIGTERM, after unsuccessful attempt and 2 seconds of delay the child is killed by SIGKILL. CONFIG FILES top su reads the /etc/default/su and /etc/login.defs configuration files. The following configuration items are relevant for su: FAIL_DELAY (number) Delay in seconds in case of an authentication failure. The number must be a non-negative integer. ENV_PATH (string) Defines the PATH environment variable for a regular user. The default value is /usr/local/bin:/bin:/usr/bin. ENV_ROOTPATH (string), ENV_SUPATH (string) Defines the PATH environment variable for root. ENV_SUPATH takes precedence. The default value is /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin. ALWAYS_SET_PATH (boolean) If set to yes and --login and --preserve-environment were not specified su initializes PATH. The environment variable PATH may be different on systems where /bin and /sbin are merged into /usr; this variable is also affected by the --login command-line option and the PAM system setting (e.g., pam_env(8)). EXIT STATUS top su normally returns the exit status of the command it executed. If the command was killed by a signal, su returns the number of the signal plus 128. Exit status generated by su itself: 1 Generic error before executing the requested command 126 The requested command could not be executed 127 The requested command was not found FILES top /etc/pam.d/su default PAM configuration file /etc/pam.d/su-l PAM configuration file if --login is specified /etc/default/su command specific logindef config file /etc/login.defs global logindef config file NOTES top For security reasons, su always logs failed log-in attempts to the btmp file, but it does not write to the lastlog file at all. This solution can be used to control su behavior by PAM configuration. If you want to use the pam_lastlog(8) module to print warning message about failed log-in attempts then pam_lastlog(8) has to be configured to update the lastlog file as well. For example by: session required pam_lastlog.so nowtmp HISTORY top This su command was derived from coreutils' su, which was based on an implementation by David MacKenzie. The util-linux version has been refactored by Karel Zak. SEE ALSO top setpriv(1), login.defs(5), shells(5), pam(8), runuser(1) REPORTING BUGS top For bug reports, use the issue tracker at https://github.com/util-linux/util-linux/issues. AVAILABILITY top The su 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 SU(1) Pages that refer to this page: flock(1), homectl(1), login(1), login(1@@shadow-utils), machinectl(1), newgrp(1), runuser(1), setpriv(1), sg(1), updatedb(1), pam(3), pts(4), crontab(5), login.defs(5), passwd(5), passwd(5@@shadow-utils), shadow(5), suauth(5), credentials(7), environ(7), PAM(8), pam_rootok(8), pam_xauth(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: simulate a full login of user builder Bash Command:<START>su -l builder<END>
simulate a full login of user root
su -
['su']
Output a Bash command to accomplish the following task. Task: simulate a full login of user root Bash Command:<START>su -<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # su\n\n> Switch shell to another user.\n> More information: <https://manned.org/su>.\n\n- Switch to superuser (requires the root password):\n\n`su`\n\n- Switch to a given user (requires the user's password):\n\n`su {{username}}`\n\n- Switch to a given user and simulate a full login shell:\n\n`su - {{username}}`\n\n- Execute a command as another user:\n\n`su - {{username}} -c "{{command}}"`\n Task: simulate a full login of user root Bash Command:<START>su -<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: su(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training Another version of this page is provided by the shadow-utils project su(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | SIGNALS | CONFIG FILES | EXIT STATUS | FILES | NOTES | HISTORY | SEE ALSO | REPORTING BUGS | AVAILABILITY SU(1) User Commands SU(1) NAME top su - run a command with substitute user and group ID SYNOPSIS top su [options] [-] [user [argument...]] DESCRIPTION top su allows commands to be run with a substitute user and group ID. When called with no user specified, su defaults to running an interactive shell as root. When user is specified, additional arguments can be supplied, in which case they are passed to the shell. For backward compatibility, su defaults to not change the current directory and to only set the environment variables HOME and SHELL (plus USER and LOGNAME if the target user is not root). It is recommended to always use the --login option (instead of its shortcut -) to avoid side effects caused by mixing environments. This version of su uses PAM for authentication, account and session management. Some configuration options found in other su implementations, such as support for a wheel group, have to be configured via PAM. su is mostly designed for unprivileged users, the recommended solution for privileged users (e.g., scripts executed by root) is to use non-set-user-ID command runuser(1) that does not require authentication and provides separate PAM configuration. If the PAM session is not required at all then the recommended solution is to use command setpriv(1). Note that su in all cases uses PAM (pam_getenvlist(3)) to do the final environment modification. Command-line options such as --login and --preserve-environment affect the environment before it is modified by PAM. Since version 2.38 su resets process resource limits RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_FSIZE, RLIMIT_AS and RLIMIT_NOFILE. OPTIONS top -c, --command=command Pass command to the shell with the -c option. -f, --fast Pass -f to the shell, which may or may not be useful, depending on the shell. -g, --group=group Specify the primary group. This option is available to the root user only. -G, --supp-group=group Specify a supplementary group. This option is available to the root user only. The first specified supplementary group is also used as a primary group if the option --group is not specified. -, -l, --login Start the shell as a login shell with an environment similar to a real login: clears all the environment variables except TERM and variables specified by --whitelist-environment initializes the environment variables HOME, SHELL, USER, LOGNAME, and PATH changes to the target users home directory sets argv[0] of the shell to '-' in order to make the shell a login shell -m, -p, --preserve-environment Preserve the entire environment, i.e., do not set HOME, SHELL, USER or LOGNAME. This option is ignored if the option --login is specified. -P, --pty Create a pseudo-terminal for the session. The independent terminal provides better security as the user does not share a terminal with the original session. This can be used to avoid TIOCSTI ioctl terminal injection and other security attacks against terminal file descriptors. The entire session can also be moved to the background (e.g., su --pty - username -c application &). If the pseudo-terminal is enabled, then su works as a proxy between the sessions (sync stdin and stdout). This feature is mostly designed for interactive sessions. If the standard input is not a terminal, but for example a pipe (e.g., echo "date" | su --pty), then the ECHO flag for the pseudo-terminal is disabled to avoid messy output. -s, --shell=shell Run the specified shell instead of the default. The shell to run is selected according to the following rules, in order: the shell specified with --shell the shell specified in the environment variable SHELL, if the --preserve-environment option is used the shell listed in the passwd entry of the target user /bin/sh If the target user has a restricted shell (i.e., not listed in /etc/shells), the --shell option and the SHELL environment variables are ignored unless the calling user is root. --session-command=command Same as -c, but do not create a new session. (Discouraged.) -w, --whitelist-environment=list Dont reset the environment variables specified in the comma-separated list when clearing the environment for --login. The whitelist is ignored for the environment variables HOME, SHELL, USER, LOGNAME, and PATH. -h, --help Display help text and exit. -V, --version Print version and exit. SIGNALS top Upon receiving either SIGINT, SIGQUIT or SIGTERM, su terminates its child and afterwards terminates itself with the received signal. The child is terminated by SIGTERM, after unsuccessful attempt and 2 seconds of delay the child is killed by SIGKILL. CONFIG FILES top su reads the /etc/default/su and /etc/login.defs configuration files. The following configuration items are relevant for su: FAIL_DELAY (number) Delay in seconds in case of an authentication failure. The number must be a non-negative integer. ENV_PATH (string) Defines the PATH environment variable for a regular user. The default value is /usr/local/bin:/bin:/usr/bin. ENV_ROOTPATH (string), ENV_SUPATH (string) Defines the PATH environment variable for root. ENV_SUPATH takes precedence. The default value is /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin. ALWAYS_SET_PATH (boolean) If set to yes and --login and --preserve-environment were not specified su initializes PATH. The environment variable PATH may be different on systems where /bin and /sbin are merged into /usr; this variable is also affected by the --login command-line option and the PAM system setting (e.g., pam_env(8)). EXIT STATUS top su normally returns the exit status of the command it executed. If the command was killed by a signal, su returns the number of the signal plus 128. Exit status generated by su itself: 1 Generic error before executing the requested command 126 The requested command could not be executed 127 The requested command was not found FILES top /etc/pam.d/su default PAM configuration file /etc/pam.d/su-l PAM configuration file if --login is specified /etc/default/su command specific logindef config file /etc/login.defs global logindef config file NOTES top For security reasons, su always logs failed log-in attempts to the btmp file, but it does not write to the lastlog file at all. This solution can be used to control su behavior by PAM configuration. If you want to use the pam_lastlog(8) module to print warning message about failed log-in attempts then pam_lastlog(8) has to be configured to update the lastlog file as well. For example by: session required pam_lastlog.so nowtmp HISTORY top This su command was derived from coreutils' su, which was based on an implementation by David MacKenzie. The util-linux version has been refactored by Karel Zak. SEE ALSO top setpriv(1), login.defs(5), shells(5), pam(8), runuser(1) REPORTING BUGS top For bug reports, use the issue tracker at https://github.com/util-linux/util-linux/issues. AVAILABILITY top The su 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 SU(1) Pages that refer to this page: flock(1), homectl(1), login(1), login(1@@shadow-utils), machinectl(1), newgrp(1), runuser(1), setpriv(1), sg(1), updatedb(1), pam(3), pts(4), crontab(5), login.defs(5), passwd(5), passwd(5@@shadow-utils), shadow(5), suauth(5), credentials(7), environ(7), PAM(8), pam_rootok(8), pam_xauth(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: simulate a full login of user root Bash Command:<START>su -<END>
sleep for 1 second
sleep 1
['sleep']
Output a Bash command to accomplish the following task. Task: sleep for 1 second Bash Command:<START>sleep 1<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # sleep\n\n> Delay for a specified amount of time.\n> More information: <https://www.gnu.org/software/coreutils/sleep>.\n\n- Delay in seconds:\n\n`sleep {{seconds}}`\n\n- Delay in [m]inutes. (Other units [d]ay, [h]our, [s]econd, [inf]inity can also be used):\n\n`sleep {{minutes}}m`\n\n- Delay for 1 [d]ay 3 [h]ours:\n\n`sleep 1d 3h`\n\n- Execute a specific command after 20 [m]inutes delay:\n\n`sleep 20m && {{command}}`\n Task: sleep for 1 second Bash Command:<START>sleep 1<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: sleep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sleep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SLEEP(1) User Commands SLEEP(1) NAME top sleep - delay for a specified amount of time SYNOPSIS top sleep NUMBER[SUFFIX]... sleep OPTION DESCRIPTION top Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. NUMBER need not be an integer. Given two or more arguments, pause for the amount of time specified by the sum of their values. --help display this help and exit --version output version information and exit AUTHOR top Written by Jim Meyering 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 sleep(3) Full documentation <https://www.gnu.org/software/coreutils/sleep> or available locally via: info '(coreutils) sleep 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 SLEEP(1) Pages that refer to this page: dbpmda(1), pmsleep(1), ioctl_ns(2), sleep(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: sleep for 1 second Bash Command:<START>sleep 1<END>
sleep for 10 seconds
sleep 10
['sleep']
Output a Bash command to accomplish the following task. Task: sleep for 10 seconds Bash Command:<START>sleep 10<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # sleep\n\n> Delay for a specified amount of time.\n> More information: <https://www.gnu.org/software/coreutils/sleep>.\n\n- Delay in seconds:\n\n`sleep {{seconds}}`\n\n- Delay in [m]inutes. (Other units [d]ay, [h]our, [s]econd, [inf]inity can also be used):\n\n`sleep {{minutes}}m`\n\n- Delay for 1 [d]ay 3 [h]ours:\n\n`sleep 1d 3h`\n\n- Execute a specific command after 20 [m]inutes delay:\n\n`sleep 20m && {{command}}`\n Task: sleep for 10 seconds Bash Command:<START>sleep 10<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: sleep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sleep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SLEEP(1) User Commands SLEEP(1) NAME top sleep - delay for a specified amount of time SYNOPSIS top sleep NUMBER[SUFFIX]... sleep OPTION DESCRIPTION top Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. NUMBER need not be an integer. Given two or more arguments, pause for the amount of time specified by the sum of their values. --help display this help and exit --version output version information and exit AUTHOR top Written by Jim Meyering 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 sleep(3) Full documentation <https://www.gnu.org/software/coreutils/sleep> or available locally via: info '(coreutils) sleep 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 SLEEP(1) Pages that refer to this page: dbpmda(1), pmsleep(1), ioctl_ns(2), sleep(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: sleep for 10 seconds Bash Command:<START>sleep 10<END>
sleep for 5 seconds
sleep 5
['sleep']
Output a Bash command to accomplish the following task. Task: sleep for 5 seconds Bash Command:<START>sleep 5<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # sleep\n\n> Delay for a specified amount of time.\n> More information: <https://www.gnu.org/software/coreutils/sleep>.\n\n- Delay in seconds:\n\n`sleep {{seconds}}`\n\n- Delay in [m]inutes. (Other units [d]ay, [h]our, [s]econd, [inf]inity can also be used):\n\n`sleep {{minutes}}m`\n\n- Delay for 1 [d]ay 3 [h]ours:\n\n`sleep 1d 3h`\n\n- Execute a specific command after 20 [m]inutes delay:\n\n`sleep 20m && {{command}}`\n Task: sleep for 5 seconds Bash Command:<START>sleep 5<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: sleep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sleep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SLEEP(1) User Commands SLEEP(1) NAME top sleep - delay for a specified amount of time SYNOPSIS top sleep NUMBER[SUFFIX]... sleep OPTION DESCRIPTION top Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. NUMBER need not be an integer. Given two or more arguments, pause for the amount of time specified by the sum of their values. --help display this help and exit --version output version information and exit AUTHOR top Written by Jim Meyering 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 sleep(3) Full documentation <https://www.gnu.org/software/coreutils/sleep> or available locally via: info '(coreutils) sleep 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 SLEEP(1) Pages that refer to this page: dbpmda(1), pmsleep(1), ioctl_ns(2), sleep(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: sleep for 5 seconds Bash Command:<START>sleep 5<END>
sleep for 500 seconds
sleep 500
['sleep']
Output a Bash command to accomplish the following task. Task: sleep for 500 seconds Bash Command:<START>sleep 500<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # sleep\n\n> Delay for a specified amount of time.\n> More information: <https://www.gnu.org/software/coreutils/sleep>.\n\n- Delay in seconds:\n\n`sleep {{seconds}}`\n\n- Delay in [m]inutes. (Other units [d]ay, [h]our, [s]econd, [inf]inity can also be used):\n\n`sleep {{minutes}}m`\n\n- Delay for 1 [d]ay 3 [h]ours:\n\n`sleep 1d 3h`\n\n- Execute a specific command after 20 [m]inutes delay:\n\n`sleep 20m && {{command}}`\n Task: sleep for 500 seconds Bash Command:<START>sleep 500<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: sleep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sleep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SLEEP(1) User Commands SLEEP(1) NAME top sleep - delay for a specified amount of time SYNOPSIS top sleep NUMBER[SUFFIX]... sleep OPTION DESCRIPTION top Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. NUMBER need not be an integer. Given two or more arguments, pause for the amount of time specified by the sum of their values. --help display this help and exit --version output version information and exit AUTHOR top Written by Jim Meyering 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 sleep(3) Full documentation <https://www.gnu.org/software/coreutils/sleep> or available locally via: info '(coreutils) sleep 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 SLEEP(1) Pages that refer to this page: dbpmda(1), pmsleep(1), ioctl_ns(2), sleep(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: sleep for 500 seconds Bash Command:<START>sleep 500<END>
sort and display the unique lines display the contents of all the files that have been modified in the last 91 days and not in the last 2 days
find . -name "*.txt" -type f -daystart -mtime -91 -mtime +2 | xargs cat | sort | uniq
['find', 'cat', 'xargs', 'sort', 'uniq']
Output a Bash command to accomplish the following task. Task: sort and display the unique lines display the contents of all the files that have been modified in the last 91 days and not in the last 2 days Bash Command:<START>find . -name "*.txt" -type f -daystart -mtime -91 -mtime +2 | xargs cat | sort | uniq<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 # 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 # 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: sort and display the unique lines display the contents of all the files that have been modified in the last 91 days and not in the last 2 days Bash Command:<START>find . -name "*.txt" -type f -daystart -mtime -91 -mtime +2 | xargs cat | sort | uniq<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. 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. 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: sort and display the unique lines display the contents of all the files that have been modified in the last 91 days and not in the last 2 days Bash Command:<START>find . -name "*.txt" -type f -daystart -mtime -91 -mtime +2 | xargs cat | sort | uniq<END>
sort and display top 11 files along with the last access date for all the files in the file system ( sort based on the timestamp )
find / -type f -printf "\n%AD %AT %p" | head -n 11 | sort -k1.8n -k1.1nr -k1
['find', 'head', 'sort']
Output a Bash command to accomplish the following task. Task: sort and display top 11 files along with the last access date for all the files in the file system ( sort based on the timestamp ) Bash Command:<START>find / -type f -printf "\n%AD %AT %p" | head -n 11 | sort -k1.8n -k1.1nr -k1<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 # head\n\n> Output the first part of files.\n> More information: <https://www.gnu.org/software/coreutils/head>.\n\n- Output the first few lines of a file:\n\n`head --lines {{count}} {{path/to/file}}`\n\n- Output the first few bytes of a file:\n\n`head --bytes {{count}} {{path/to/file}}`\n\n- Output everything but the last few lines of a file:\n\n`head --lines -{{count}} {{path/to/file}}`\n\n- Output everything but the last few bytes of a file:\n\n`head --bytes -{{count}} {{path/to/file}}`\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 Task: sort and display top 11 files along with the last access date for all the files in the file system ( sort based on the timestamp ) Bash Command:<START>find / -type f -printf "\n%AD %AT %p" | head -n 11 | sort -k1.8n -k1.1nr -k1<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. head(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training head(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON HEAD(1) User Commands HEAD(1) NAME top head - output the first part of files SYNOPSIS top head [OPTION]... [FILE]... DESCRIPTION top Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -c, --bytes=[-]NUM print the first NUM bytes of each file; with the leading '-', print all but the last NUM bytes of each file -n, --lines=[-]NUM print the first NUM lines instead of the first 10; with the leading '-', print all but the last NUM lines of each file -q, --quiet, --silent never print headers giving file names -v, --verbose always print headers giving file names -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit NUM may have a multiplier suffix: b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. 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 tail(1) Full documentation <https://www.gnu.org/software/coreutils/head> or available locally via: info '(coreutils) head 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 HEAD(1) Pages that refer to this page: tail(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. 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. Task: sort and display top 11 files along with the last access date for all the files in the file system ( sort based on the timestamp ) Bash Command:<START>find / -type f -printf "\n%AD %AT %p" | head -n 11 | sort -k1.8n -k1.1nr -k1<END>
sort based on size and display top ten largest normal/regular files in the current folder
find . -type f -exec ls -s {} \; | sort -n -r | head -10
['find', 'ls', 'head', 'sort']
Output a Bash command to accomplish the following task. Task: sort based on size and display top ten largest normal/regular files in the current folder Bash Command:<START>find . -type f -exec ls -s {} \; | sort -n -r | head -10<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 # ls\n\n> List directory contents.\n> More information: <https://www.gnu.org/software/coreutils/ls>.\n\n- List files one per line:\n\n`ls -1`\n\n- List all files, including hidden files:\n\n`ls -a`\n\n- List all files, with trailing `/` added to directory names:\n\n`ls -F`\n\n- Long format list (permissions, ownership, size, and modification date) of all files:\n\n`ls -la`\n\n- Long format list with size displayed using human-readable units (KiB, MiB, GiB):\n\n`ls -lh`\n\n- Long format list sorted by size (descending) recursively:\n\n`ls -lSR`\n\n- Long format list of all files, sorted by modification date (oldest first):\n\n`ls -ltr`\n\n- Only list directories:\n\n`ls -d */`\n # head\n\n> Output the first part of files.\n> More information: <https://www.gnu.org/software/coreutils/head>.\n\n- Output the first few lines of a file:\n\n`head --lines {{count}} {{path/to/file}}`\n\n- Output the first few bytes of a file:\n\n`head --bytes {{count}} {{path/to/file}}`\n\n- Output everything but the last few lines of a file:\n\n`head --lines -{{count}} {{path/to/file}}`\n\n- Output everything but the last few bytes of a file:\n\n`head --bytes -{{count}} {{path/to/file}}`\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 Task: sort based on size and display top ten largest normal/regular files in the current folder Bash Command:<START>find . -type f -exec ls -s {} \; | sort -n -r | head -10<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. ls(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ls(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON LS(1) User Commands LS(1) NAME top ls - list directory contents SYNOPSIS top ls [OPTION]... [FILE]... DESCRIPTION top List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. Mandatory arguments to long options are mandatory for short options too. -a, --all do not ignore entries starting with . -A, --almost-all do not list implied . and .. --author with -l, print the author of each file -b, --escape print C-style escapes for nongraphic characters --block-size=SIZE with -l, scale sizes by SIZE when printing them; e.g., '--block-size=M'; see SIZE format below -B, --ignore-backups do not list implied entries ending with ~ -c with -lt: sort by, and show, ctime (time of last change of file status information); with -l: show ctime and sort by name; otherwise: sort by ctime, newest first -C list entries by columns --color[=WHEN] color the output WHEN; more info below -d, --directory list directories themselves, not their contents -D, --dired generate output designed for Emacs' dired mode -f list all entries in directory order -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN --file-type likewise, except do not append '*' --format=WORD across -x, commas -m, horizontal -x, long -l, single-column -1, verbose -l, vertical -C --full-time like -l --time-style=full-iso -g like -l, but do not list owner --group-directories-first group directories before files; can be augmented with a --sort option, but any use of --sort=none (-U) disables grouping -G, --no-group in a long listing, don't print group names -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc. --si likewise, but use powers of 1000 not 1024 -H, --dereference-command-line follow symbolic links listed on the command line --dereference-command-line-symlink-to-dir follow each command line symbolic link that points to a directory --hide=PATTERN do not list implied entries matching shell PATTERN (overridden by -a or -A) --hyperlink[=WHEN] hyperlink file names WHEN --indicator-style=WORD append indicator with style WORD to entry names: none (default), slash (-p), file-type (--file-type), classify (-F) -i, --inode print the index number of each file -I, --ignore=PATTERN do not list implied entries matching shell PATTERN -k, --kibibytes default to 1024-byte blocks for file system usage; used only with -s and per directory totals -l use a long listing format -L, --dereference when showing file information for a symbolic link, show information for the file the link references rather than for the link itself -m fill width with a comma separated list of entries -n, --numeric-uid-gid like -l, but list numeric user and group IDs -N, --literal print entry names without quoting -o like -l, but do not list group information -p, --indicator-style=slash append / indicator to directories -q, --hide-control-chars print ? instead of nongraphic characters --show-control-chars show nongraphic characters as-is (the default, unless program is 'ls' and output is a terminal) -Q, --quote-name enclose entry names in double quotes --quoting-style=WORD use quoting style WORD for entry names: literal, locale, shell, shell-always, shell-escape, shell-escape-always, c, escape (overrides QUOTING_STYLE environment variable) -r, --reverse reverse order while sorting -R, --recursive list subdirectories recursively -s, --size print the allocated size of each file, in blocks -S sort by file size, largest first --sort=WORD sort by WORD instead of name: none (-U), size (-S), time (-t), version (-v), extension (-X), width --time=WORD select which timestamp used to display or sort; access time (-u): atime, access, use; metadata change time (-c): ctime, status; modified time (default): mtime, modification; birth time: birth, creation; with -l, WORD determines which time to show; with --sort=time, sort by WORD (newest first) --time-style=TIME_STYLE time/date format with -l; see TIME_STYLE below -t sort by time, newest first; see --time -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u with -lt: sort by, and show, access time; with -l: show access time and sort by name; otherwise: sort by access time, newest first -U do not sort; list entries in directory order -v natural sort of (version) numbers within text -w, --width=COLS set output width to COLS. 0 means no limit -x list entries by lines instead of by columns -X sort alphabetically by entry extension -Z, --context print any security context of each file --zero end each output line with NUL, not newline -1 list one file per line --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT. FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2, then FORMAT1 applies to non-recent files and FORMAT2 to recent files. TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale. Also the TIME_STYLE environment variable sets the default style to use. The WHEN argument defaults to 'always' and can also be 'auto' or 'never'. Using color to distinguish file types is disabled both by default and with --color=never. With --color=auto, ls emits color codes only when standard output is connected to a terminal. The LS_COLORS environment variable can change the settings. Use the dircolors(1) command to set it. Exit status: 0 if OK, 1 if minor problems (e.g., cannot access subdirectory), 2 if serious trouble (e.g., cannot access command-line argument). 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 dircolors(1) Full documentation <https://www.gnu.org/software/coreutils/ls> or available locally via: info '(coreutils) ls 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 LS(1) Pages that refer to this page: column(1), find(1), namei(1), stat(2), statx(2), glob(3), strverscmp(3), core(5), dir_colors(5), passwd(5), proc(5), mq_overview(7), symlink(7), lsblk(8), lsof(8), setfiles(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. head(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training head(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON HEAD(1) User Commands HEAD(1) NAME top head - output the first part of files SYNOPSIS top head [OPTION]... [FILE]... DESCRIPTION top Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -c, --bytes=[-]NUM print the first NUM bytes of each file; with the leading '-', print all but the last NUM bytes of each file -n, --lines=[-]NUM print the first NUM lines instead of the first 10; with the leading '-', print all but the last NUM lines of each file -q, --quiet, --silent never print headers giving file names -v, --verbose always print headers giving file names -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit NUM may have a multiplier suffix: b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. 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 tail(1) Full documentation <https://www.gnu.org/software/coreutils/head> or available locally via: info '(coreutils) head 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 HEAD(1) Pages that refer to this page: tail(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. 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. Task: sort based on size and display top ten largest normal/regular files in the current folder Bash Command:<START>find . -type f -exec ls -s {} \; | sort -n -r | head -10<END>
sort based on size and display top ten small normal/regular files in the current folder
find . -type f -exec ls -s {} \; | sort -n | head -10
['find', 'ls', 'head', 'sort']
Output a Bash command to accomplish the following task. Task: sort based on size and display top ten small normal/regular files in the current folder Bash Command:<START>find . -type f -exec ls -s {} \; | sort -n | head -10<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 # ls\n\n> List directory contents.\n> More information: <https://www.gnu.org/software/coreutils/ls>.\n\n- List files one per line:\n\n`ls -1`\n\n- List all files, including hidden files:\n\n`ls -a`\n\n- List all files, with trailing `/` added to directory names:\n\n`ls -F`\n\n- Long format list (permissions, ownership, size, and modification date) of all files:\n\n`ls -la`\n\n- Long format list with size displayed using human-readable units (KiB, MiB, GiB):\n\n`ls -lh`\n\n- Long format list sorted by size (descending) recursively:\n\n`ls -lSR`\n\n- Long format list of all files, sorted by modification date (oldest first):\n\n`ls -ltr`\n\n- Only list directories:\n\n`ls -d */`\n # head\n\n> Output the first part of files.\n> More information: <https://www.gnu.org/software/coreutils/head>.\n\n- Output the first few lines of a file:\n\n`head --lines {{count}} {{path/to/file}}`\n\n- Output the first few bytes of a file:\n\n`head --bytes {{count}} {{path/to/file}}`\n\n- Output everything but the last few lines of a file:\n\n`head --lines -{{count}} {{path/to/file}}`\n\n- Output everything but the last few bytes of a file:\n\n`head --bytes -{{count}} {{path/to/file}}`\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 Task: sort based on size and display top ten small normal/regular files in the current folder Bash Command:<START>find . -type f -exec ls -s {} \; | sort -n | head -10<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. ls(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ls(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON LS(1) User Commands LS(1) NAME top ls - list directory contents SYNOPSIS top ls [OPTION]... [FILE]... DESCRIPTION top List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. Mandatory arguments to long options are mandatory for short options too. -a, --all do not ignore entries starting with . -A, --almost-all do not list implied . and .. --author with -l, print the author of each file -b, --escape print C-style escapes for nongraphic characters --block-size=SIZE with -l, scale sizes by SIZE when printing them; e.g., '--block-size=M'; see SIZE format below -B, --ignore-backups do not list implied entries ending with ~ -c with -lt: sort by, and show, ctime (time of last change of file status information); with -l: show ctime and sort by name; otherwise: sort by ctime, newest first -C list entries by columns --color[=WHEN] color the output WHEN; more info below -d, --directory list directories themselves, not their contents -D, --dired generate output designed for Emacs' dired mode -f list all entries in directory order -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN --file-type likewise, except do not append '*' --format=WORD across -x, commas -m, horizontal -x, long -l, single-column -1, verbose -l, vertical -C --full-time like -l --time-style=full-iso -g like -l, but do not list owner --group-directories-first group directories before files; can be augmented with a --sort option, but any use of --sort=none (-U) disables grouping -G, --no-group in a long listing, don't print group names -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc. --si likewise, but use powers of 1000 not 1024 -H, --dereference-command-line follow symbolic links listed on the command line --dereference-command-line-symlink-to-dir follow each command line symbolic link that points to a directory --hide=PATTERN do not list implied entries matching shell PATTERN (overridden by -a or -A) --hyperlink[=WHEN] hyperlink file names WHEN --indicator-style=WORD append indicator with style WORD to entry names: none (default), slash (-p), file-type (--file-type), classify (-F) -i, --inode print the index number of each file -I, --ignore=PATTERN do not list implied entries matching shell PATTERN -k, --kibibytes default to 1024-byte blocks for file system usage; used only with -s and per directory totals -l use a long listing format -L, --dereference when showing file information for a symbolic link, show information for the file the link references rather than for the link itself -m fill width with a comma separated list of entries -n, --numeric-uid-gid like -l, but list numeric user and group IDs -N, --literal print entry names without quoting -o like -l, but do not list group information -p, --indicator-style=slash append / indicator to directories -q, --hide-control-chars print ? instead of nongraphic characters --show-control-chars show nongraphic characters as-is (the default, unless program is 'ls' and output is a terminal) -Q, --quote-name enclose entry names in double quotes --quoting-style=WORD use quoting style WORD for entry names: literal, locale, shell, shell-always, shell-escape, shell-escape-always, c, escape (overrides QUOTING_STYLE environment variable) -r, --reverse reverse order while sorting -R, --recursive list subdirectories recursively -s, --size print the allocated size of each file, in blocks -S sort by file size, largest first --sort=WORD sort by WORD instead of name: none (-U), size (-S), time (-t), version (-v), extension (-X), width --time=WORD select which timestamp used to display or sort; access time (-u): atime, access, use; metadata change time (-c): ctime, status; modified time (default): mtime, modification; birth time: birth, creation; with -l, WORD determines which time to show; with --sort=time, sort by WORD (newest first) --time-style=TIME_STYLE time/date format with -l; see TIME_STYLE below -t sort by time, newest first; see --time -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u with -lt: sort by, and show, access time; with -l: show access time and sort by name; otherwise: sort by access time, newest first -U do not sort; list entries in directory order -v natural sort of (version) numbers within text -w, --width=COLS set output width to COLS. 0 means no limit -x list entries by lines instead of by columns -X sort alphabetically by entry extension -Z, --context print any security context of each file --zero end each output line with NUL, not newline -1 list one file per line --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT. FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2, then FORMAT1 applies to non-recent files and FORMAT2 to recent files. TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale. Also the TIME_STYLE environment variable sets the default style to use. The WHEN argument defaults to 'always' and can also be 'auto' or 'never'. Using color to distinguish file types is disabled both by default and with --color=never. With --color=auto, ls emits color codes only when standard output is connected to a terminal. The LS_COLORS environment variable can change the settings. Use the dircolors(1) command to set it. Exit status: 0 if OK, 1 if minor problems (e.g., cannot access subdirectory), 2 if serious trouble (e.g., cannot access command-line argument). 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 dircolors(1) Full documentation <https://www.gnu.org/software/coreutils/ls> or available locally via: info '(coreutils) ls 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 LS(1) Pages that refer to this page: column(1), find(1), namei(1), stat(2), statx(2), glob(3), strverscmp(3), core(5), dir_colors(5), passwd(5), proc(5), mq_overview(7), symlink(7), lsblk(8), lsof(8), setfiles(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. head(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training head(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON HEAD(1) User Commands HEAD(1) NAME top head - output the first part of files SYNOPSIS top head [OPTION]... [FILE]... DESCRIPTION top Print the first 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -c, --bytes=[-]NUM print the first NUM bytes of each file; with the leading '-', print all but the last NUM bytes of each file -n, --lines=[-]NUM print the first NUM lines instead of the first 10; with the leading '-', print all but the last NUM lines of each file -q, --quiet, --silent never print headers giving file names -v, --verbose always print headers giving file names -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit NUM may have a multiplier suffix: b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. 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 tail(1) Full documentation <https://www.gnu.org/software/coreutils/head> or available locally via: info '(coreutils) head 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 HEAD(1) Pages that refer to this page: tail(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. 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. Task: sort based on size and display top ten small normal/regular files in the current folder Bash Command:<START>find . -type f -exec ls -s {} \; | sort -n | head -10<END>
sort each file in the bills directory, leaving the output in that file name with .sorted appended
find bills -type f -execdir sort -o '{}.sorted' '{}' ';'
['find', 'sort']
Output a Bash command to accomplish the following task. Task: sort each file in the bills directory, leaving the output in that file name with .sorted appended Bash Command:<START>find bills -type f -execdir sort -o '{}.sorted' '{}' ';'<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 # 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 Task: sort each file in the bills directory, leaving the output in that file name with .sorted appended Bash Command:<START>find bills -type f -execdir sort -o '{}.sorted' '{}' ';'<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. 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. Task: sort each file in the bills directory, leaving the output in that file name with .sorted appended Bash Command:<START>find bills -type f -execdir sort -o '{}.sorted' '{}' ';'<END>
sort each file in the bills directory, leaving the output in that file name with .sorted appended
find bills -type f | xargs -I XX sort -o XX.sorted XX
['find', 'xargs', 'sort']
Output a Bash command to accomplish the following task. Task: sort each file in the bills directory, leaving the output in that file name with .sorted appended Bash Command:<START>find bills -type f | xargs -I XX sort -o XX.sorted XX<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 # 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 Task: sort each file in the bills directory, leaving the output in that file name with .sorted appended Bash Command:<START>find bills -type f | xargs -I XX sort -o XX.sorted XX<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. 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. Task: sort each file in the bills directory, leaving the output in that file name with .sorted appended Bash Command:<START>find bills -type f | xargs -I XX sort -o XX.sorted XX<END>
split $SOURCE_FILE" into pieces per 100 lines
split -l 100 "$SOURCE_FILE"
['split']
Output a Bash command to accomplish the following task. Task: split $SOURCE_FILE" into pieces per 100 lines Bash Command:<START>split -l 100 "$SOURCE_FILE"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split $SOURCE_FILE" into pieces per 100 lines Bash Command:<START>split -l 100 "$SOURCE_FILE"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split $SOURCE_FILE" into pieces per 100 lines Bash Command:<START>split -l 100 "$SOURCE_FILE"<END>
split a file "list.txt" into pieces per 600 lines
split -l 600 list.txt
['split']
Output a Bash command to accomplish the following task. Task: split a file "list.txt" into pieces per 600 lines Bash Command:<START>split -l 600 list.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split a file "list.txt" into pieces per 600 lines Bash Command:<START>split -l 600 list.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split a file "list.txt" into pieces per 600 lines Bash Command:<START>split -l 600 list.txt<END>
split all files in directory "/dev/shm/split/" into pieces per 1000 lines
find /dev/shm/split/ -type f -exec split -l 1000 {} {} \;
['find', 'split']
Output a Bash command to accomplish the following task. Task: split all files in directory "/dev/shm/split/" into pieces per 1000 lines Bash Command:<START>find /dev/shm/split/ -type f -exec split -l 1000 {} {} \;<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 # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split all files in directory "/dev/shm/split/" into pieces per 1000 lines Bash Command:<START>find /dev/shm/split/ -type f -exec split -l 1000 {} {} \;<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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split all files in directory "/dev/shm/split/" into pieces per 1000 lines Bash Command:<START>find /dev/shm/split/ -type f -exec split -l 1000 {} {} \;<END>
split all files in directory "posns " into pieces per 10000 lines
find posns -type f -exec split -l 10000 {} \;
['find', 'split']
Output a Bash command to accomplish the following task. Task: split all files in directory "posns " into pieces per 10000 lines Bash Command:<START>find posns -type f -exec split -l 10000 {} \;<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 # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split all files in directory "posns " into pieces per 10000 lines Bash Command:<START>find posns -type f -exec split -l 10000 {} \;<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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split all files in directory "posns " into pieces per 10000 lines Bash Command:<START>find posns -type f -exec split -l 10000 {} \;<END>
split compressed content of the directory /home into pieces per 4000 mb named as "/media/DRIVENAME/BACKUPNAME.tgz.NNN"
tar --one-file-system -czv /home | split -b 4000m - /media/DRIVENAME/BACKUPNAME.tgz
['tar', 'split']
Output a Bash command to accomplish the following task. Task: split compressed content of the directory /home into pieces per 4000 mb named as "/media/DRIVENAME/BACKUPNAME.tgz.NNN" Bash Command:<START>tar --one-file-system -czv /home | split -b 4000m - /media/DRIVENAME/BACKUPNAME.tgz<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # tar\n\n> Archiving utility.\n> Often combined with a compression method, such as `gzip` or `bzip2`.\n> More information: <https://www.gnu.org/software/tar>.\n\n- [c]reate an archive and write it to a [f]ile:\n\n`tar cf {{path/to/target.tar}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive and write it to a [f]ile:\n\n`tar czf {{path/to/target.tar.gz}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive from a directory using relative paths:\n\n`tar czf {{path/to/target.tar.gz}} --directory={{path/to/directory}} .`\n\n- E[x]tract a (compressed) archive [f]ile into the current directory [v]erbosely:\n\n`tar xvf {{path/to/source.tar[.gz|.bz2|.xz]}}`\n\n- E[x]tract a (compressed) archive [f]ile into the target directory:\n\n`tar xf {{path/to/source.tar[.gz|.bz2|.xz]}} --directory={{path/to/directory}}`\n\n- [c]reate a compressed archive and write it to a [f]ile, using the file extension to [a]utomatically determine the compression program:\n\n`tar caf {{path/to/target.tar.xz}} {{path/to/file1 path/to/file2 ...}}`\n\n- Lis[t] the contents of a tar [f]ile [v]erbosely:\n\n`tar tvf {{path/to/source.tar}}`\n\n- E[x]tract files matching a pattern from an archive [f]ile:\n\n`tar xf {{path/to/source.tar}} --wildcards "{{*.html}}"`\n # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split compressed content of the directory /home into pieces per 4000 mb named as "/media/DRIVENAME/BACKUPNAME.tgz.NNN" Bash Command:<START>tar --one-file-system -czv /home | split -b 4000m - /media/DRIVENAME/BACKUPNAME.tgz<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: tar(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tar(1) Linux manual page NAME | SYNOPSIS | NOTE | DESCRIPTION | OPTIONS | RETURN VALUE | SEE ALSO | BUG REPORTS | COPYRIGHT | COLOPHON TAR(1) GNU TAR Manual TAR(1) NAME top tar - an archiving utility SYNOPSIS top Traditional usage tar {A|c|d|r|t|u|x}[GnSkUWOmpsMBiajJzZhPlRvwo] [ARG...] UNIX-style usage tar -A [OPTIONS] -f ARCHIVE ARCHIVE... tar -c [-f ARCHIVE] [OPTIONS] [FILE...] tar -d [-f ARCHIVE] [OPTIONS] [FILE...] tar -r [-f ARCHIVE] [OPTIONS] [FILE...] tar -t [-f ARCHIVE] [OPTIONS] [MEMBER...] tar -u [-f ARCHIVE] [OPTIONS] [FILE...] tar -x [-f ARCHIVE] [OPTIONS] [MEMBER...] GNU-style usage tar {--catenate|--concatenate} [OPTIONS] --file ARCHIVE ARCHIVE... tar --create [--file ARCHIVE] [OPTIONS] [FILE...] tar {--diff|--compare} [--file ARCHIVE] [OPTIONS] [FILE...] tar --delete [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --append [--file ARCHIVE] [OPTIONS] [FILE...] tar --list [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --test-label [--file ARCHIVE] [OPTIONS] [LABEL...] tar --update [--file ARCHIVE] [OPTIONS] [FILE...] tar {--extract|--get} [--file ARCHIVE] [OPTIONS] [MEMBER...] NOTE top This manpage is a short description of GNU tar. For a detailed discussion, including examples and usage recommendations, refer to the GNU Tar Manual available in texinfo format. If the info reader and the tar documentation are properly installed on your system, the command info tar should give you access to the complete manual. You can also view the manual using the info mode in emacs(1), or find it in various formats online at https://www.gnu.org/software/tar/manual If any discrepancies occur between this manpage and the GNU Tar Manual, the later shall be considered the authoritative source. DESCRIPTION top GNU tar is an archiving program designed to store multiple files in a single file (an archive), and to manipulate such archives. The archive can be either a regular file or a device (e.g. a tape drive, hence the name of the program, which stands for tape archiver), which can be located either on the local or on a remote machine. Option styles Options to GNU tar can be given in three different styles. In traditional style, the first argument is a cluster of option letters and all subsequent arguments supply arguments to those options that require them. The arguments are read in the same order as the option letters. Any command line words that remain after all options have been processed are treated as non-option arguments: file or archive member names. For example, the c option requires creating the archive, the v option requests the verbose operation, and the f option takes an argument that sets the name of the archive to operate upon. The following command, written in the traditional style, instructs tar to store all files from the directory /etc into the archive file etc.tar, verbosely listing the files being archived: tar cfv etc.tar /etc In UNIX or short-option style, each option letter is prefixed with a single dash, as in other command line utilities. If an option takes an argument, the argument follows it, either as a separate command line word, or immediately following the option. However, if the option takes an optional argument, the argument must follow the option letter without any intervening whitespace, as in -g/tmp/snar.db. Any number of options not taking arguments can be clustered together after a single dash, e.g. -vkp. An option that takes an argument (whether mandatory or optional) can appear at the end of such a cluster, e.g. -vkpf a.tar. The example command above written in the short-option style could look like: tar -cvf etc.tar /etc or tar -c -v -f etc.tar /etc In GNU or long-option style, each option begins with two dashes and has a meaningful name, consisting of lower-case letters and dashes. When used, the long option can be abbreviated to its initial letters, provided that this does not create ambiguity. Arguments to long options are supplied either as a separate command line word, immediately following the option, or separated from the option by an equals sign with no intervening whitespace. Optional arguments must always use the latter method. Here are several ways of writing the example command in this style: tar --create --file etc.tar --verbose /etc or (abbreviating some options): tar --cre --file=etc.tar --verb /etc The options in all three styles can be intermixed, although doing so with old options is not encouraged. Operation mode The options listed in the table below tell GNU tar what operation it is to perform. Exactly one of them must be given. The meaning of non-option arguments depends on the operation mode requested. -A, --catenate, --concatenate Append archives to the end of another archive. The arguments are treated as the names of archives to append. All archives must be of the same format as the archive they are appended to, otherwise the resulting archive might be unusable with non-GNU implementations of tar. Notice also that when more than one archive is given, the members from archives other than the first one will be accessible in the resulting archive only when using the -i (--ignore-zeros) option. Compressed archives cannot be concatenated. -c, --create Create a new archive. Arguments supply the names of the files to be archived. Directories are archived recursively, unless the --no-recursion option is given. -d, --diff, --compare Find differences between archive and file system. The arguments are optional and specify archive members to compare. If not given, the current working directory is assumed. --delete Delete from the archive. The arguments supply names of the archive members to be removed. At least one argument must be given. This option does not operate on compressed archives. There is no short option equivalent. -r, --append Append files to the end of an archive. Arguments have the same meaning as for -c (--create). -t, --list List the contents of an archive. Arguments are optional. When given, they specify the names of the members to list. --test-label Test the archive volume label and exit. When used without arguments, it prints the volume label (if any) and exits with status 0. When one or more command line arguments are given. tar compares the volume label with each argument. It exits with code 0 if a match is found, and with code 1 otherwise. No output is displayed, unless used together with the -v (--verbose) option. There is no short option equivalent for this option. -u, --update Append files which are newer than the corresponding copy in the archive. Arguments have the same meaning as with the -c and -r options. Notice, that newer files don't replace their old archive copies, but instead are appended to the end of archive. The resulting archive can thus contain several members of the same name, corresponding to various versions of the same file. -x, --extract, --get Extract files from an archive. Arguments are optional. When given, they specify names of the archive members to be extracted. --show-defaults Show built-in defaults for various tar options and exit. -?, --help Display a short option summary and exit. --usage Display a list of available options and exit. --version Print program version and copyright information and exit. OPTIONS top Operation modifiers --check-device Check device numbers when creating incremental archives (default). -g, --listed-incremental=FILE Handle new GNU-format incremental backups. FILE is the name of a snapshot file, where tar stores additional information which is used to decide which files changed since the previous incremental dump and, consequently, must be dumped again. If FILE does not exist when creating an archive, it will be created and all files will be added to the resulting archive (the level 0 dump). To create incremental archives of non-zero level N, you need a copy of the snapshot file created for level N-1, and use it as FILE. When listing or extracting, the actual content of FILE is not inspected, it is needed only due to syntactical requirements. It is therefore common practice to use /dev/null in its place. --hole-detection=METHOD Use METHOD to detect holes in sparse files. This option implies --sparse. Valid values for METHOD are seek and raw. Default is seek with fallback to raw when not applicable. -G, --incremental Handle old GNU-format incremental backups. --ignore-failed-read Do not exit with nonzero on unreadable files. --level=NUMBER Set dump level for a created listed-incremental archive. Currently only --level=0 is meaningful: it instructs tar to truncate the snapshot file before dumping, thereby forcing a level 0 dump. -n, --seek Assume the archive is seekable. Normally tar determines automatically whether the archive can be seeked or not. This option is intended for use in cases when such recognition fails. It takes effect only if the archive is open for reading (e.g. with --list or --extract options). --no-check-device Do not check device numbers when creating incremental archives. --no-seek Assume the archive is not seekable. --occurrence[=N] Process only the Nth occurrence of each file in the archive. This option is valid only when used with one of the following subcommands: --delete, --diff, --extract or --list and when a list of files is given either on the command line or via the -T option. The default N is 1. --restrict Disable the use of some potentially harmful options. --sparse-version=MAJOR[.MINOR] Set which version of the sparse format to use. This option implies --sparse. Valid argument values are 0.0, 0.1, and 1.0. For a detailed discussion of sparse formats, refer to the GNU Tar Manual, appendix D, "Sparse Formats". Using the info reader, it can be accessed running the following command: info tar 'Sparse Formats'. -S, --sparse Handle sparse files efficiently. Some files in the file system may have segments which were actually never written (quite often these are database files created by such systems as DBM). When given this option, tar attempts to determine if the file is sparse prior to archiving it, and if so, to reduce the resulting archive size by not dumping empty parts of the file. Overwrite control These options control tar actions when extracting a file over an existing copy on disk. -k, --keep-old-files Don't replace existing files when extracting. --keep-newer-files Don't replace existing files that are newer than their archive copies. --keep-directory-symlink Don't replace existing symlinks to directories when extracting. --no-overwrite-dir Preserve metadata of existing directories. --one-top-level[=DIR] Extract all files into DIR, or, if used without argument, into a subdirectory named by the base name of the archive (minus standard compression suffixes recognizable by --auto-compress). --overwrite Overwrite existing files when extracting. --overwrite-dir Overwrite metadata of existing directories when extracting (default). --recursive-unlink Recursively remove all files in the directory prior to extracting it. --remove-files Remove files from disk after adding them to the archive. --skip-old-files Don't replace existing files when extracting, silently skip over them. -U, --unlink-first Remove each file prior to extracting over it. -W, --verify Verify the archive after writing it. Output stream selection --ignore-command-error Ignore subprocess exit codes. --no-ignore-command-error Treat non-zero exit codes of children as error (default). -O, --to-stdout Extract files to standard output. --to-command=COMMAND Pipe extracted files to COMMAND. The argument is the pathname of an external program, optionally with command line arguments. The program will be invoked and the contents of the file being extracted supplied to it on its standard input. Additional data will be supplied via the following environment variables: TAR_FILETYPE Type of the file. It is a single letter with the following meaning: f Regular file d Directory l Symbolic link h Hard link b Block device c Character device Currently only regular files are supported. TAR_MODE File mode, an octal number. TAR_FILENAME The name of the file. TAR_REALNAME Name of the file as stored in the archive. TAR_UNAME Name of the file owner. TAR_GNAME Name of the file owner group. TAR_ATIME Time of last access. It is a decimal number, representing seconds since the Epoch. If the archive provides times with nanosecond precision, the nanoseconds are appended to the timestamp after a decimal point. TAR_MTIME Time of last modification. TAR_CTIME Time of last status change. TAR_SIZE Size of the file. TAR_UID UID of the file owner. TAR_GID GID of the file owner. Additionally, the following variables contain information about tar operation mode and the archive being processed: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. Handling of file attributes --atime-preserve[=METHOD] Preserve access times on dumped files, either by restoring the times after reading (METHOD=replace, this is the default) or by not setting the times in the first place (METHOD=system). --delay-directory-restore Delay setting modification times and permissions of extracted directories until the end of extraction. Use this option when extracting from an archive which has unusual member ordering. --group=NAME[:GID] Force NAME as group for added files. If GID is not supplied, NAME can be either a user name or numeric GID. In this case the missing part (GID or name) will be inferred from the current host's group database. When used with --group-map=FILE, affects only those files whose owner group is not listed in FILE. --group-map=FILE Read group translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single group. It must consist of two fields, delimited by any amount of whitespace: OLDGRP NEWGRP[:NEWGID] OLDGRP is either a valid group name or a GID prefixed with +. Unless NEWGID is supplied, NEWGRP must also be either a valid group name or a +GID. Otherwise, both NEWGRP and NEWGID need not be listed in the system group database. As a result, each input file with owner group OLDGRP will be stored in archive with owner group NEWGRP and GID NEWGID. --mode=CHANGES Force symbolic mode CHANGES for added files. --mtime=DATE-OR-FILE Set mtime for added files. DATE-OR-FILE is either a date/time in almost arbitrary format, or the name of an existing file. In the latter case the mtime of that file will be used. -m, --touch Don't extract file modified time. --no-delay-directory-restore Cancel the effect of the prior --delay-directory-restore option. --no-same-owner Extract files as yourself (default for ordinary users). --no-same-permissions Apply the user's umask when extracting permissions from the archive (default for ordinary users). --numeric-owner Always use numbers for user/group names. --owner=NAME[:UID] Force NAME as owner for added files. If UID is not supplied, NAME can be either a user name or numeric UID. In this case the missing part (UID or name) will be inferred from the current host's user database. When used with --owner-map=FILE, affects only those files whose owner is not listed in FILE. --owner-map=FILE Read owner translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single UID. It must consist of two fields, delimited by any amount of whitespace: OLDUSR NEWUSR[:NEWUID] OLDUSR is either a valid user name or a UID prefixed with +. Unless NEWUID is supplied, NEWUSR must also be either a valid user name or a +UID. Otherwise, both NEWUSR and NEWUID need not be listed in the system user database. As a result, each input file owned by OLDUSR will be stored in archive with owner name NEWUSR and UID NEWUID. -p, --preserve-permissions, --same-permissions Set permissions of extracted files to those recorded in the archive (default for superuser). --same-owner Try extracting files with the same ownership as exists in the archive (default for superuser). -s, --preserve-order, --same-order Tell tar that the list of file names to process is sorted in the same order as the files in the archive. --sort=ORDER When creating an archive, sort directory entries according to ORDER, which is one of none, name, or inode. The default is --sort=none, which stores archive members in the same order as returned by the operating system. Using --sort=name ensures the member ordering in the created archive is uniform and reproducible. Using --sort=inode reduces the number of disk seeks made when creating the archive and thus can considerably speed up archivation. This sorting order is supported only if the underlying system provides the necessary information. Extended file attributes --acls Enable POSIX ACLs support. --no-acls Disable POSIX ACLs support. --selinux Enable SELinux context support. --no-selinux Disable SELinux context support. --xattrs Enable extended attributes support. --no-xattrs Disable extended attributes support. --xattrs-exclude=PATTERN Specify the exclude pattern for xattr keys. PATTERN is a globbing pattern, e.g. --xattrs-exclude='user.*' to include only attributes from the user namespace. --xattrs-include=PATTERN Specify the include pattern for xattr keys. PATTERN is a globbing pattern. Device selection and switching -f, --file=ARCHIVE Use archive file or device ARCHIVE. If this option is not given, tar will first examine the environment variable `TAPE'. If it is set, its value will be used as the archive name. Otherwise, tar will assume the compiled-in default. The default value can be inspected either using the --show-defaults option, or at the end of the tar --help output. An archive name that has a colon in it specifies a file or device on a remote machine. The part before the colon is taken as the machine name or IP address, and the part after it as the file or device pathname, e.g.: --file=remotehost:/dev/sr0 An optional username can be prefixed to the hostname, placing a @ sign between them. By default, the remote host is accessed via the rsh(1) command. Nowadays it is common to use ssh(1) instead. You can do so by giving the following command line option: --rsh-command=/usr/bin/ssh The remote machine should have the rmt(8) command installed. If its pathname does not match tar's default, you can inform tar about the correct pathname using the --rmt-command option. --force-local Archive file is local even if it has a colon. -F, --info-script=COMMAND, --new-volume-script=COMMAND Run COMMAND at the end of each tape (implies -M). The command can include arguments. When started, it will inherit tar's environment plus the following variables: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. TAR_FD File descriptor which can be used to communicate the new volume name to tar. If the info script fails, tar exits; otherwise, it begins writing the next volume. -L, --tape-length=N Change tape after writing Nx1024 bytes. If N is followed by a size suffix (see the subsection Size suffixes below), the suffix specifies the multiplicative factor to be used instead of 1024. This option implies -M. -M, --multi-volume Create/list/extract multi-volume archive. --rmt-command=COMMAND Use COMMAND instead of rmt when accessing remote archives. See the description of the -f option, above. --rsh-command=COMMAND Use COMMAND instead of rsh when accessing remote archives. See the description of the -f option, above. --volno-file=FILE When this option is used in conjunction with --multi-volume, tar will keep track of which volume of a multi-volume archive it is working in FILE. Device blocking -b, --blocking-factor=BLOCKS Set record size to BLOCKSx512 bytes. -B, --read-full-records When listing or extracting, accept incomplete input records after end-of-file marker. -i, --ignore-zeros Ignore zeroed blocks in archive. Normally two consecutive 512-blocks filled with zeroes mean EOF and tar stops reading after encountering them. This option instructs it to read further and is useful when reading archives created with the -A option. --record-size=NUMBER Set record size. NUMBER is the number of bytes per record. It must be multiple of 512. It can can be suffixed with a size suffix, e.g. --record-size=10K, for 10 Kilobytes. See the subsection Size suffixes, for a list of valid suffixes. Archive format selection -H, --format=FORMAT Create archive of the given format. Valid formats are: gnu GNU tar 1.13.x format oldgnu GNU format as per tar <= 1.12. pax, posix POSIX 1003.1-2001 (pax) format. ustar POSIX 1003.1-1988 (ustar) format. v7 Old V7 tar format. --old-archive, --portability Same as --format=v7. --pax-option=keyword[[:]=value][,keyword[[:]=value]]... Control pax keywords when creating PAX archives (-H pax). This option is equivalent to the -o option of the pax(1) utility. --posix Same as --format=posix. -V, --label=TEXT Create archive with volume name TEXT. If listing or extracting, use TEXT as a globbing pattern for volume name. Compression options -a, --auto-compress Use archive suffix to determine the compression program. -I, --use-compress-program=COMMAND Filter data through COMMAND. It must accept the -d option, for decompression. The argument can contain command line options. -j, --bzip2 Filter the archive through bzip2(1). -J, --xz Filter the archive through xz(1). --lzip Filter the archive through lzip(1). --lzma Filter the archive through lzma(1). --lzop Filter the archive through lzop(1). --no-auto-compress Do not use archive suffix to determine the compression program. -z, --gzip, --gunzip, --ungzip Filter the archive through gzip(1). -Z, --compress, --uncompress Filter the archive through compress(1). --zstd Filter the archive through zstd(1). Local file selection --add-file=FILE Add FILE to the archive (useful if its name starts with a dash). --backup[=CONTROL] Backup before removal. The CONTROL argument, if supplied, controls the backup policy. Its valid values are: none, off Never make backups. t, numbered Make numbered backups. nil, existing Make numbered backups if numbered backups exist, simple backups otherwise. never, simple Always make simple backups If CONTROL is not given, the value is taken from the VERSION_CONTROL environment variable. If it is not set, existing is assumed. -C, --directory=DIR Change to DIR before performing any operations. This option is order-sensitive, i.e. it affects all options that follow. --exclude=PATTERN Exclude files matching PATTERN, a glob(3)-style wildcard pattern. --exclude-backups Exclude backup and lock files. --exclude-caches Exclude contents of directories containing file CACHEDIR.TAG, except for the tag file itself. --exclude-caches-all Exclude directories containing file CACHEDIR.TAG and the file itself. --exclude-caches-under Exclude everything under directories containing CACHEDIR.TAG --exclude-ignore=FILE Before dumping a directory, see if it contains FILE. If so, read exclusion patterns from this file. The patterns affect only the directory itself. --exclude-ignore-recursive=FILE Same as --exclude-ignore, except that patterns from FILE affect both the directory and all its subdirectories. --exclude-tag=FILE Exclude contents of directories containing FILE, except for FILE itself. --exclude-tag-all=FILE Exclude directories containing FILE. --exclude-tag-under=FILE Exclude everything under directories containing FILE. --exclude-vcs Exclude version control system directories. --exclude-vcs-ignores Exclude files that match patterns read from VCS-specific ignore files. Supported files are: .cvsignore, .gitignore, .bzrignore, and .hgignore. -h, --dereference Follow symlinks; archive and dump the files they point to. --hard-dereference Follow hard links; archive and dump the files they refer to. -K, --starting-file=MEMBER Begin at the given member in the archive. --newer-mtime=DATE Work on files whose data changed after the DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --no-null Disable the effect of the previous --null option. --no-recursion Avoid descending automatically in directories. --no-unquote Do not unquote input file or member names. --no-verbatim-files-from Treat each line read from a file list as if it were supplied in the command line. I.e., leading and trailing whitespace is removed and, if the resulting string begins with a dash, it is treated as tar command line option. This is the default behavior. The --no-verbatim-files-from option is provided as a way to restore it after --verbatim-files-from option. This option is positional: it affects all --files-from options that occur after it in, until --verbatim-files-from option or end of line, whichever occurs first. It is implied by the --no-null option. --null Instruct subsequent -T options to read null-terminated names verbatim (disables special handling of names that start with a dash). See also --verbatim-files-from. -N, --newer=DATE, --after-date=DATE Only store files newer than DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --one-file-system Stay in local file system when creating archive. -P, --absolute-names Don't strip leading slashes from file names when creating archives. --recursion Recurse into directories (default). --suffix=STRING Backup before removal, override usual suffix. Default suffix is ~, unless overridden by environment variable SIMPLE_BACKUP_SUFFIX. -T, --files-from=FILE Get names to extract or create from FILE. Unless specified otherwise, the FILE must contain a list of names separated by ASCII LF (i.e. one name per line). The names read are handled the same way as command line arguments. They undergo quote removal and word splitting, and any string that starts with a - is handled as tar command line option. If this behavior is undesirable, it can be turned off using the --verbatim-files-from option. The --null option instructs tar that the names in FILE are separated by ASCII NUL character, instead of LF. It is useful if the list is generated by find(1) -print0 predicate. --unquote Unquote file or member names (default). --verbatim-files-from Treat each line obtained from a file list as a file name, even if it starts with a dash. File lists are supplied with the --files-from (-T) option. The default behavior is to handle names supplied in file lists as if they were typed in the command line, i.e. any names starting with a dash are treated as tar options. The --verbatim-files-from option disables this behavior. This option affects all --files-from options that occur after it in the command line. Its effect is reverted by the --no-verbatim-files-from option. This option is implied by the --null option. See also --add-file. -X, --exclude-from=FILE Exclude files matching patterns listed in FILE. File name transformations --strip-components=NUMBER Strip NUMBER leading components from file names on extraction. --transform=EXPRESSION, --xform=EXPRESSION Use sed replace EXPRESSION to transform file names. File name matching options These options affect both exclude and include patterns. --anchored Patterns match file name start. --ignore-case Ignore case. --no-anchored Patterns match after any / (default for exclusion). --no-ignore-case Case sensitive matching (default). --no-wildcards Verbatim string matching. --no-wildcards-match-slash Wildcards do not match /. --wildcards Use wildcards (default for exclusion). --wildcards-match-slash Wildcards match / (default for exclusion). Informative output --checkpoint[=N] Display progress messages every Nth record (default 10). --checkpoint-action=ACTION Run ACTION on each checkpoint. --clamp-mtime Only set time when the file is more recent than what was given with --mtime. --full-time Print file time to its full resolution. --index-file=FILE Send verbose output to FILE. -l, --check-links Print a message if not all links are dumped. --no-quote-chars=STRING Disable quoting for characters from STRING. --quote-chars=STRING Additionally quote characters from STRING. --quoting-style=STYLE Set quoting style for file and member names. Valid values for STYLE are literal, shell, shell-always, c, c-maybe, escape, locale, clocale. -R, --block-number Show block number within archive with each message. --show-omitted-dirs When listing or extracting, list each directory that does not match search criteria. --show-transformed-names, --show-stored-names Show file or archive names after transformation by --strip and --transform options. --totals[=SIGNAL] Print total bytes after processing the archive. If SIGNAL is given, print total bytes when this signal is delivered. Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1, and SIGUSR2. The SIG prefix can be omitted. --utc Print file modification times in UTC. -v, --verbose Verbosely list files processed. Each instance of this option on the command line increases the verbosity level by one. The maximum verbosity level is 3. For a detailed discussion of how various verbosity levels affect tar's output, please refer to GNU Tar Manual, subsection 2.5.2 "The '--verbose' Option". --warning=KEYWORD Enable or disable warning messages identified by KEYWORD. The messages are suppressed if KEYWORD is prefixed with no- and enabled otherwise. Multiple --warning options accumulate. Keywords controlling general tar operation: all Enable all warning messages. This is the default. none Disable all warning messages. filename-with-nuls "%s: file name read contains nul character" alone-zero-block "A lone zero block at %s" Keywords applicable for tar --create: cachedir "%s: contains a cache directory tag %s; %s" file-shrank "%s: File shrank by %s bytes; padding with zeros" xdev "%s: file is on a different filesystem; not dumped" file-ignored "%s: Unknown file type; file ignored" "%s: socket ignored" "%s: door ignored" file-unchanged "%s: file is unchanged; not dumped" ignore-archive "%s: archive cannot contain itself; not dumped" file-removed "%s: File removed before we read it" file-changed "%s: file changed as we read it" failed-read Suppresses warnings about unreadable files or directories. This keyword applies only if used together with the --ignore-failed-read option. Keywords applicable for tar --extract: existing-file "%s: skipping existing file" timestamp "%s: implausibly old time stamp %s" "%s: time stamp %s is %s s in the future" contiguous-cast "Extracting contiguous files as regular files" symlink-cast "Attempting extraction of symbolic links as hard links" unknown-cast "%s: Unknown file type '%c', extracted as normal file" ignore-newer "Current %s is newer or same age" unknown-keyword "Ignoring unknown extended header keyword '%s'" decompress-program Controls verbose description of failures occurring when trying to run alternative decompressor programs. This warning is disabled by default (unless --verbose is used). A common example of what you can get when using this warning is: $ tar --warning=decompress-program -x -f archive.Z tar (child): cannot run compress: No such file or directory tar (child): trying gzip This means that tar first tried to decompress archive.Z using compress, and, when that failed, switched to gzip. record-size "Record size = %lu blocks" Keywords controlling incremental extraction: rename-directory "%s: Directory has been renamed from %s" "%s: Directory has been renamed" new-directory "%s: Directory is new" xdev "%s: directory is on a different device: not purging" bad-dumpdir "Malformed dumpdir: 'X' never used" -w, --interactive, --confirmation Ask for confirmation for every action. Compatibility options -o When creating, same as --old-archive. When extracting, same as --no-same-owner. Size suffixes Suffix Units Byte Equivalent b Blocks SIZE x 512 B Kilobytes SIZE x 1024 c Bytes SIZE G Gigabytes SIZE x 1024^3 K Kilobytes SIZE x 1024 k Kilobytes SIZE x 1024 M Megabytes SIZE x 1024^2 P Petabytes SIZE x 1024^5 T Terabytes SIZE x 1024^4 w Words SIZE x 2 RETURN VALUE top Tar's exit code indicates whether it was able to successfully perform the requested operation, and if not, what kind of error occurred. 0 Successful termination. 1 Some files differ. If tar was invoked with the --compare (--diff, -d) command line option, this means that some files in the archive differ from their disk counterparts. If tar was given one of the --create, --append or --update options, this exit code means that some files were changed while being archived and so the resulting archive does not contain the exact copy of the file set. 2 Fatal error. This means that some fatal, unrecoverable error occurred. If a subprocess that had been invoked by tar exited with a nonzero exit code, tar itself exits with that code as well. This can happen, for example, if a compression option (e.g. -z) was used and the external compressor program failed. Another example is rmt failure during backup to a remote device. SEE ALSO top bzip2(1), compress(1), gzip(1), lzma(1), lzop(1), rmt(8), symlink(7), xz(1), zstd(1). Complete tar manual: run info tar or use emacs(1) info mode to read it. Online copies of GNU tar documentation in various formats can be found at: https://www.gnu.org/software/tar/manual BUG REPORTS top Report bugs to <bug-tar@gnu.org>. COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://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. COLOPHON top This page is part of the tar (an archiver program) project. Information about the project can be found at http://savannah.gnu.org/projects/tar/. If you have a bug report for this manual page, see http://savannah.gnu.org/bugs/?group=tar. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/tar.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-12.) 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 TAR July 11, 2022 TAR(1) Pages that refer to this page: attr(1), dpkg-deb(1), dpkg-source(1), machinectl(1), rsync(1), st(4), suffixes(7), symlink(7), cupsd-helper(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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split compressed content of the directory /home into pieces per 4000 mb named as "/media/DRIVENAME/BACKUPNAME.tgz.NNN" Bash Command:<START>tar --one-file-system -czv /home | split -b 4000m - /media/DRIVENAME/BACKUPNAME.tgz<END>
split compressed content of the file www into pieces per 1073741824 bytes named as "backup.tar.NNN"
tar czf - www|split -b 1073741824 - www-backup.tar.
['tar', 'split']
Output a Bash command to accomplish the following task. Task: split compressed content of the file www into pieces per 1073741824 bytes named as "backup.tar.NNN" Bash Command:<START>tar czf - www|split -b 1073741824 - www-backup.tar.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # tar\n\n> Archiving utility.\n> Often combined with a compression method, such as `gzip` or `bzip2`.\n> More information: <https://www.gnu.org/software/tar>.\n\n- [c]reate an archive and write it to a [f]ile:\n\n`tar cf {{path/to/target.tar}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive and write it to a [f]ile:\n\n`tar czf {{path/to/target.tar.gz}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive from a directory using relative paths:\n\n`tar czf {{path/to/target.tar.gz}} --directory={{path/to/directory}} .`\n\n- E[x]tract a (compressed) archive [f]ile into the current directory [v]erbosely:\n\n`tar xvf {{path/to/source.tar[.gz|.bz2|.xz]}}`\n\n- E[x]tract a (compressed) archive [f]ile into the target directory:\n\n`tar xf {{path/to/source.tar[.gz|.bz2|.xz]}} --directory={{path/to/directory}}`\n\n- [c]reate a compressed archive and write it to a [f]ile, using the file extension to [a]utomatically determine the compression program:\n\n`tar caf {{path/to/target.tar.xz}} {{path/to/file1 path/to/file2 ...}}`\n\n- Lis[t] the contents of a tar [f]ile [v]erbosely:\n\n`tar tvf {{path/to/source.tar}}`\n\n- E[x]tract files matching a pattern from an archive [f]ile:\n\n`tar xf {{path/to/source.tar}} --wildcards "{{*.html}}"`\n # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split compressed content of the file www into pieces per 1073741824 bytes named as "backup.tar.NNN" Bash Command:<START>tar czf - www|split -b 1073741824 - www-backup.tar.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: tar(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tar(1) Linux manual page NAME | SYNOPSIS | NOTE | DESCRIPTION | OPTIONS | RETURN VALUE | SEE ALSO | BUG REPORTS | COPYRIGHT | COLOPHON TAR(1) GNU TAR Manual TAR(1) NAME top tar - an archiving utility SYNOPSIS top Traditional usage tar {A|c|d|r|t|u|x}[GnSkUWOmpsMBiajJzZhPlRvwo] [ARG...] UNIX-style usage tar -A [OPTIONS] -f ARCHIVE ARCHIVE... tar -c [-f ARCHIVE] [OPTIONS] [FILE...] tar -d [-f ARCHIVE] [OPTIONS] [FILE...] tar -r [-f ARCHIVE] [OPTIONS] [FILE...] tar -t [-f ARCHIVE] [OPTIONS] [MEMBER...] tar -u [-f ARCHIVE] [OPTIONS] [FILE...] tar -x [-f ARCHIVE] [OPTIONS] [MEMBER...] GNU-style usage tar {--catenate|--concatenate} [OPTIONS] --file ARCHIVE ARCHIVE... tar --create [--file ARCHIVE] [OPTIONS] [FILE...] tar {--diff|--compare} [--file ARCHIVE] [OPTIONS] [FILE...] tar --delete [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --append [--file ARCHIVE] [OPTIONS] [FILE...] tar --list [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --test-label [--file ARCHIVE] [OPTIONS] [LABEL...] tar --update [--file ARCHIVE] [OPTIONS] [FILE...] tar {--extract|--get} [--file ARCHIVE] [OPTIONS] [MEMBER...] NOTE top This manpage is a short description of GNU tar. For a detailed discussion, including examples and usage recommendations, refer to the GNU Tar Manual available in texinfo format. If the info reader and the tar documentation are properly installed on your system, the command info tar should give you access to the complete manual. You can also view the manual using the info mode in emacs(1), or find it in various formats online at https://www.gnu.org/software/tar/manual If any discrepancies occur between this manpage and the GNU Tar Manual, the later shall be considered the authoritative source. DESCRIPTION top GNU tar is an archiving program designed to store multiple files in a single file (an archive), and to manipulate such archives. The archive can be either a regular file or a device (e.g. a tape drive, hence the name of the program, which stands for tape archiver), which can be located either on the local or on a remote machine. Option styles Options to GNU tar can be given in three different styles. In traditional style, the first argument is a cluster of option letters and all subsequent arguments supply arguments to those options that require them. The arguments are read in the same order as the option letters. Any command line words that remain after all options have been processed are treated as non-option arguments: file or archive member names. For example, the c option requires creating the archive, the v option requests the verbose operation, and the f option takes an argument that sets the name of the archive to operate upon. The following command, written in the traditional style, instructs tar to store all files from the directory /etc into the archive file etc.tar, verbosely listing the files being archived: tar cfv etc.tar /etc In UNIX or short-option style, each option letter is prefixed with a single dash, as in other command line utilities. If an option takes an argument, the argument follows it, either as a separate command line word, or immediately following the option. However, if the option takes an optional argument, the argument must follow the option letter without any intervening whitespace, as in -g/tmp/snar.db. Any number of options not taking arguments can be clustered together after a single dash, e.g. -vkp. An option that takes an argument (whether mandatory or optional) can appear at the end of such a cluster, e.g. -vkpf a.tar. The example command above written in the short-option style could look like: tar -cvf etc.tar /etc or tar -c -v -f etc.tar /etc In GNU or long-option style, each option begins with two dashes and has a meaningful name, consisting of lower-case letters and dashes. When used, the long option can be abbreviated to its initial letters, provided that this does not create ambiguity. Arguments to long options are supplied either as a separate command line word, immediately following the option, or separated from the option by an equals sign with no intervening whitespace. Optional arguments must always use the latter method. Here are several ways of writing the example command in this style: tar --create --file etc.tar --verbose /etc or (abbreviating some options): tar --cre --file=etc.tar --verb /etc The options in all three styles can be intermixed, although doing so with old options is not encouraged. Operation mode The options listed in the table below tell GNU tar what operation it is to perform. Exactly one of them must be given. The meaning of non-option arguments depends on the operation mode requested. -A, --catenate, --concatenate Append archives to the end of another archive. The arguments are treated as the names of archives to append. All archives must be of the same format as the archive they are appended to, otherwise the resulting archive might be unusable with non-GNU implementations of tar. Notice also that when more than one archive is given, the members from archives other than the first one will be accessible in the resulting archive only when using the -i (--ignore-zeros) option. Compressed archives cannot be concatenated. -c, --create Create a new archive. Arguments supply the names of the files to be archived. Directories are archived recursively, unless the --no-recursion option is given. -d, --diff, --compare Find differences between archive and file system. The arguments are optional and specify archive members to compare. If not given, the current working directory is assumed. --delete Delete from the archive. The arguments supply names of the archive members to be removed. At least one argument must be given. This option does not operate on compressed archives. There is no short option equivalent. -r, --append Append files to the end of an archive. Arguments have the same meaning as for -c (--create). -t, --list List the contents of an archive. Arguments are optional. When given, they specify the names of the members to list. --test-label Test the archive volume label and exit. When used without arguments, it prints the volume label (if any) and exits with status 0. When one or more command line arguments are given. tar compares the volume label with each argument. It exits with code 0 if a match is found, and with code 1 otherwise. No output is displayed, unless used together with the -v (--verbose) option. There is no short option equivalent for this option. -u, --update Append files which are newer than the corresponding copy in the archive. Arguments have the same meaning as with the -c and -r options. Notice, that newer files don't replace their old archive copies, but instead are appended to the end of archive. The resulting archive can thus contain several members of the same name, corresponding to various versions of the same file. -x, --extract, --get Extract files from an archive. Arguments are optional. When given, they specify names of the archive members to be extracted. --show-defaults Show built-in defaults for various tar options and exit. -?, --help Display a short option summary and exit. --usage Display a list of available options and exit. --version Print program version and copyright information and exit. OPTIONS top Operation modifiers --check-device Check device numbers when creating incremental archives (default). -g, --listed-incremental=FILE Handle new GNU-format incremental backups. FILE is the name of a snapshot file, where tar stores additional information which is used to decide which files changed since the previous incremental dump and, consequently, must be dumped again. If FILE does not exist when creating an archive, it will be created and all files will be added to the resulting archive (the level 0 dump). To create incremental archives of non-zero level N, you need a copy of the snapshot file created for level N-1, and use it as FILE. When listing or extracting, the actual content of FILE is not inspected, it is needed only due to syntactical requirements. It is therefore common practice to use /dev/null in its place. --hole-detection=METHOD Use METHOD to detect holes in sparse files. This option implies --sparse. Valid values for METHOD are seek and raw. Default is seek with fallback to raw when not applicable. -G, --incremental Handle old GNU-format incremental backups. --ignore-failed-read Do not exit with nonzero on unreadable files. --level=NUMBER Set dump level for a created listed-incremental archive. Currently only --level=0 is meaningful: it instructs tar to truncate the snapshot file before dumping, thereby forcing a level 0 dump. -n, --seek Assume the archive is seekable. Normally tar determines automatically whether the archive can be seeked or not. This option is intended for use in cases when such recognition fails. It takes effect only if the archive is open for reading (e.g. with --list or --extract options). --no-check-device Do not check device numbers when creating incremental archives. --no-seek Assume the archive is not seekable. --occurrence[=N] Process only the Nth occurrence of each file in the archive. This option is valid only when used with one of the following subcommands: --delete, --diff, --extract or --list and when a list of files is given either on the command line or via the -T option. The default N is 1. --restrict Disable the use of some potentially harmful options. --sparse-version=MAJOR[.MINOR] Set which version of the sparse format to use. This option implies --sparse. Valid argument values are 0.0, 0.1, and 1.0. For a detailed discussion of sparse formats, refer to the GNU Tar Manual, appendix D, "Sparse Formats". Using the info reader, it can be accessed running the following command: info tar 'Sparse Formats'. -S, --sparse Handle sparse files efficiently. Some files in the file system may have segments which were actually never written (quite often these are database files created by such systems as DBM). When given this option, tar attempts to determine if the file is sparse prior to archiving it, and if so, to reduce the resulting archive size by not dumping empty parts of the file. Overwrite control These options control tar actions when extracting a file over an existing copy on disk. -k, --keep-old-files Don't replace existing files when extracting. --keep-newer-files Don't replace existing files that are newer than their archive copies. --keep-directory-symlink Don't replace existing symlinks to directories when extracting. --no-overwrite-dir Preserve metadata of existing directories. --one-top-level[=DIR] Extract all files into DIR, or, if used without argument, into a subdirectory named by the base name of the archive (minus standard compression suffixes recognizable by --auto-compress). --overwrite Overwrite existing files when extracting. --overwrite-dir Overwrite metadata of existing directories when extracting (default). --recursive-unlink Recursively remove all files in the directory prior to extracting it. --remove-files Remove files from disk after adding them to the archive. --skip-old-files Don't replace existing files when extracting, silently skip over them. -U, --unlink-first Remove each file prior to extracting over it. -W, --verify Verify the archive after writing it. Output stream selection --ignore-command-error Ignore subprocess exit codes. --no-ignore-command-error Treat non-zero exit codes of children as error (default). -O, --to-stdout Extract files to standard output. --to-command=COMMAND Pipe extracted files to COMMAND. The argument is the pathname of an external program, optionally with command line arguments. The program will be invoked and the contents of the file being extracted supplied to it on its standard input. Additional data will be supplied via the following environment variables: TAR_FILETYPE Type of the file. It is a single letter with the following meaning: f Regular file d Directory l Symbolic link h Hard link b Block device c Character device Currently only regular files are supported. TAR_MODE File mode, an octal number. TAR_FILENAME The name of the file. TAR_REALNAME Name of the file as stored in the archive. TAR_UNAME Name of the file owner. TAR_GNAME Name of the file owner group. TAR_ATIME Time of last access. It is a decimal number, representing seconds since the Epoch. If the archive provides times with nanosecond precision, the nanoseconds are appended to the timestamp after a decimal point. TAR_MTIME Time of last modification. TAR_CTIME Time of last status change. TAR_SIZE Size of the file. TAR_UID UID of the file owner. TAR_GID GID of the file owner. Additionally, the following variables contain information about tar operation mode and the archive being processed: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. Handling of file attributes --atime-preserve[=METHOD] Preserve access times on dumped files, either by restoring the times after reading (METHOD=replace, this is the default) or by not setting the times in the first place (METHOD=system). --delay-directory-restore Delay setting modification times and permissions of extracted directories until the end of extraction. Use this option when extracting from an archive which has unusual member ordering. --group=NAME[:GID] Force NAME as group for added files. If GID is not supplied, NAME can be either a user name or numeric GID. In this case the missing part (GID or name) will be inferred from the current host's group database. When used with --group-map=FILE, affects only those files whose owner group is not listed in FILE. --group-map=FILE Read group translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single group. It must consist of two fields, delimited by any amount of whitespace: OLDGRP NEWGRP[:NEWGID] OLDGRP is either a valid group name or a GID prefixed with +. Unless NEWGID is supplied, NEWGRP must also be either a valid group name or a +GID. Otherwise, both NEWGRP and NEWGID need not be listed in the system group database. As a result, each input file with owner group OLDGRP will be stored in archive with owner group NEWGRP and GID NEWGID. --mode=CHANGES Force symbolic mode CHANGES for added files. --mtime=DATE-OR-FILE Set mtime for added files. DATE-OR-FILE is either a date/time in almost arbitrary format, or the name of an existing file. In the latter case the mtime of that file will be used. -m, --touch Don't extract file modified time. --no-delay-directory-restore Cancel the effect of the prior --delay-directory-restore option. --no-same-owner Extract files as yourself (default for ordinary users). --no-same-permissions Apply the user's umask when extracting permissions from the archive (default for ordinary users). --numeric-owner Always use numbers for user/group names. --owner=NAME[:UID] Force NAME as owner for added files. If UID is not supplied, NAME can be either a user name or numeric UID. In this case the missing part (UID or name) will be inferred from the current host's user database. When used with --owner-map=FILE, affects only those files whose owner is not listed in FILE. --owner-map=FILE Read owner translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single UID. It must consist of two fields, delimited by any amount of whitespace: OLDUSR NEWUSR[:NEWUID] OLDUSR is either a valid user name or a UID prefixed with +. Unless NEWUID is supplied, NEWUSR must also be either a valid user name or a +UID. Otherwise, both NEWUSR and NEWUID need not be listed in the system user database. As a result, each input file owned by OLDUSR will be stored in archive with owner name NEWUSR and UID NEWUID. -p, --preserve-permissions, --same-permissions Set permissions of extracted files to those recorded in the archive (default for superuser). --same-owner Try extracting files with the same ownership as exists in the archive (default for superuser). -s, --preserve-order, --same-order Tell tar that the list of file names to process is sorted in the same order as the files in the archive. --sort=ORDER When creating an archive, sort directory entries according to ORDER, which is one of none, name, or inode. The default is --sort=none, which stores archive members in the same order as returned by the operating system. Using --sort=name ensures the member ordering in the created archive is uniform and reproducible. Using --sort=inode reduces the number of disk seeks made when creating the archive and thus can considerably speed up archivation. This sorting order is supported only if the underlying system provides the necessary information. Extended file attributes --acls Enable POSIX ACLs support. --no-acls Disable POSIX ACLs support. --selinux Enable SELinux context support. --no-selinux Disable SELinux context support. --xattrs Enable extended attributes support. --no-xattrs Disable extended attributes support. --xattrs-exclude=PATTERN Specify the exclude pattern for xattr keys. PATTERN is a globbing pattern, e.g. --xattrs-exclude='user.*' to include only attributes from the user namespace. --xattrs-include=PATTERN Specify the include pattern for xattr keys. PATTERN is a globbing pattern. Device selection and switching -f, --file=ARCHIVE Use archive file or device ARCHIVE. If this option is not given, tar will first examine the environment variable `TAPE'. If it is set, its value will be used as the archive name. Otherwise, tar will assume the compiled-in default. The default value can be inspected either using the --show-defaults option, or at the end of the tar --help output. An archive name that has a colon in it specifies a file or device on a remote machine. The part before the colon is taken as the machine name or IP address, and the part after it as the file or device pathname, e.g.: --file=remotehost:/dev/sr0 An optional username can be prefixed to the hostname, placing a @ sign between them. By default, the remote host is accessed via the rsh(1) command. Nowadays it is common to use ssh(1) instead. You can do so by giving the following command line option: --rsh-command=/usr/bin/ssh The remote machine should have the rmt(8) command installed. If its pathname does not match tar's default, you can inform tar about the correct pathname using the --rmt-command option. --force-local Archive file is local even if it has a colon. -F, --info-script=COMMAND, --new-volume-script=COMMAND Run COMMAND at the end of each tape (implies -M). The command can include arguments. When started, it will inherit tar's environment plus the following variables: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. TAR_FD File descriptor which can be used to communicate the new volume name to tar. If the info script fails, tar exits; otherwise, it begins writing the next volume. -L, --tape-length=N Change tape after writing Nx1024 bytes. If N is followed by a size suffix (see the subsection Size suffixes below), the suffix specifies the multiplicative factor to be used instead of 1024. This option implies -M. -M, --multi-volume Create/list/extract multi-volume archive. --rmt-command=COMMAND Use COMMAND instead of rmt when accessing remote archives. See the description of the -f option, above. --rsh-command=COMMAND Use COMMAND instead of rsh when accessing remote archives. See the description of the -f option, above. --volno-file=FILE When this option is used in conjunction with --multi-volume, tar will keep track of which volume of a multi-volume archive it is working in FILE. Device blocking -b, --blocking-factor=BLOCKS Set record size to BLOCKSx512 bytes. -B, --read-full-records When listing or extracting, accept incomplete input records after end-of-file marker. -i, --ignore-zeros Ignore zeroed blocks in archive. Normally two consecutive 512-blocks filled with zeroes mean EOF and tar stops reading after encountering them. This option instructs it to read further and is useful when reading archives created with the -A option. --record-size=NUMBER Set record size. NUMBER is the number of bytes per record. It must be multiple of 512. It can can be suffixed with a size suffix, e.g. --record-size=10K, for 10 Kilobytes. See the subsection Size suffixes, for a list of valid suffixes. Archive format selection -H, --format=FORMAT Create archive of the given format. Valid formats are: gnu GNU tar 1.13.x format oldgnu GNU format as per tar <= 1.12. pax, posix POSIX 1003.1-2001 (pax) format. ustar POSIX 1003.1-1988 (ustar) format. v7 Old V7 tar format. --old-archive, --portability Same as --format=v7. --pax-option=keyword[[:]=value][,keyword[[:]=value]]... Control pax keywords when creating PAX archives (-H pax). This option is equivalent to the -o option of the pax(1) utility. --posix Same as --format=posix. -V, --label=TEXT Create archive with volume name TEXT. If listing or extracting, use TEXT as a globbing pattern for volume name. Compression options -a, --auto-compress Use archive suffix to determine the compression program. -I, --use-compress-program=COMMAND Filter data through COMMAND. It must accept the -d option, for decompression. The argument can contain command line options. -j, --bzip2 Filter the archive through bzip2(1). -J, --xz Filter the archive through xz(1). --lzip Filter the archive through lzip(1). --lzma Filter the archive through lzma(1). --lzop Filter the archive through lzop(1). --no-auto-compress Do not use archive suffix to determine the compression program. -z, --gzip, --gunzip, --ungzip Filter the archive through gzip(1). -Z, --compress, --uncompress Filter the archive through compress(1). --zstd Filter the archive through zstd(1). Local file selection --add-file=FILE Add FILE to the archive (useful if its name starts with a dash). --backup[=CONTROL] Backup before removal. The CONTROL argument, if supplied, controls the backup policy. Its valid values are: none, off Never make backups. t, numbered Make numbered backups. nil, existing Make numbered backups if numbered backups exist, simple backups otherwise. never, simple Always make simple backups If CONTROL is not given, the value is taken from the VERSION_CONTROL environment variable. If it is not set, existing is assumed. -C, --directory=DIR Change to DIR before performing any operations. This option is order-sensitive, i.e. it affects all options that follow. --exclude=PATTERN Exclude files matching PATTERN, a glob(3)-style wildcard pattern. --exclude-backups Exclude backup and lock files. --exclude-caches Exclude contents of directories containing file CACHEDIR.TAG, except for the tag file itself. --exclude-caches-all Exclude directories containing file CACHEDIR.TAG and the file itself. --exclude-caches-under Exclude everything under directories containing CACHEDIR.TAG --exclude-ignore=FILE Before dumping a directory, see if it contains FILE. If so, read exclusion patterns from this file. The patterns affect only the directory itself. --exclude-ignore-recursive=FILE Same as --exclude-ignore, except that patterns from FILE affect both the directory and all its subdirectories. --exclude-tag=FILE Exclude contents of directories containing FILE, except for FILE itself. --exclude-tag-all=FILE Exclude directories containing FILE. --exclude-tag-under=FILE Exclude everything under directories containing FILE. --exclude-vcs Exclude version control system directories. --exclude-vcs-ignores Exclude files that match patterns read from VCS-specific ignore files. Supported files are: .cvsignore, .gitignore, .bzrignore, and .hgignore. -h, --dereference Follow symlinks; archive and dump the files they point to. --hard-dereference Follow hard links; archive and dump the files they refer to. -K, --starting-file=MEMBER Begin at the given member in the archive. --newer-mtime=DATE Work on files whose data changed after the DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --no-null Disable the effect of the previous --null option. --no-recursion Avoid descending automatically in directories. --no-unquote Do not unquote input file or member names. --no-verbatim-files-from Treat each line read from a file list as if it were supplied in the command line. I.e., leading and trailing whitespace is removed and, if the resulting string begins with a dash, it is treated as tar command line option. This is the default behavior. The --no-verbatim-files-from option is provided as a way to restore it after --verbatim-files-from option. This option is positional: it affects all --files-from options that occur after it in, until --verbatim-files-from option or end of line, whichever occurs first. It is implied by the --no-null option. --null Instruct subsequent -T options to read null-terminated names verbatim (disables special handling of names that start with a dash). See also --verbatim-files-from. -N, --newer=DATE, --after-date=DATE Only store files newer than DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --one-file-system Stay in local file system when creating archive. -P, --absolute-names Don't strip leading slashes from file names when creating archives. --recursion Recurse into directories (default). --suffix=STRING Backup before removal, override usual suffix. Default suffix is ~, unless overridden by environment variable SIMPLE_BACKUP_SUFFIX. -T, --files-from=FILE Get names to extract or create from FILE. Unless specified otherwise, the FILE must contain a list of names separated by ASCII LF (i.e. one name per line). The names read are handled the same way as command line arguments. They undergo quote removal and word splitting, and any string that starts with a - is handled as tar command line option. If this behavior is undesirable, it can be turned off using the --verbatim-files-from option. The --null option instructs tar that the names in FILE are separated by ASCII NUL character, instead of LF. It is useful if the list is generated by find(1) -print0 predicate. --unquote Unquote file or member names (default). --verbatim-files-from Treat each line obtained from a file list as a file name, even if it starts with a dash. File lists are supplied with the --files-from (-T) option. The default behavior is to handle names supplied in file lists as if they were typed in the command line, i.e. any names starting with a dash are treated as tar options. The --verbatim-files-from option disables this behavior. This option affects all --files-from options that occur after it in the command line. Its effect is reverted by the --no-verbatim-files-from option. This option is implied by the --null option. See also --add-file. -X, --exclude-from=FILE Exclude files matching patterns listed in FILE. File name transformations --strip-components=NUMBER Strip NUMBER leading components from file names on extraction. --transform=EXPRESSION, --xform=EXPRESSION Use sed replace EXPRESSION to transform file names. File name matching options These options affect both exclude and include patterns. --anchored Patterns match file name start. --ignore-case Ignore case. --no-anchored Patterns match after any / (default for exclusion). --no-ignore-case Case sensitive matching (default). --no-wildcards Verbatim string matching. --no-wildcards-match-slash Wildcards do not match /. --wildcards Use wildcards (default for exclusion). --wildcards-match-slash Wildcards match / (default for exclusion). Informative output --checkpoint[=N] Display progress messages every Nth record (default 10). --checkpoint-action=ACTION Run ACTION on each checkpoint. --clamp-mtime Only set time when the file is more recent than what was given with --mtime. --full-time Print file time to its full resolution. --index-file=FILE Send verbose output to FILE. -l, --check-links Print a message if not all links are dumped. --no-quote-chars=STRING Disable quoting for characters from STRING. --quote-chars=STRING Additionally quote characters from STRING. --quoting-style=STYLE Set quoting style for file and member names. Valid values for STYLE are literal, shell, shell-always, c, c-maybe, escape, locale, clocale. -R, --block-number Show block number within archive with each message. --show-omitted-dirs When listing or extracting, list each directory that does not match search criteria. --show-transformed-names, --show-stored-names Show file or archive names after transformation by --strip and --transform options. --totals[=SIGNAL] Print total bytes after processing the archive. If SIGNAL is given, print total bytes when this signal is delivered. Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1, and SIGUSR2. The SIG prefix can be omitted. --utc Print file modification times in UTC. -v, --verbose Verbosely list files processed. Each instance of this option on the command line increases the verbosity level by one. The maximum verbosity level is 3. For a detailed discussion of how various verbosity levels affect tar's output, please refer to GNU Tar Manual, subsection 2.5.2 "The '--verbose' Option". --warning=KEYWORD Enable or disable warning messages identified by KEYWORD. The messages are suppressed if KEYWORD is prefixed with no- and enabled otherwise. Multiple --warning options accumulate. Keywords controlling general tar operation: all Enable all warning messages. This is the default. none Disable all warning messages. filename-with-nuls "%s: file name read contains nul character" alone-zero-block "A lone zero block at %s" Keywords applicable for tar --create: cachedir "%s: contains a cache directory tag %s; %s" file-shrank "%s: File shrank by %s bytes; padding with zeros" xdev "%s: file is on a different filesystem; not dumped" file-ignored "%s: Unknown file type; file ignored" "%s: socket ignored" "%s: door ignored" file-unchanged "%s: file is unchanged; not dumped" ignore-archive "%s: archive cannot contain itself; not dumped" file-removed "%s: File removed before we read it" file-changed "%s: file changed as we read it" failed-read Suppresses warnings about unreadable files or directories. This keyword applies only if used together with the --ignore-failed-read option. Keywords applicable for tar --extract: existing-file "%s: skipping existing file" timestamp "%s: implausibly old time stamp %s" "%s: time stamp %s is %s s in the future" contiguous-cast "Extracting contiguous files as regular files" symlink-cast "Attempting extraction of symbolic links as hard links" unknown-cast "%s: Unknown file type '%c', extracted as normal file" ignore-newer "Current %s is newer or same age" unknown-keyword "Ignoring unknown extended header keyword '%s'" decompress-program Controls verbose description of failures occurring when trying to run alternative decompressor programs. This warning is disabled by default (unless --verbose is used). A common example of what you can get when using this warning is: $ tar --warning=decompress-program -x -f archive.Z tar (child): cannot run compress: No such file or directory tar (child): trying gzip This means that tar first tried to decompress archive.Z using compress, and, when that failed, switched to gzip. record-size "Record size = %lu blocks" Keywords controlling incremental extraction: rename-directory "%s: Directory has been renamed from %s" "%s: Directory has been renamed" new-directory "%s: Directory is new" xdev "%s: directory is on a different device: not purging" bad-dumpdir "Malformed dumpdir: 'X' never used" -w, --interactive, --confirmation Ask for confirmation for every action. Compatibility options -o When creating, same as --old-archive. When extracting, same as --no-same-owner. Size suffixes Suffix Units Byte Equivalent b Blocks SIZE x 512 B Kilobytes SIZE x 1024 c Bytes SIZE G Gigabytes SIZE x 1024^3 K Kilobytes SIZE x 1024 k Kilobytes SIZE x 1024 M Megabytes SIZE x 1024^2 P Petabytes SIZE x 1024^5 T Terabytes SIZE x 1024^4 w Words SIZE x 2 RETURN VALUE top Tar's exit code indicates whether it was able to successfully perform the requested operation, and if not, what kind of error occurred. 0 Successful termination. 1 Some files differ. If tar was invoked with the --compare (--diff, -d) command line option, this means that some files in the archive differ from their disk counterparts. If tar was given one of the --create, --append or --update options, this exit code means that some files were changed while being archived and so the resulting archive does not contain the exact copy of the file set. 2 Fatal error. This means that some fatal, unrecoverable error occurred. If a subprocess that had been invoked by tar exited with a nonzero exit code, tar itself exits with that code as well. This can happen, for example, if a compression option (e.g. -z) was used and the external compressor program failed. Another example is rmt failure during backup to a remote device. SEE ALSO top bzip2(1), compress(1), gzip(1), lzma(1), lzop(1), rmt(8), symlink(7), xz(1), zstd(1). Complete tar manual: run info tar or use emacs(1) info mode to read it. Online copies of GNU tar documentation in various formats can be found at: https://www.gnu.org/software/tar/manual BUG REPORTS top Report bugs to <bug-tar@gnu.org>. COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://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. COLOPHON top This page is part of the tar (an archiver program) project. Information about the project can be found at http://savannah.gnu.org/projects/tar/. If you have a bug report for this manual page, see http://savannah.gnu.org/bugs/?group=tar. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/tar.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-12.) 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 TAR July 11, 2022 TAR(1) Pages that refer to this page: attr(1), dpkg-deb(1), dpkg-source(1), machinectl(1), rsync(1), st(4), suffixes(7), symlink(7), cupsd-helper(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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split compressed content of the file www into pieces per 1073741824 bytes named as "backup.tar.NNN" Bash Command:<START>tar czf - www|split -b 1073741824 - www-backup.tar.<END>
split content all files file1..40000 into pieces per 1445 lines named as outputprefixNNN as digital prefix
cat file1 file2 ... file40000 | split -n r/1445 -d - outputprefix
['cat', 'split']
Output a Bash command to accomplish the following task. Task: split content all files file1..40000 into pieces per 1445 lines named as outputprefixNNN as digital prefix Bash Command:<START>cat file1 file2 ... file40000 | split -n r/1445 -d - outputprefix<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split content all files file1..40000 into pieces per 1445 lines named as outputprefixNNN as digital prefix Bash Command:<START>cat file1 file2 ... file40000 | split -n r/1445 -d - outputprefix<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split content all files file1..40000 into pieces per 1445 lines named as outputprefixNNN as digital prefix Bash Command:<START>cat file1 file2 ... file40000 | split -n r/1445 -d - outputprefix<END>
split content of the file file.txt started from second line into pieces per 4 lines named as split_NNN
tail -n +2 file.txt | split -l 4 - split_
['split', 'tail']
Output a Bash command to accomplish the following task. Task: split content of the file file.txt started from second line into pieces per 4 lines named as split_NNN Bash Command:<START>tail -n +2 file.txt | split -l 4 - split_<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n # tail\n\n> Display the last part of a file.\n> See also: `head`.\n> More information: <https://www.gnu.org/software/coreutils/tail>.\n\n- Show last 'count' lines in file:\n\n`tail --lines {{count}} {{path/to/file}}`\n\n- Print a file from a specific line number:\n\n`tail --lines +{{count}} {{path/to/file}}`\n\n- Print a specific count of bytes from the end of a given file:\n\n`tail --bytes {{count}} {{path/to/file}}`\n\n- Print the last lines of a given file and keep reading it until `Ctrl + C`:\n\n`tail --follow {{path/to/file}}`\n\n- Keep reading file until `Ctrl + C`, even if the file is inaccessible:\n\n`tail --retry --follow {{path/to/file}}`\n\n- Show last 'num' lines in 'file' and refresh every 'n' seconds:\n\n`tail --lines {{count}} --sleep-interval {{seconds}} --follow {{path/to/file}}`\n Task: split content of the file file.txt started from second line into pieces per 4 lines named as split_NNN Bash Command:<START>tail -n +2 file.txt | split -l 4 - split_<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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. tail(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tail(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TAIL(1) User Commands TAIL(1) NAME top tail - output the last part of files SYNOPSIS top tail [OPTION]... [FILE]... DESCRIPTION top Print the last 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -c, --bytes=[+]NUM output the last NUM bytes; or use -c +NUM to output starting with byte NUM of each file -f, --follow[={name|descriptor}] output appended data as the file grows; an absent option argument means 'descriptor' -F same as --follow=name --retry -n, --lines=[+]NUM output the last NUM lines, instead of the last 10; or use -n +NUM to skip NUM-1 lines at the start --max-unchanged-stats=N with --follow=name, reopen a FILE which has not changed size after N (default 5) iterations to see if it has been unlinked or renamed (this is the usual case of rotated log files); with inotify, this option is rarely useful --pid=PID with -f, terminate after process ID, PID dies -q, --quiet, --silent never output headers giving file names --retry keep trying to open a file if it is inaccessible -s, --sleep-interval=N with -f, sleep for approximately N seconds (default 1.0) between iterations; with inotify and --pid=P, check process P at least once every N seconds -v, --verbose always output headers giving file names -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit NUM may have a multiplier suffix: b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. With --follow (-f), tail defaults to following the file descriptor, which means that even if a tail'ed file is renamed, tail will continue to track its end. This default behavior is not desirable when you really want to track the actual name of the file, not the file descriptor (e.g., log rotation). Use --follow=name in that case. That causes tail to track the named file in a way that accommodates renaming, removal and creation. AUTHOR top Written by Paul Rubin, David MacKenzie, Ian Lance Taylor, 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 head(1) Full documentation <https://www.gnu.org/software/coreutils/tail> or available locally via: info '(coreutils) tail 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 TAIL(1) Pages that refer to this page: head(1), pmcd(1), pmdalogger(1), pmdasystemd(1), pmdaweblog(1), pon(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: split content of the file file.txt started from second line into pieces per 4 lines named as split_NNN Bash Command:<START>tail -n +2 file.txt | split -l 4 - split_<END>
split content of the file inputfile except lines started with "^t:" into pieces per 200 lines
cat inputfile | grep "^t\:" | split -l 200
['cat', 'split', 'grep']
Output a Bash command to accomplish the following task. Task: split content of the file inputfile except lines started with "^t:" into pieces per 200 lines Bash Command:<START>cat inputfile | grep "^t\:" | split -l 200<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{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 Task: split content of the file inputfile except lines started with "^t:" into pieces per 200 lines Bash Command:<START>cat inputfile | grep "^t\:" | split -l 200<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split content of the file inputfile except lines started with "^t:" into pieces per 200 lines Bash Command:<START>cat inputfile | grep "^t\:" | split -l 200<END>
split content of the files *.txt beginning with 1001st line into pieces per 1000 lines
cat *.txt | tail -n +1001 | split --lines=1000
['cat', 'split', 'tail']
Output a Bash command to accomplish the following task. Task: split content of the files *.txt beginning with 1001st line into pieces per 1000 lines Bash Command:<START>cat *.txt | tail -n +1001 | split --lines=1000<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n # tail\n\n> Display the last part of a file.\n> See also: `head`.\n> More information: <https://www.gnu.org/software/coreutils/tail>.\n\n- Show last 'count' lines in file:\n\n`tail --lines {{count}} {{path/to/file}}`\n\n- Print a file from a specific line number:\n\n`tail --lines +{{count}} {{path/to/file}}`\n\n- Print a specific count of bytes from the end of a given file:\n\n`tail --bytes {{count}} {{path/to/file}}`\n\n- Print the last lines of a given file and keep reading it until `Ctrl + C`:\n\n`tail --follow {{path/to/file}}`\n\n- Keep reading file until `Ctrl + C`, even if the file is inaccessible:\n\n`tail --retry --follow {{path/to/file}}`\n\n- Show last 'num' lines in 'file' and refresh every 'n' seconds:\n\n`tail --lines {{count}} --sleep-interval {{seconds}} --follow {{path/to/file}}`\n Task: split content of the files *.txt beginning with 1001st line into pieces per 1000 lines Bash Command:<START>cat *.txt | tail -n +1001 | split --lines=1000<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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. tail(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tail(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TAIL(1) User Commands TAIL(1) NAME top tail - output the last part of files SYNOPSIS top tail [OPTION]... [FILE]... DESCRIPTION top Print the last 10 lines of each FILE to standard output. With more than one FILE, precede each with a header giving the file name. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -c, --bytes=[+]NUM output the last NUM bytes; or use -c +NUM to output starting with byte NUM of each file -f, --follow[={name|descriptor}] output appended data as the file grows; an absent option argument means 'descriptor' -F same as --follow=name --retry -n, --lines=[+]NUM output the last NUM lines, instead of the last 10; or use -n +NUM to skip NUM-1 lines at the start --max-unchanged-stats=N with --follow=name, reopen a FILE which has not changed size after N (default 5) iterations to see if it has been unlinked or renamed (this is the usual case of rotated log files); with inotify, this option is rarely useful --pid=PID with -f, terminate after process ID, PID dies -q, --quiet, --silent never output headers giving file names --retry keep trying to open a file if it is inaccessible -s, --sleep-interval=N with -f, sleep for approximately N seconds (default 1.0) between iterations; with inotify and --pid=P, check process P at least once every N seconds -v, --verbose always output headers giving file names -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit NUM may have a multiplier suffix: b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. With --follow (-f), tail defaults to following the file descriptor, which means that even if a tail'ed file is renamed, tail will continue to track its end. This default behavior is not desirable when you really want to track the actual name of the file, not the file descriptor (e.g., log rotation). Use --follow=name in that case. That causes tail to track the named file in a way that accommodates renaming, removal and creation. AUTHOR top Written by Paul Rubin, David MacKenzie, Ian Lance Taylor, 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 head(1) Full documentation <https://www.gnu.org/software/coreutils/tail> or available locally via: info '(coreutils) tail 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 TAIL(1) Pages that refer to this page: head(1), pmcd(1), pmdalogger(1), pmdasystemd(1), pmdaweblog(1), pon(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: split content of the files *.txt beginning with 1001st line into pieces per 1000 lines Bash Command:<START>cat *.txt | tail -n +1001 | split --lines=1000<END>
split file "$file into pieces named with 5 character suffix
split -a 5 $file
['split']
Output a Bash command to accomplish the following task. Task: split file "$file into pieces named with 5 character suffix Bash Command:<START>split -a 5 $file<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file "$file into pieces named with 5 character suffix Bash Command:<START>split -a 5 $file<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file "$file into pieces named with 5 character suffix Bash Command:<START>split -a 5 $file<END>
split file "${fspec} into pieces named as "xyzzyNNN" with numeric prefix from 1 to 6
split --number=l/6 ${fspec} xyzzy.
['split']
Output a Bash command to accomplish the following task. Task: split file "${fspec} into pieces named as "xyzzyNNN" with numeric prefix from 1 to 6 Bash Command:<START>split --number=l/6 ${fspec} xyzzy.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file "${fspec} into pieces named as "xyzzyNNN" with numeric prefix from 1 to 6 Bash Command:<START>split --number=l/6 ${fspec} xyzzy.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file "${fspec} into pieces named as "xyzzyNNN" with numeric prefix from 1 to 6 Bash Command:<START>split --number=l/6 ${fspec} xyzzy.<END>
split file "your_file" into pieces per 9 lines
split -l9 your_file
['split']
Output a Bash command to accomplish the following task. Task: split file "your_file" into pieces per 9 lines Bash Command:<START>split -l9 your_file<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file "your_file" into pieces per 9 lines Bash Command:<START>split -l9 your_file<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file "your_file" into pieces per 9 lines Bash Command:<START>split -l9 your_file<END>
split file /etc/gconf/schemas/gnome-terminal.schemas into pieces per 1000000 lines
split -n 1000000 /etc/gconf/schemas/gnome-terminal.schemas
['split']
Output a Bash command to accomplish the following task. Task: split file /etc/gconf/schemas/gnome-terminal.schemas into pieces per 1000000 lines Bash Command:<START>split -n 1000000 /etc/gconf/schemas/gnome-terminal.schemas<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file /etc/gconf/schemas/gnome-terminal.schemas into pieces per 1000000 lines Bash Command:<START>split -n 1000000 /etc/gconf/schemas/gnome-terminal.schemas<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file /etc/gconf/schemas/gnome-terminal.schemas into pieces per 1000000 lines Bash Command:<START>split -n 1000000 /etc/gconf/schemas/gnome-terminal.schemas<END>
split file /usr/bin/firefox into pieces per 1000 lines
split -n 1000 /usr/bin/firefox
['split']
Output a Bash command to accomplish the following task. Task: split file /usr/bin/firefox into pieces per 1000 lines Bash Command:<START>split -n 1000 /usr/bin/firefox<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file /usr/bin/firefox into pieces per 1000 lines Bash Command:<START>split -n 1000 /usr/bin/firefox<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file /usr/bin/firefox into pieces per 1000 lines Bash Command:<START>split -n 1000 /usr/bin/firefox<END>
split file /usr/bin/gcc into pieces per 100000 lines
split -n 100000 /usr/bin/gcc
['split']
Output a Bash command to accomplish the following task. Task: split file /usr/bin/gcc into pieces per 100000 lines Bash Command:<START>split -n 100000 /usr/bin/gcc<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file /usr/bin/gcc into pieces per 100000 lines Bash Command:<START>split -n 100000 /usr/bin/gcc<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file /usr/bin/gcc into pieces per 100000 lines Bash Command:<START>split -n 100000 /usr/bin/gcc<END>
split file abc.txt into pieces per 1500000000 bytes named as "abc.NNN"
split --bytes=1500000000 abc.txt abc
['split']
Output a Bash command to accomplish the following task. Task: split file abc.txt into pieces per 1500000000 bytes named as "abc.NNN" Bash Command:<START>split --bytes=1500000000 abc.txt abc<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file abc.txt into pieces per 1500000000 bytes named as "abc.NNN" Bash Command:<START>split --bytes=1500000000 abc.txt abc<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file abc.txt into pieces per 1500000000 bytes named as "abc.NNN" Bash Command:<START>split --bytes=1500000000 abc.txt abc<END>
split file data.csv into pieces per 100 lines
split -l 100 date.csv
['split']
Output a Bash command to accomplish the following task. Task: split file data.csv into pieces per 100 lines Bash Command:<START>split -l 100 date.csv<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file data.csv into pieces per 100 lines Bash Command:<START>split -l 100 date.csv<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file data.csv into pieces per 100 lines Bash Command:<START>split -l 100 date.csv<END>
split file input.txt into pieces per 1 line named output.NNNNN
split --lines=1 --suffix-length=5 input.txt output.
['split']
Output a Bash command to accomplish the following task. Task: split file input.txt into pieces per 1 line named output.NNNNN Bash Command:<START>split --lines=1 --suffix-length=5 input.txt output.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file input.txt into pieces per 1 line named output.NNNNN Bash Command:<START>split --lines=1 --suffix-length=5 input.txt output.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file input.txt into pieces per 1 line named output.NNNNN Bash Command:<START>split --lines=1 --suffix-length=5 input.txt output.<END>
split file t.txt into pieces per 30000000 lines named as "t.NN" with numeric suffix
split --lines=30000000 --numeric-suffixes --suffix-length=2 t.txt t
['split']
Output a Bash command to accomplish the following task. Task: split file t.txt into pieces per 30000000 lines named as "t.NN" with numeric suffix Bash Command:<START>split --lines=30000000 --numeric-suffixes --suffix-length=2 t.txt t<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split file t.txt into pieces per 30000000 lines named as "t.NN" with numeric suffix Bash Command:<START>split --lines=30000000 --numeric-suffixes --suffix-length=2 t.txt t<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split file t.txt into pieces per 30000000 lines named as "t.NN" with numeric suffix Bash Command:<START>split --lines=30000000 --numeric-suffixes --suffix-length=2 t.txt t<END>
split listing of the current directory into pieces per 500 lines named "outputXYZNNN"
ls | split -l 500 - outputXYZ.
['ls', 'split']
Output a Bash command to accomplish the following task. Task: split listing of the current directory into pieces per 500 lines named "outputXYZNNN" Bash Command:<START>ls | split -l 500 - outputXYZ.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # ls\n\n> List directory contents.\n> More information: <https://www.gnu.org/software/coreutils/ls>.\n\n- List files one per line:\n\n`ls -1`\n\n- List all files, including hidden files:\n\n`ls -a`\n\n- List all files, with trailing `/` added to directory names:\n\n`ls -F`\n\n- Long format list (permissions, ownership, size, and modification date) of all files:\n\n`ls -la`\n\n- Long format list with size displayed using human-readable units (KiB, MiB, GiB):\n\n`ls -lh`\n\n- Long format list sorted by size (descending) recursively:\n\n`ls -lSR`\n\n- Long format list of all files, sorted by modification date (oldest first):\n\n`ls -ltr`\n\n- Only list directories:\n\n`ls -d */`\n # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split listing of the current directory into pieces per 500 lines named "outputXYZNNN" Bash Command:<START>ls | split -l 500 - outputXYZ.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: ls(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ls(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON LS(1) User Commands LS(1) NAME top ls - list directory contents SYNOPSIS top ls [OPTION]... [FILE]... DESCRIPTION top List information about the FILEs (the current directory by default). Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. Mandatory arguments to long options are mandatory for short options too. -a, --all do not ignore entries starting with . -A, --almost-all do not list implied . and .. --author with -l, print the author of each file -b, --escape print C-style escapes for nongraphic characters --block-size=SIZE with -l, scale sizes by SIZE when printing them; e.g., '--block-size=M'; see SIZE format below -B, --ignore-backups do not list implied entries ending with ~ -c with -lt: sort by, and show, ctime (time of last change of file status information); with -l: show ctime and sort by name; otherwise: sort by ctime, newest first -C list entries by columns --color[=WHEN] color the output WHEN; more info below -d, --directory list directories themselves, not their contents -D, --dired generate output designed for Emacs' dired mode -f list all entries in directory order -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN --file-type likewise, except do not append '*' --format=WORD across -x, commas -m, horizontal -x, long -l, single-column -1, verbose -l, vertical -C --full-time like -l --time-style=full-iso -g like -l, but do not list owner --group-directories-first group directories before files; can be augmented with a --sort option, but any use of --sort=none (-U) disables grouping -G, --no-group in a long listing, don't print group names -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc. --si likewise, but use powers of 1000 not 1024 -H, --dereference-command-line follow symbolic links listed on the command line --dereference-command-line-symlink-to-dir follow each command line symbolic link that points to a directory --hide=PATTERN do not list implied entries matching shell PATTERN (overridden by -a or -A) --hyperlink[=WHEN] hyperlink file names WHEN --indicator-style=WORD append indicator with style WORD to entry names: none (default), slash (-p), file-type (--file-type), classify (-F) -i, --inode print the index number of each file -I, --ignore=PATTERN do not list implied entries matching shell PATTERN -k, --kibibytes default to 1024-byte blocks for file system usage; used only with -s and per directory totals -l use a long listing format -L, --dereference when showing file information for a symbolic link, show information for the file the link references rather than for the link itself -m fill width with a comma separated list of entries -n, --numeric-uid-gid like -l, but list numeric user and group IDs -N, --literal print entry names without quoting -o like -l, but do not list group information -p, --indicator-style=slash append / indicator to directories -q, --hide-control-chars print ? instead of nongraphic characters --show-control-chars show nongraphic characters as-is (the default, unless program is 'ls' and output is a terminal) -Q, --quote-name enclose entry names in double quotes --quoting-style=WORD use quoting style WORD for entry names: literal, locale, shell, shell-always, shell-escape, shell-escape-always, c, escape (overrides QUOTING_STYLE environment variable) -r, --reverse reverse order while sorting -R, --recursive list subdirectories recursively -s, --size print the allocated size of each file, in blocks -S sort by file size, largest first --sort=WORD sort by WORD instead of name: none (-U), size (-S), time (-t), version (-v), extension (-X), width --time=WORD select which timestamp used to display or sort; access time (-u): atime, access, use; metadata change time (-c): ctime, status; modified time (default): mtime, modification; birth time: birth, creation; with -l, WORD determines which time to show; with --sort=time, sort by WORD (newest first) --time-style=TIME_STYLE time/date format with -l; see TIME_STYLE below -t sort by time, newest first; see --time -T, --tabsize=COLS assume tab stops at each COLS instead of 8 -u with -lt: sort by, and show, access time; with -l: show access time and sort by name; otherwise: sort by access time, newest first -U do not sort; list entries in directory order -v natural sort of (version) numbers within text -w, --width=COLS set output width to COLS. 0 means no limit -x list entries by lines instead of by columns -X sort alphabetically by entry extension -Z, --context print any security context of each file --zero end each output line with NUL, not newline -1 list one file per line --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT. FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2, then FORMAT1 applies to non-recent files and FORMAT2 to recent files. TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale. Also the TIME_STYLE environment variable sets the default style to use. The WHEN argument defaults to 'always' and can also be 'auto' or 'never'. Using color to distinguish file types is disabled both by default and with --color=never. With --color=auto, ls emits color codes only when standard output is connected to a terminal. The LS_COLORS environment variable can change the settings. Use the dircolors(1) command to set it. Exit status: 0 if OK, 1 if minor problems (e.g., cannot access subdirectory), 2 if serious trouble (e.g., cannot access command-line argument). 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 dircolors(1) Full documentation <https://www.gnu.org/software/coreutils/ls> or available locally via: info '(coreutils) ls 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 LS(1) Pages that refer to this page: column(1), find(1), namei(1), stat(2), statx(2), glob(3), strverscmp(3), core(5), dir_colors(5), passwd(5), proc(5), mq_overview(7), symlink(7), lsblk(8), lsof(8), setfiles(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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split listing of the current directory into pieces per 500 lines named "outputXYZNNN" Bash Command:<START>ls | split -l 500 - outputXYZ.<END>
split processed content of the file inout_file into pieces per 2000000 named as "out-prefix-NNN"
sed 's/\(.....\)\(.....\)/\1\n\2/' input_file | split -l 2000000 - out-prefix-
['split', 'sed']
Output a Bash command to accomplish the following task. Task: split processed content of the file inout_file into pieces per 2000000 named as "out-prefix-NNN" Bash Command:<START>sed 's/\(.....\)\(.....\)/\1\n\2/' input_file | split -l 2000000 - out-prefix-<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\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: split processed content of the file inout_file into pieces per 2000000 named as "out-prefix-NNN" Bash Command:<START>sed 's/\(.....\)\(.....\)/\1\n\2/' input_file | split -l 2000000 - out-prefix-<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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. 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: split processed content of the file inout_file into pieces per 2000000 named as "out-prefix-NNN" Bash Command:<START>sed 's/\(.....\)\(.....\)/\1\n\2/' input_file | split -l 2000000 - out-prefix-<END>
split processed content of the file temp into pieces per 1 line named "tempNNN" with numeric suffix
sed 's/3d3d/\n&/2g' temp | split -dl1 - temp
['split', 'sed']
Output a Bash command to accomplish the following task. Task: split processed content of the file temp into pieces per 1 line named "tempNNN" with numeric suffix Bash Command:<START>sed 's/3d3d/\n&/2g' temp | split -dl1 - temp<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\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: split processed content of the file temp into pieces per 1 line named "tempNNN" with numeric suffix Bash Command:<START>sed 's/3d3d/\n&/2g' temp | split -dl1 - temp<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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. 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: split processed content of the file temp into pieces per 1 line named "tempNNN" with numeric suffix Bash Command:<START>sed 's/3d3d/\n&/2g' temp | split -dl1 - temp<END>
split result of the command "tar [your params]" into pieces per 500 mb named as "output_prefixNNN"
tar [your params] |split -b 500m - output_prefix
['tar', 'split']
Output a Bash command to accomplish the following task. Task: split result of the command "tar [your params]" into pieces per 500 mb named as "output_prefixNNN" Bash Command:<START>tar [your params] |split -b 500m - output_prefix<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # tar\n\n> Archiving utility.\n> Often combined with a compression method, such as `gzip` or `bzip2`.\n> More information: <https://www.gnu.org/software/tar>.\n\n- [c]reate an archive and write it to a [f]ile:\n\n`tar cf {{path/to/target.tar}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive and write it to a [f]ile:\n\n`tar czf {{path/to/target.tar.gz}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive from a directory using relative paths:\n\n`tar czf {{path/to/target.tar.gz}} --directory={{path/to/directory}} .`\n\n- E[x]tract a (compressed) archive [f]ile into the current directory [v]erbosely:\n\n`tar xvf {{path/to/source.tar[.gz|.bz2|.xz]}}`\n\n- E[x]tract a (compressed) archive [f]ile into the target directory:\n\n`tar xf {{path/to/source.tar[.gz|.bz2|.xz]}} --directory={{path/to/directory}}`\n\n- [c]reate a compressed archive and write it to a [f]ile, using the file extension to [a]utomatically determine the compression program:\n\n`tar caf {{path/to/target.tar.xz}} {{path/to/file1 path/to/file2 ...}}`\n\n- Lis[t] the contents of a tar [f]ile [v]erbosely:\n\n`tar tvf {{path/to/source.tar}}`\n\n- E[x]tract files matching a pattern from an archive [f]ile:\n\n`tar xf {{path/to/source.tar}} --wildcards "{{*.html}}"`\n # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split result of the command "tar [your params]" into pieces per 500 mb named as "output_prefixNNN" Bash Command:<START>tar [your params] |split -b 500m - output_prefix<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: tar(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tar(1) Linux manual page NAME | SYNOPSIS | NOTE | DESCRIPTION | OPTIONS | RETURN VALUE | SEE ALSO | BUG REPORTS | COPYRIGHT | COLOPHON TAR(1) GNU TAR Manual TAR(1) NAME top tar - an archiving utility SYNOPSIS top Traditional usage tar {A|c|d|r|t|u|x}[GnSkUWOmpsMBiajJzZhPlRvwo] [ARG...] UNIX-style usage tar -A [OPTIONS] -f ARCHIVE ARCHIVE... tar -c [-f ARCHIVE] [OPTIONS] [FILE...] tar -d [-f ARCHIVE] [OPTIONS] [FILE...] tar -r [-f ARCHIVE] [OPTIONS] [FILE...] tar -t [-f ARCHIVE] [OPTIONS] [MEMBER...] tar -u [-f ARCHIVE] [OPTIONS] [FILE...] tar -x [-f ARCHIVE] [OPTIONS] [MEMBER...] GNU-style usage tar {--catenate|--concatenate} [OPTIONS] --file ARCHIVE ARCHIVE... tar --create [--file ARCHIVE] [OPTIONS] [FILE...] tar {--diff|--compare} [--file ARCHIVE] [OPTIONS] [FILE...] tar --delete [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --append [--file ARCHIVE] [OPTIONS] [FILE...] tar --list [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --test-label [--file ARCHIVE] [OPTIONS] [LABEL...] tar --update [--file ARCHIVE] [OPTIONS] [FILE...] tar {--extract|--get} [--file ARCHIVE] [OPTIONS] [MEMBER...] NOTE top This manpage is a short description of GNU tar. For a detailed discussion, including examples and usage recommendations, refer to the GNU Tar Manual available in texinfo format. If the info reader and the tar documentation are properly installed on your system, the command info tar should give you access to the complete manual. You can also view the manual using the info mode in emacs(1), or find it in various formats online at https://www.gnu.org/software/tar/manual If any discrepancies occur between this manpage and the GNU Tar Manual, the later shall be considered the authoritative source. DESCRIPTION top GNU tar is an archiving program designed to store multiple files in a single file (an archive), and to manipulate such archives. The archive can be either a regular file or a device (e.g. a tape drive, hence the name of the program, which stands for tape archiver), which can be located either on the local or on a remote machine. Option styles Options to GNU tar can be given in three different styles. In traditional style, the first argument is a cluster of option letters and all subsequent arguments supply arguments to those options that require them. The arguments are read in the same order as the option letters. Any command line words that remain after all options have been processed are treated as non-option arguments: file or archive member names. For example, the c option requires creating the archive, the v option requests the verbose operation, and the f option takes an argument that sets the name of the archive to operate upon. The following command, written in the traditional style, instructs tar to store all files from the directory /etc into the archive file etc.tar, verbosely listing the files being archived: tar cfv etc.tar /etc In UNIX or short-option style, each option letter is prefixed with a single dash, as in other command line utilities. If an option takes an argument, the argument follows it, either as a separate command line word, or immediately following the option. However, if the option takes an optional argument, the argument must follow the option letter without any intervening whitespace, as in -g/tmp/snar.db. Any number of options not taking arguments can be clustered together after a single dash, e.g. -vkp. An option that takes an argument (whether mandatory or optional) can appear at the end of such a cluster, e.g. -vkpf a.tar. The example command above written in the short-option style could look like: tar -cvf etc.tar /etc or tar -c -v -f etc.tar /etc In GNU or long-option style, each option begins with two dashes and has a meaningful name, consisting of lower-case letters and dashes. When used, the long option can be abbreviated to its initial letters, provided that this does not create ambiguity. Arguments to long options are supplied either as a separate command line word, immediately following the option, or separated from the option by an equals sign with no intervening whitespace. Optional arguments must always use the latter method. Here are several ways of writing the example command in this style: tar --create --file etc.tar --verbose /etc or (abbreviating some options): tar --cre --file=etc.tar --verb /etc The options in all three styles can be intermixed, although doing so with old options is not encouraged. Operation mode The options listed in the table below tell GNU tar what operation it is to perform. Exactly one of them must be given. The meaning of non-option arguments depends on the operation mode requested. -A, --catenate, --concatenate Append archives to the end of another archive. The arguments are treated as the names of archives to append. All archives must be of the same format as the archive they are appended to, otherwise the resulting archive might be unusable with non-GNU implementations of tar. Notice also that when more than one archive is given, the members from archives other than the first one will be accessible in the resulting archive only when using the -i (--ignore-zeros) option. Compressed archives cannot be concatenated. -c, --create Create a new archive. Arguments supply the names of the files to be archived. Directories are archived recursively, unless the --no-recursion option is given. -d, --diff, --compare Find differences between archive and file system. The arguments are optional and specify archive members to compare. If not given, the current working directory is assumed. --delete Delete from the archive. The arguments supply names of the archive members to be removed. At least one argument must be given. This option does not operate on compressed archives. There is no short option equivalent. -r, --append Append files to the end of an archive. Arguments have the same meaning as for -c (--create). -t, --list List the contents of an archive. Arguments are optional. When given, they specify the names of the members to list. --test-label Test the archive volume label and exit. When used without arguments, it prints the volume label (if any) and exits with status 0. When one or more command line arguments are given. tar compares the volume label with each argument. It exits with code 0 if a match is found, and with code 1 otherwise. No output is displayed, unless used together with the -v (--verbose) option. There is no short option equivalent for this option. -u, --update Append files which are newer than the corresponding copy in the archive. Arguments have the same meaning as with the -c and -r options. Notice, that newer files don't replace their old archive copies, but instead are appended to the end of archive. The resulting archive can thus contain several members of the same name, corresponding to various versions of the same file. -x, --extract, --get Extract files from an archive. Arguments are optional. When given, they specify names of the archive members to be extracted. --show-defaults Show built-in defaults for various tar options and exit. -?, --help Display a short option summary and exit. --usage Display a list of available options and exit. --version Print program version and copyright information and exit. OPTIONS top Operation modifiers --check-device Check device numbers when creating incremental archives (default). -g, --listed-incremental=FILE Handle new GNU-format incremental backups. FILE is the name of a snapshot file, where tar stores additional information which is used to decide which files changed since the previous incremental dump and, consequently, must be dumped again. If FILE does not exist when creating an archive, it will be created and all files will be added to the resulting archive (the level 0 dump). To create incremental archives of non-zero level N, you need a copy of the snapshot file created for level N-1, and use it as FILE. When listing or extracting, the actual content of FILE is not inspected, it is needed only due to syntactical requirements. It is therefore common practice to use /dev/null in its place. --hole-detection=METHOD Use METHOD to detect holes in sparse files. This option implies --sparse. Valid values for METHOD are seek and raw. Default is seek with fallback to raw when not applicable. -G, --incremental Handle old GNU-format incremental backups. --ignore-failed-read Do not exit with nonzero on unreadable files. --level=NUMBER Set dump level for a created listed-incremental archive. Currently only --level=0 is meaningful: it instructs tar to truncate the snapshot file before dumping, thereby forcing a level 0 dump. -n, --seek Assume the archive is seekable. Normally tar determines automatically whether the archive can be seeked or not. This option is intended for use in cases when such recognition fails. It takes effect only if the archive is open for reading (e.g. with --list or --extract options). --no-check-device Do not check device numbers when creating incremental archives. --no-seek Assume the archive is not seekable. --occurrence[=N] Process only the Nth occurrence of each file in the archive. This option is valid only when used with one of the following subcommands: --delete, --diff, --extract or --list and when a list of files is given either on the command line or via the -T option. The default N is 1. --restrict Disable the use of some potentially harmful options. --sparse-version=MAJOR[.MINOR] Set which version of the sparse format to use. This option implies --sparse. Valid argument values are 0.0, 0.1, and 1.0. For a detailed discussion of sparse formats, refer to the GNU Tar Manual, appendix D, "Sparse Formats". Using the info reader, it can be accessed running the following command: info tar 'Sparse Formats'. -S, --sparse Handle sparse files efficiently. Some files in the file system may have segments which were actually never written (quite often these are database files created by such systems as DBM). When given this option, tar attempts to determine if the file is sparse prior to archiving it, and if so, to reduce the resulting archive size by not dumping empty parts of the file. Overwrite control These options control tar actions when extracting a file over an existing copy on disk. -k, --keep-old-files Don't replace existing files when extracting. --keep-newer-files Don't replace existing files that are newer than their archive copies. --keep-directory-symlink Don't replace existing symlinks to directories when extracting. --no-overwrite-dir Preserve metadata of existing directories. --one-top-level[=DIR] Extract all files into DIR, or, if used without argument, into a subdirectory named by the base name of the archive (minus standard compression suffixes recognizable by --auto-compress). --overwrite Overwrite existing files when extracting. --overwrite-dir Overwrite metadata of existing directories when extracting (default). --recursive-unlink Recursively remove all files in the directory prior to extracting it. --remove-files Remove files from disk after adding them to the archive. --skip-old-files Don't replace existing files when extracting, silently skip over them. -U, --unlink-first Remove each file prior to extracting over it. -W, --verify Verify the archive after writing it. Output stream selection --ignore-command-error Ignore subprocess exit codes. --no-ignore-command-error Treat non-zero exit codes of children as error (default). -O, --to-stdout Extract files to standard output. --to-command=COMMAND Pipe extracted files to COMMAND. The argument is the pathname of an external program, optionally with command line arguments. The program will be invoked and the contents of the file being extracted supplied to it on its standard input. Additional data will be supplied via the following environment variables: TAR_FILETYPE Type of the file. It is a single letter with the following meaning: f Regular file d Directory l Symbolic link h Hard link b Block device c Character device Currently only regular files are supported. TAR_MODE File mode, an octal number. TAR_FILENAME The name of the file. TAR_REALNAME Name of the file as stored in the archive. TAR_UNAME Name of the file owner. TAR_GNAME Name of the file owner group. TAR_ATIME Time of last access. It is a decimal number, representing seconds since the Epoch. If the archive provides times with nanosecond precision, the nanoseconds are appended to the timestamp after a decimal point. TAR_MTIME Time of last modification. TAR_CTIME Time of last status change. TAR_SIZE Size of the file. TAR_UID UID of the file owner. TAR_GID GID of the file owner. Additionally, the following variables contain information about tar operation mode and the archive being processed: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. Handling of file attributes --atime-preserve[=METHOD] Preserve access times on dumped files, either by restoring the times after reading (METHOD=replace, this is the default) or by not setting the times in the first place (METHOD=system). --delay-directory-restore Delay setting modification times and permissions of extracted directories until the end of extraction. Use this option when extracting from an archive which has unusual member ordering. --group=NAME[:GID] Force NAME as group for added files. If GID is not supplied, NAME can be either a user name or numeric GID. In this case the missing part (GID or name) will be inferred from the current host's group database. When used with --group-map=FILE, affects only those files whose owner group is not listed in FILE. --group-map=FILE Read group translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single group. It must consist of two fields, delimited by any amount of whitespace: OLDGRP NEWGRP[:NEWGID] OLDGRP is either a valid group name or a GID prefixed with +. Unless NEWGID is supplied, NEWGRP must also be either a valid group name or a +GID. Otherwise, both NEWGRP and NEWGID need not be listed in the system group database. As a result, each input file with owner group OLDGRP will be stored in archive with owner group NEWGRP and GID NEWGID. --mode=CHANGES Force symbolic mode CHANGES for added files. --mtime=DATE-OR-FILE Set mtime for added files. DATE-OR-FILE is either a date/time in almost arbitrary format, or the name of an existing file. In the latter case the mtime of that file will be used. -m, --touch Don't extract file modified time. --no-delay-directory-restore Cancel the effect of the prior --delay-directory-restore option. --no-same-owner Extract files as yourself (default for ordinary users). --no-same-permissions Apply the user's umask when extracting permissions from the archive (default for ordinary users). --numeric-owner Always use numbers for user/group names. --owner=NAME[:UID] Force NAME as owner for added files. If UID is not supplied, NAME can be either a user name or numeric UID. In this case the missing part (UID or name) will be inferred from the current host's user database. When used with --owner-map=FILE, affects only those files whose owner is not listed in FILE. --owner-map=FILE Read owner translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single UID. It must consist of two fields, delimited by any amount of whitespace: OLDUSR NEWUSR[:NEWUID] OLDUSR is either a valid user name or a UID prefixed with +. Unless NEWUID is supplied, NEWUSR must also be either a valid user name or a +UID. Otherwise, both NEWUSR and NEWUID need not be listed in the system user database. As a result, each input file owned by OLDUSR will be stored in archive with owner name NEWUSR and UID NEWUID. -p, --preserve-permissions, --same-permissions Set permissions of extracted files to those recorded in the archive (default for superuser). --same-owner Try extracting files with the same ownership as exists in the archive (default for superuser). -s, --preserve-order, --same-order Tell tar that the list of file names to process is sorted in the same order as the files in the archive. --sort=ORDER When creating an archive, sort directory entries according to ORDER, which is one of none, name, or inode. The default is --sort=none, which stores archive members in the same order as returned by the operating system. Using --sort=name ensures the member ordering in the created archive is uniform and reproducible. Using --sort=inode reduces the number of disk seeks made when creating the archive and thus can considerably speed up archivation. This sorting order is supported only if the underlying system provides the necessary information. Extended file attributes --acls Enable POSIX ACLs support. --no-acls Disable POSIX ACLs support. --selinux Enable SELinux context support. --no-selinux Disable SELinux context support. --xattrs Enable extended attributes support. --no-xattrs Disable extended attributes support. --xattrs-exclude=PATTERN Specify the exclude pattern for xattr keys. PATTERN is a globbing pattern, e.g. --xattrs-exclude='user.*' to include only attributes from the user namespace. --xattrs-include=PATTERN Specify the include pattern for xattr keys. PATTERN is a globbing pattern. Device selection and switching -f, --file=ARCHIVE Use archive file or device ARCHIVE. If this option is not given, tar will first examine the environment variable `TAPE'. If it is set, its value will be used as the archive name. Otherwise, tar will assume the compiled-in default. The default value can be inspected either using the --show-defaults option, or at the end of the tar --help output. An archive name that has a colon in it specifies a file or device on a remote machine. The part before the colon is taken as the machine name or IP address, and the part after it as the file or device pathname, e.g.: --file=remotehost:/dev/sr0 An optional username can be prefixed to the hostname, placing a @ sign between them. By default, the remote host is accessed via the rsh(1) command. Nowadays it is common to use ssh(1) instead. You can do so by giving the following command line option: --rsh-command=/usr/bin/ssh The remote machine should have the rmt(8) command installed. If its pathname does not match tar's default, you can inform tar about the correct pathname using the --rmt-command option. --force-local Archive file is local even if it has a colon. -F, --info-script=COMMAND, --new-volume-script=COMMAND Run COMMAND at the end of each tape (implies -M). The command can include arguments. When started, it will inherit tar's environment plus the following variables: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. TAR_FD File descriptor which can be used to communicate the new volume name to tar. If the info script fails, tar exits; otherwise, it begins writing the next volume. -L, --tape-length=N Change tape after writing Nx1024 bytes. If N is followed by a size suffix (see the subsection Size suffixes below), the suffix specifies the multiplicative factor to be used instead of 1024. This option implies -M. -M, --multi-volume Create/list/extract multi-volume archive. --rmt-command=COMMAND Use COMMAND instead of rmt when accessing remote archives. See the description of the -f option, above. --rsh-command=COMMAND Use COMMAND instead of rsh when accessing remote archives. See the description of the -f option, above. --volno-file=FILE When this option is used in conjunction with --multi-volume, tar will keep track of which volume of a multi-volume archive it is working in FILE. Device blocking -b, --blocking-factor=BLOCKS Set record size to BLOCKSx512 bytes. -B, --read-full-records When listing or extracting, accept incomplete input records after end-of-file marker. -i, --ignore-zeros Ignore zeroed blocks in archive. Normally two consecutive 512-blocks filled with zeroes mean EOF and tar stops reading after encountering them. This option instructs it to read further and is useful when reading archives created with the -A option. --record-size=NUMBER Set record size. NUMBER is the number of bytes per record. It must be multiple of 512. It can can be suffixed with a size suffix, e.g. --record-size=10K, for 10 Kilobytes. See the subsection Size suffixes, for a list of valid suffixes. Archive format selection -H, --format=FORMAT Create archive of the given format. Valid formats are: gnu GNU tar 1.13.x format oldgnu GNU format as per tar <= 1.12. pax, posix POSIX 1003.1-2001 (pax) format. ustar POSIX 1003.1-1988 (ustar) format. v7 Old V7 tar format. --old-archive, --portability Same as --format=v7. --pax-option=keyword[[:]=value][,keyword[[:]=value]]... Control pax keywords when creating PAX archives (-H pax). This option is equivalent to the -o option of the pax(1) utility. --posix Same as --format=posix. -V, --label=TEXT Create archive with volume name TEXT. If listing or extracting, use TEXT as a globbing pattern for volume name. Compression options -a, --auto-compress Use archive suffix to determine the compression program. -I, --use-compress-program=COMMAND Filter data through COMMAND. It must accept the -d option, for decompression. The argument can contain command line options. -j, --bzip2 Filter the archive through bzip2(1). -J, --xz Filter the archive through xz(1). --lzip Filter the archive through lzip(1). --lzma Filter the archive through lzma(1). --lzop Filter the archive through lzop(1). --no-auto-compress Do not use archive suffix to determine the compression program. -z, --gzip, --gunzip, --ungzip Filter the archive through gzip(1). -Z, --compress, --uncompress Filter the archive through compress(1). --zstd Filter the archive through zstd(1). Local file selection --add-file=FILE Add FILE to the archive (useful if its name starts with a dash). --backup[=CONTROL] Backup before removal. The CONTROL argument, if supplied, controls the backup policy. Its valid values are: none, off Never make backups. t, numbered Make numbered backups. nil, existing Make numbered backups if numbered backups exist, simple backups otherwise. never, simple Always make simple backups If CONTROL is not given, the value is taken from the VERSION_CONTROL environment variable. If it is not set, existing is assumed. -C, --directory=DIR Change to DIR before performing any operations. This option is order-sensitive, i.e. it affects all options that follow. --exclude=PATTERN Exclude files matching PATTERN, a glob(3)-style wildcard pattern. --exclude-backups Exclude backup and lock files. --exclude-caches Exclude contents of directories containing file CACHEDIR.TAG, except for the tag file itself. --exclude-caches-all Exclude directories containing file CACHEDIR.TAG and the file itself. --exclude-caches-under Exclude everything under directories containing CACHEDIR.TAG --exclude-ignore=FILE Before dumping a directory, see if it contains FILE. If so, read exclusion patterns from this file. The patterns affect only the directory itself. --exclude-ignore-recursive=FILE Same as --exclude-ignore, except that patterns from FILE affect both the directory and all its subdirectories. --exclude-tag=FILE Exclude contents of directories containing FILE, except for FILE itself. --exclude-tag-all=FILE Exclude directories containing FILE. --exclude-tag-under=FILE Exclude everything under directories containing FILE. --exclude-vcs Exclude version control system directories. --exclude-vcs-ignores Exclude files that match patterns read from VCS-specific ignore files. Supported files are: .cvsignore, .gitignore, .bzrignore, and .hgignore. -h, --dereference Follow symlinks; archive and dump the files they point to. --hard-dereference Follow hard links; archive and dump the files they refer to. -K, --starting-file=MEMBER Begin at the given member in the archive. --newer-mtime=DATE Work on files whose data changed after the DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --no-null Disable the effect of the previous --null option. --no-recursion Avoid descending automatically in directories. --no-unquote Do not unquote input file or member names. --no-verbatim-files-from Treat each line read from a file list as if it were supplied in the command line. I.e., leading and trailing whitespace is removed and, if the resulting string begins with a dash, it is treated as tar command line option. This is the default behavior. The --no-verbatim-files-from option is provided as a way to restore it after --verbatim-files-from option. This option is positional: it affects all --files-from options that occur after it in, until --verbatim-files-from option or end of line, whichever occurs first. It is implied by the --no-null option. --null Instruct subsequent -T options to read null-terminated names verbatim (disables special handling of names that start with a dash). See also --verbatim-files-from. -N, --newer=DATE, --after-date=DATE Only store files newer than DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --one-file-system Stay in local file system when creating archive. -P, --absolute-names Don't strip leading slashes from file names when creating archives. --recursion Recurse into directories (default). --suffix=STRING Backup before removal, override usual suffix. Default suffix is ~, unless overridden by environment variable SIMPLE_BACKUP_SUFFIX. -T, --files-from=FILE Get names to extract or create from FILE. Unless specified otherwise, the FILE must contain a list of names separated by ASCII LF (i.e. one name per line). The names read are handled the same way as command line arguments. They undergo quote removal and word splitting, and any string that starts with a - is handled as tar command line option. If this behavior is undesirable, it can be turned off using the --verbatim-files-from option. The --null option instructs tar that the names in FILE are separated by ASCII NUL character, instead of LF. It is useful if the list is generated by find(1) -print0 predicate. --unquote Unquote file or member names (default). --verbatim-files-from Treat each line obtained from a file list as a file name, even if it starts with a dash. File lists are supplied with the --files-from (-T) option. The default behavior is to handle names supplied in file lists as if they were typed in the command line, i.e. any names starting with a dash are treated as tar options. The --verbatim-files-from option disables this behavior. This option affects all --files-from options that occur after it in the command line. Its effect is reverted by the --no-verbatim-files-from option. This option is implied by the --null option. See also --add-file. -X, --exclude-from=FILE Exclude files matching patterns listed in FILE. File name transformations --strip-components=NUMBER Strip NUMBER leading components from file names on extraction. --transform=EXPRESSION, --xform=EXPRESSION Use sed replace EXPRESSION to transform file names. File name matching options These options affect both exclude and include patterns. --anchored Patterns match file name start. --ignore-case Ignore case. --no-anchored Patterns match after any / (default for exclusion). --no-ignore-case Case sensitive matching (default). --no-wildcards Verbatim string matching. --no-wildcards-match-slash Wildcards do not match /. --wildcards Use wildcards (default for exclusion). --wildcards-match-slash Wildcards match / (default for exclusion). Informative output --checkpoint[=N] Display progress messages every Nth record (default 10). --checkpoint-action=ACTION Run ACTION on each checkpoint. --clamp-mtime Only set time when the file is more recent than what was given with --mtime. --full-time Print file time to its full resolution. --index-file=FILE Send verbose output to FILE. -l, --check-links Print a message if not all links are dumped. --no-quote-chars=STRING Disable quoting for characters from STRING. --quote-chars=STRING Additionally quote characters from STRING. --quoting-style=STYLE Set quoting style for file and member names. Valid values for STYLE are literal, shell, shell-always, c, c-maybe, escape, locale, clocale. -R, --block-number Show block number within archive with each message. --show-omitted-dirs When listing or extracting, list each directory that does not match search criteria. --show-transformed-names, --show-stored-names Show file or archive names after transformation by --strip and --transform options. --totals[=SIGNAL] Print total bytes after processing the archive. If SIGNAL is given, print total bytes when this signal is delivered. Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1, and SIGUSR2. The SIG prefix can be omitted. --utc Print file modification times in UTC. -v, --verbose Verbosely list files processed. Each instance of this option on the command line increases the verbosity level by one. The maximum verbosity level is 3. For a detailed discussion of how various verbosity levels affect tar's output, please refer to GNU Tar Manual, subsection 2.5.2 "The '--verbose' Option". --warning=KEYWORD Enable or disable warning messages identified by KEYWORD. The messages are suppressed if KEYWORD is prefixed with no- and enabled otherwise. Multiple --warning options accumulate. Keywords controlling general tar operation: all Enable all warning messages. This is the default. none Disable all warning messages. filename-with-nuls "%s: file name read contains nul character" alone-zero-block "A lone zero block at %s" Keywords applicable for tar --create: cachedir "%s: contains a cache directory tag %s; %s" file-shrank "%s: File shrank by %s bytes; padding with zeros" xdev "%s: file is on a different filesystem; not dumped" file-ignored "%s: Unknown file type; file ignored" "%s: socket ignored" "%s: door ignored" file-unchanged "%s: file is unchanged; not dumped" ignore-archive "%s: archive cannot contain itself; not dumped" file-removed "%s: File removed before we read it" file-changed "%s: file changed as we read it" failed-read Suppresses warnings about unreadable files or directories. This keyword applies only if used together with the --ignore-failed-read option. Keywords applicable for tar --extract: existing-file "%s: skipping existing file" timestamp "%s: implausibly old time stamp %s" "%s: time stamp %s is %s s in the future" contiguous-cast "Extracting contiguous files as regular files" symlink-cast "Attempting extraction of symbolic links as hard links" unknown-cast "%s: Unknown file type '%c', extracted as normal file" ignore-newer "Current %s is newer or same age" unknown-keyword "Ignoring unknown extended header keyword '%s'" decompress-program Controls verbose description of failures occurring when trying to run alternative decompressor programs. This warning is disabled by default (unless --verbose is used). A common example of what you can get when using this warning is: $ tar --warning=decompress-program -x -f archive.Z tar (child): cannot run compress: No such file or directory tar (child): trying gzip This means that tar first tried to decompress archive.Z using compress, and, when that failed, switched to gzip. record-size "Record size = %lu blocks" Keywords controlling incremental extraction: rename-directory "%s: Directory has been renamed from %s" "%s: Directory has been renamed" new-directory "%s: Directory is new" xdev "%s: directory is on a different device: not purging" bad-dumpdir "Malformed dumpdir: 'X' never used" -w, --interactive, --confirmation Ask for confirmation for every action. Compatibility options -o When creating, same as --old-archive. When extracting, same as --no-same-owner. Size suffixes Suffix Units Byte Equivalent b Blocks SIZE x 512 B Kilobytes SIZE x 1024 c Bytes SIZE G Gigabytes SIZE x 1024^3 K Kilobytes SIZE x 1024 k Kilobytes SIZE x 1024 M Megabytes SIZE x 1024^2 P Petabytes SIZE x 1024^5 T Terabytes SIZE x 1024^4 w Words SIZE x 2 RETURN VALUE top Tar's exit code indicates whether it was able to successfully perform the requested operation, and if not, what kind of error occurred. 0 Successful termination. 1 Some files differ. If tar was invoked with the --compare (--diff, -d) command line option, this means that some files in the archive differ from their disk counterparts. If tar was given one of the --create, --append or --update options, this exit code means that some files were changed while being archived and so the resulting archive does not contain the exact copy of the file set. 2 Fatal error. This means that some fatal, unrecoverable error occurred. If a subprocess that had been invoked by tar exited with a nonzero exit code, tar itself exits with that code as well. This can happen, for example, if a compression option (e.g. -z) was used and the external compressor program failed. Another example is rmt failure during backup to a remote device. SEE ALSO top bzip2(1), compress(1), gzip(1), lzma(1), lzop(1), rmt(8), symlink(7), xz(1), zstd(1). Complete tar manual: run info tar or use emacs(1) info mode to read it. Online copies of GNU tar documentation in various formats can be found at: https://www.gnu.org/software/tar/manual BUG REPORTS top Report bugs to <bug-tar@gnu.org>. COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://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. COLOPHON top This page is part of the tar (an archiver program) project. Information about the project can be found at http://savannah.gnu.org/projects/tar/. If you have a bug report for this manual page, see http://savannah.gnu.org/bugs/?group=tar. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/tar.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-12.) 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 TAR July 11, 2022 TAR(1) Pages that refer to this page: attr(1), dpkg-deb(1), dpkg-source(1), machinectl(1), rsync(1), st(4), suffixes(7), symlink(7), cupsd-helper(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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split result of the command "tar [your params]" into pieces per 500 mb named as "output_prefixNNN" Bash Command:<START>tar [your params] |split -b 500m - output_prefix<END>
split the file "/path/to/large/file" into pieces per 50000 lines named as /path/to/output/file/prefixNNN
split --lines=50000 /path/to/large/file /path/to/output/file/prefix
['split']
Output a Bash command to accomplish the following task. Task: split the file "/path/to/large/file" into pieces per 50000 lines named as /path/to/output/file/prefixNNN Bash Command:<START>split --lines=50000 /path/to/large/file /path/to/output/file/prefix<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split the file "/path/to/large/file" into pieces per 50000 lines named as /path/to/output/file/prefixNNN Bash Command:<START>split --lines=50000 /path/to/large/file /path/to/output/file/prefix<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split the file "/path/to/large/file" into pieces per 50000 lines named as /path/to/output/file/prefixNNN Bash Command:<START>split --lines=50000 /path/to/large/file /path/to/output/file/prefix<END>
split the file "file" into pieces per 2 lines
split -n2 infile
['split']
Output a Bash command to accomplish the following task. Task: split the file "file" into pieces per 2 lines Bash Command:<START>split -n2 infile<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split the file "file" into pieces per 2 lines Bash Command:<START>split -n2 infile<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split the file "file" into pieces per 2 lines Bash Command:<START>split -n2 infile<END>
split the file data.csv into pieces per 100 mb named as data.tsv.NNN with digital prefixes
split -C 100m -d data.tsv data.tsv.
['split']
Output a Bash command to accomplish the following task. Task: split the file data.csv into pieces per 100 mb named as data.tsv.NNN with digital prefixes Bash Command:<START>split -C 100m -d data.tsv data.tsv.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split the file data.csv into pieces per 100 mb named as data.tsv.NNN with digital prefixes Bash Command:<START>split -C 100m -d data.tsv data.tsv.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split the file data.csv into pieces per 100 mb named as data.tsv.NNN with digital prefixes Bash Command:<START>split -C 100m -d data.tsv data.tsv.<END>
split the file hugefile.txt into pieces per 100000 lines named as partNNN with digital prefixes
split -a4 -d -l100000 hugefile.txt part.
['split']
Output a Bash command to accomplish the following task. Task: split the file hugefile.txt into pieces per 100000 lines named as partNNN with digital prefixes Bash Command:<START>split -a4 -d -l100000 hugefile.txt part.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n Task: split the file hugefile.txt into pieces per 100000 lines named as partNNN with digital prefixes Bash Command:<START>split -a4 -d -l100000 hugefile.txt part.<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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: split the file hugefile.txt into pieces per 100000 lines named as partNNN with digital prefixes Bash Command:<START>split -a4 -d -l100000 hugefile.txt part.<END>
split the first 100 lines of the file "datafile" per lines with size 1700 bytes
sed 100q datafile | split -C 1700 -
['split', 'sed']
Output a Bash command to accomplish the following task. Task: split the first 100 lines of the file "datafile" per lines with size 1700 bytes Bash Command:<START>sed 100q datafile | split -C 1700 -<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\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: split the first 100 lines of the file "datafile" per lines with size 1700 bytes Bash Command:<START>sed 100q datafile | split -C 1700 -<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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. 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: split the first 100 lines of the file "datafile" per lines with size 1700 bytes Bash Command:<START>sed 100q datafile | split -C 1700 -<END>
split the result of command "ping -c 25 google.com | tee " into pieces per 100000 bytes named as "/home/user/myLogFile.logNNN"
ping -c 25 google.com | tee >(split -d -b 100000 - /home/user/myLogFile.log)
['tee', 'split', 'ping']
Output a Bash command to accomplish the following task. Task: split the result of command "ping -c 25 google.com | tee " into pieces per 100000 bytes named as "/home/user/myLogFile.logNNN" Bash Command:<START>ping -c 25 google.com | tee >(split -d -b 100000 - /home/user/myLogFile.log)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # tee\n\n> Read from `stdin` and write to `stdout` and files (or commands).\n> More information: <https://www.gnu.org/software/coreutils/tee>.\n\n- Copy `stdin` to each file, and also to `stdout`:\n\n`echo "example" | tee {{path/to/file}}`\n\n- Append to the given files, do not overwrite:\n\n`echo "example" | tee -a {{path/to/file}}`\n\n- Print `stdin` to the terminal, and also pipe it into another program for further processing:\n\n`echo "example" | tee {{/dev/tty}} | {{xargs printf "[%s]"}}`\n\n- Create a directory called "example", count the number of characters in "example" and write "example" to the terminal:\n\n`echo "example" | tee >(xargs mkdir) >(wc -c)`\n # split\n\n> Split a file into pieces.\n> More information: <https://www.gnu.org/software/coreutils/split>.\n\n- Split a file, each split having 10 lines (except the last split):\n\n`split -l {{10}} {{path/to/file}}`\n\n- Split a file into 5 files. File is split such that each split has same size (except the last split):\n\n`split -n {{5}} {{path/to/file}}`\n\n- Split a file with 512 bytes in each split (except the last split; use 512k for kilobytes and 512m for megabytes):\n\n`split -b {{512}} {{path/to/file}}`\n\n- Split a file with at most 512 bytes in each split without breaking lines:\n\n`split -C {{512}} {{path/to/file}}`\n # ping\n\n> Send ICMP ECHO_REQUEST packets to network hosts.\n> More information: <https://manned.org/ping>.\n\n- Ping host:\n\n`ping {{host}}`\n\n- Ping a host only a specific number of times:\n\n`ping -c {{count}} {{host}}`\n\n- Ping host, specifying the interval in seconds between requests (default is 1 second):\n\n`ping -i {{seconds}} {{host}}`\n\n- Ping host without trying to lookup symbolic names for addresses:\n\n`ping -n {{host}}`\n\n- Ping host and ring the bell when a packet is received (if your terminal supports it):\n\n`ping -a {{host}}`\n\n- Also display a message if no response was received:\n\n`ping -O {{host}}`\n Task: split the result of command "ping -c 25 google.com | tee " into pieces per 100000 bytes named as "/home/user/myLogFile.logNNN" Bash Command:<START>ping -c 25 google.com | tee >(split -d -b 100000 - /home/user/myLogFile.log)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: tee(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tee(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TEE(1) User Commands TEE(1) NAME top tee - read from standard input and write to standard output and files SYNOPSIS top tee [OPTION]... [FILE]... DESCRIPTION top Copy standard input to each FILE, and also to standard output. -a, --append append to the given FILEs, do not overwrite -i, --ignore-interrupts ignore interrupt signals -p operate in a more appropriate MODE with pipes. --output-error[=MODE] set behavior on write error. See MODE below --help display this help and exit --version output version information and exit MODE determines behavior with write errors on the outputs: warn diagnose errors writing to any output warn-nopipe diagnose errors writing to any output not a pipe exit exit on error writing to any output exit-nopipe exit on error writing to any output not a pipe The default MODE for the -p option is 'warn-nopipe'. With "nopipe" MODEs, exit immediately if all outputs become broken pipes. The default operation when --output-error is not specified, is to exit immediately on error writing to a pipe, and diagnose errors writing to non pipe outputs. AUTHOR top Written by Mike Parker, 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 Full documentation <https://www.gnu.org/software/coreutils/tee> or available locally via: info '(coreutils) tee 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 TEE(1) Pages that refer to this page: tee(2) 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. split(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training split(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SPLIT(1) User Commands SPLIT(1) NAME top split - split a file into pieces SYNOPSIS top split [OPTION]... [FILE [PREFIX]] DESCRIPTION top Output pieces of FILE to PREFIXaa, PREFIXab, ...; default size is 1000 lines, and default PREFIX is 'x'. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -a, --suffix-length=N generate suffixes of length N (default 2) --additional-suffix=SUFFIX append an additional SUFFIX to file names -b, --bytes=SIZE put SIZE bytes per output file -C, --line-bytes=SIZE put at most SIZE bytes of records per output file -d use numeric suffixes starting at 0, not alphabetic --numeric-suffixes[=FROM] same as -d, but allow setting the start value -x use hex suffixes starting at 0, not alphabetic --hex-suffixes[=FROM] same as -x, but allow setting the start value -e, --elide-empty-files do not generate empty output files with '-n' --filter=COMMAND write to shell COMMAND; file name is $FILE -l, --lines=NUMBER put NUMBER lines/records per output file -n, --number=CHUNKS generate CHUNKS output files; see explanation below -t, --separator=SEP use SEP instead of newline as the record separator; '\0' (zero) specifies the NUL character -u, --unbuffered immediately copy input to output with '-n r/...' --verbose print a diagnostic just before each output file is opened --help display this help and exit --version output version information and exit The SIZE argument is an integer and optional unit (example: 10K is 10*1024). Units are K,M,G,T,P,E,Z,Y,R,Q (powers of 1024) or KB,MB,... (powers of 1000). Binary prefixes can be used, too: KiB=K, MiB=M, and so on. CHUNKS may be: N split into N files based on size of input K/N output Kth of N to stdout l/N split into N files without splitting lines/records l/K/N output Kth of N to stdout without splitting lines/records r/N like 'l' but use round robin distribution r/K/N likewise but only output Kth of N to stdout 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 Full documentation <https://www.gnu.org/software/coreutils/split> or available locally via: info '(coreutils) split 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 SPLIT(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. ping(8) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ping(8) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | IPV6 LINK-LOCAL DESTINATIONS | ICMP PACKET DETAILS | DUPLICATE AND DAMAGED PACKETS | ID COLLISIONS | TRYING DIFFERENT DATA PATTERNS | TTL DETAILS | BUGS | SEE ALSO | HISTORY | SECURITY | AVAILABILITY | COLOPHON PING(8) iputils PING(8) NAME top ping - send ICMP ECHO_REQUEST to network hosts SYNOPSIS top ping [-aAbBdCDfhHLnOqrRUvV46] [-c count] [-e identifier] [-F flowlabel] [-i interval] [-I interface] [-l preload] [-m mark] [-M pmtudisc_option] [-N nodeinfo_option] [-w deadline] [-W timeout] [-p pattern] [-Q tos] [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp option] [hop...] {destination} DESCRIPTION top ping uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit an ICMP ECHO_RESPONSE from a host or gateway. ECHO_REQUEST datagrams (pings) have an IP and ICMP header, followed by a struct timeval and then an arbitrary number of pad bytes used to fill out the packet. ping works with both IPv4 and IPv6. Using only one of them explicitly can be enforced by specifying -4 or -6. ping can also send IPv6 Node Information Queries (RFC4620). Intermediate hops may not be allowed, because IPv6 source routing was deprecated (RFC5095). OPTIONS top -4 Use IPv4 only. -6 Use IPv6 only. -a Audible ping. -A Adaptive ping. Interpacket interval adapts to round-trip time, so that effectively not more than one (or more, if preload is set) unanswered probe is present in the network. Minimal interval is 200msec unless super-user. On networks with low RTT this mode is essentially equivalent to flood mode. -b Allow pinging a broadcast address. -B Do not allow ping to change source address of probes. The address is bound to one selected when ping starts. -c count Stop after sending count ECHO_REQUEST packets. With deadline option, ping waits for count ECHO_REPLY packets, until the timeout expires. -C Call connect() syscall on socket creation. -d Set the SO_DEBUG option on the socket being used. Essentially, this socket option is not used by Linux kernel. -D Print timestamp (unix time + microseconds as in gettimeofday) before each line. -e identifier Set the identification field of ECHO_REQUEST. Value 0 implies using raw socket (not supported on ICMP datagram socket). The value of the field may be printed with -v option. -f Flood ping. For every ECHO_REQUEST sent a period . is printed, while for every ECHO_REPLY received a backspace is printed. This provides a rapid display of how many packets are being dropped. If interval is not given, it sets interval to zero and outputs packets as fast as they come back or one hundred times per second, whichever is more. Only the super-user may use this option with zero interval. -F flow label IPv6 only. Allocate and set 20 bit flow label (in hex) on echo request packets. If value is zero, kernel allocates random flow label. -h Show help. -H Force DNS name resolution for the output. Useful for numeric destination, or -f option, which by default do not perform it. Override previously defined -n option. -i interval Wait interval seconds between sending each packet. Real number allowed with dot as a decimal separator (regardless locale setup). The default is to wait for one second between each packet normally, or not to wait in flood mode. Only super-user may set interval to values less than 2 ms. Broadcast and multicast ping have even higher limitation for regular user: minimum is 1 sec. -I interface interface is either an address, an interface name or a VRF name. If interface is an address, it sets source address to specified interface address. If interface is an interface name, it sets source interface to specified interface. If interface is a VRF name, each packet is routed using the corresponding routing table; in this case, the -I option can be repeated to specify a source address. NOTE: For IPv6, when doing ping to a link-local scope address, link specification (by the '%'-notation in destination, or by this option) can be used but it is no longer required. -l preload If preload is specified, ping sends that many packets not waiting for reply. Only the super-user may select preload more than 3. -L Suppress loopback of multicast packets. This flag only applies if the ping destination is a multicast address. -m mark use mark to tag the packets going out. This is useful for variety of reasons within the kernel such as using policy routing to select specific outbound processing. -M pmtudisc_opt Select Path MTU Discovery strategy. pmtudisc_option may be either do (set DF flag but subject to PMTU checks by kernel, packets too large will be rejected), want (do PMTU discovery, fragment locally when packet size is large), probe (set DF flag and bypass PMTU checks, useful for probing), or dont (do not set DF flag). -N nodeinfo_option IPv6 only. Send IPv6 Node Information Queries (RFC4620), instead of Echo Request. CAP_NET_RAW capability is required. help Show help for NI support. name Queries for Node Names. ipv6 Queries for IPv6 Addresses. There are several IPv6 specific flags. ipv6-global Request IPv6 global-scope addresses. ipv6-sitelocal Request IPv6 site-local addresses. ipv6-linklocal Request IPv6 link-local addresses. ipv6-all Request IPv6 addresses on other interfaces. ipv4 Queries for IPv4 Addresses. There is one IPv4 specific flag. ipv4-all Request IPv4 addresses on other interfaces. subject-ipv6=ipv6addr IPv6 subject address. subject-ipv4=ipv4addr IPv4 subject address. subject-name=nodename Subject name. If it contains more than one dot, fully-qualified domain name is assumed. subject-fqdn=nodename Subject name. Fully-qualified domain name is always assumed. -n Numeric output only. No attempt will be made to lookup symbolic names for host addresses (no reverse DNS resolution). This is the default for numeric destination or -f option. Override previously defined -H option. -O Report outstanding ICMP ECHO reply before sending next packet. This is useful together with the timestamp -D to log output to a diagnostic file and search for missing answers. -p pattern You may specify up to 16 pad bytes to fill out the packet you send. This is useful for diagnosing data-dependent problems in a network. For example, -p ff will cause the sent packet to be filled with all ones. -q Quiet output. Nothing is displayed except the summary lines at startup time and when finished. -Q tos Set Quality of Service -related bits in ICMP datagrams. tos can be decimal (ping only) or hex number. In RFC2474, these fields are interpreted as 8-bit Differentiated Services (DS), consisting of: bits 0-1 (2 lowest bits) of separate data, and bits 2-7 (highest 6 bits) of Differentiated Services Codepoint (DSCP). In RFC2481 and RFC3168, bits 0-1 are used for ECN. Historically (RFC1349, obsoleted by RFC2474), these were interpreted as: bit 0 (lowest bit) for reserved (currently being redefined as congestion control), 1-4 for Type of Service and bits 5-7 (highest bits) for Precedence. -r Bypass the normal routing tables and send directly to a host on an attached interface. If the host is not on a directly-attached network, an error is returned. This option can be used to ping a local host through an interface that has no route through it provided the option -I is also used. -R ping only. Record route. Includes the RECORD_ROUTE option in the ECHO_REQUEST packet and displays the route buffer on returned packets. Note that the IP header is only large enough for nine such routes. Many hosts ignore or discard this option. -s packetsize Specifies the number of data bytes to be sent. The default is 56, which translates into 64 ICMP data bytes when combined with the 8 bytes of ICMP header data. -S sndbuf Set socket sndbuf. If not specified, it is selected to buffer not more than one packet. -t ttl ping only. Set the IP Time to Live. -T timestamp option Set special IP timestamp options. timestamp option may be either tsonly (only timestamps), tsandaddr (timestamps and addresses) or tsprespec host1 [host2 [host3 [host4]]] (timestamp prespecified hops). -U Print full user-to-user latency (the old behaviour). Normally ping prints network round trip time, which can be different f.e. due to DNS failures. -v Verbose output. Do not suppress DUP replies when pinging multicast address. -V Show version and exit. -w deadline Specify a timeout, in seconds, before ping exits regardless of how many packets have been sent or received. In this case ping does not stop after count packet are sent, it waits either for deadline expire or until count probes are answered or for some error notification from network. -W timeout Time to wait for a response, in seconds. The option affects only timeout in absence of any responses, otherwise ping waits for two RTTs. Real number allowed with dot as a decimal separator (regardless locale setup). 0 means infinite timeout. When using ping for fault isolation, it should first be run on the local host, to verify that the local network interface is up and running. Then, hosts and gateways further and further away should be pinged. Round-trip times and packet loss statistics are computed. If duplicate packets are received, they are not included in the packet loss calculation, although the round trip time of these packets is used in calculating the minimum/average/maximum/mdev round-trip time numbers. Population standard deviation (mdev), essentially an average of how far each ping RTT is from the mean RTT. The higher mdev is, the more variable the RTT is (over time). With a high RTT variability, you will have speed issues with bulk transfers (they will take longer than is strictly speaking necessary, as the variability will eventually cause the sender to wait for ACKs) and you will have middling to poor VoIP quality. When the specified number of packets have been sent (and received) or if the program is terminated with a SIGINT, a brief summary is displayed. Shorter current statistics can be obtained without termination of process with signal SIGQUIT. If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not. This program is intended for use in network testing, measurement and management. Because of the load it can impose on the network, it is unwise to use ping during normal operations or from automated scripts. IPV6 LINK-LOCAL DESTINATIONS top For IPv6, when the destination address has link-local scope and ping is using ICMP datagram sockets, the output interface must be specified. When ping is using raw sockets, it is not strictly necessary to specify the output interface but it should be done to avoid ambiguity when there are multiple possible output interfaces. There are two ways to specify the output interface: using the % notation The destination address is postfixed with % and the output interface name or ifindex, for example: ping fe80::5054:ff:fe70:67bc%eth0 ping fe80::5054:ff:fe70:67bc%2 using the -I option When using ICMP datagram sockets, this method is supported since the following kernel versions: 5.17, 5.15.19, 5.10.96, 5.4.176, 4.19.228, 4.14.265. Also it is not supported on musl libc. ICMP PACKET DETAILS top An IP header without options is 20 bytes. An ICMP ECHO_REQUEST packet contains an additional 8 bytes worth of ICMP header followed by an arbitrary amount of data. When a packetsize is given, this indicates the size of this extra piece of data (the default is 56). Thus the amount of data received inside of an IP packet of type ICMP ECHO_REPLY will always be 8 bytes more than the requested data space (the ICMP header). If the data space is at least of size of struct timeval ping uses the beginning bytes of this space to include a timestamp which it uses in the computation of round trip times. If the data space is shorter, no round trip times are given. DUPLICATE AND DAMAGED PACKETS top ping will report duplicate and damaged packets. Duplicate packets should never occur, and seem to be caused by inappropriate link-level retransmissions. Duplicates may occur in many situations and are rarely (if ever) a good sign, although the presence of low levels of duplicates may not always be cause for alarm. Damaged packets are obviously serious cause for alarm and often indicate broken hardware somewhere in the ping packet's path (in the network or in the hosts). ID COLLISIONS top Unlike TCP and UDP, which use port to uniquely identify the recipient to deliver data, ICMP uses identifier field (ID) for identification. Therefore, if on the same machine, at the same time, two ping processes use the same ID, echo reply can be delivered to a wrong recipient. This is a known problem due to the limited size of the 16-bit ID field. That is a historical limitation of the protocol that cannot be fixed at the moment unless we encode an ID into the ping packet payload. ping prints DIFFERENT ADDRESS error and packet loss is negative. ping uses PID to get unique number. The default value of /proc/sys/kernel/pid_max is 32768. On the systems that use ping heavily and with pid_max greater than 65535 collisions are bound to happen. TRYING DIFFERENT DATA PATTERNS top The (inter)network layer should never treat packets differently depending on the data contained in the data portion. Unfortunately, data-dependent problems have been known to sneak into networks and remain undetected for long periods of time. In many cases the particular pattern that will have problems is something that doesn't have sufficient transitions, such as all ones or all zeros, or a pattern right at the edge, such as almost all zeros. It isn't necessarily enough to specify a data pattern of all zeros (for example) on the command line because the pattern that is of interest is at the data link level, and the relationship between what you type and what the controllers transmit can be complicated. This means that if you have a data-dependent problem you will probably have to do a lot of testing to find it. If you are lucky, you may manage to find a file that either can't be sent across your network or that takes much longer to transfer than other similar length files. You can then examine this file for repeated patterns that you can test using the -p option of ping. TTL DETAILS top The TTL value of an IP packet represents the maximum number of IP routers that the packet can go through before being thrown away. In current practice you can expect each router in the Internet to decrement the TTL field by exactly one. The TTL field for TCP packets may take various values. The maximum possible value of this field is 255, a recommended initial value is 64. For more information, see the TCP/Lower-Level Interface section of RFC9293. In normal operation ping prints the TTL value from the packet it receives. When a remote system receives a ping packet, it can do one of three things with the TTL field in its response: Not change it; this is what Berkeley Unix systems did before the 4.3BSD Tahoe release. In this case the TTL value in the received packet will be 255 minus the number of routers in the round-trip path. Set it to 255; this is what current Berkeley Unix systems do. In this case the TTL value in the received packet will be 255 minus the number of routers in the path from the remote system to the pinging host. Set it to some other value. Some machines use the same value for ICMP packets that they use for TCP packets, for example either 30 or 60. Others may use completely wild values. BUGS top Many Hosts and Gateways ignore the RECORD_ROUTE option. The maximum IP header length is too small for options like RECORD_ROUTE to be completely useful. There's not much that can be done about this, however. Flood pinging is not recommended in general, and flood pinging the broadcast address should only be done under very controlled conditions. SEE ALSO top ip(8), ss(8). HISTORY top The ping command appeared in 4.3BSD. The version described here is its descendant specific to Linux. As of version s20150815, the ping6 binary doesn't exist anymore. It has been merged into ping. Creating a symlink named ping6 pointing to ping will result in the same functionality as before. SECURITY top ping requires CAP_NET_RAW capability to be executed 1) if the program is used for non-echo queries (see -N option) or when the identification field set to 0 for ECHO_REQUEST (see -e), or 2) if kernel does not support ICMP datagram sockets, or 3) if the user is not allowed to create an ICMP echo socket. The program may be used as set-uid root. AVAILABILITY top ping is part of iputils package. COLOPHON top This page is part of the iputils (IP utilities) project. Information about the project can be found at http://www.skbuff.net/iputils/. If you have a bug report for this manual page, send it to yoshfuji@skbuff.net, netdev@vger.kernel.org. This page was obtained from the project's upstream Git repository https://github.com/iputils/iputils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 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 iputils 20221126 PING(8) Pages that refer to this page: arping(8), clockdiff(8), tracepath(8), traceroute(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: split the result of command "ping -c 25 google.com | tee " into pieces per 100000 bytes named as "/home/user/myLogFile.logNNN" Bash Command:<START>ping -c 25 google.com | tee >(split -d -b 100000 - /home/user/myLogFile.log)<END>
ssh into "hostname" as user "buck"
ssh -l buck hostname
['ssh', 'hostname']
Output a Bash command to accomplish the following task. Task: ssh into "hostname" as user "buck" Bash Command:<START>ssh -l buck hostname<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # ssh\n\n> Secure Shell is a protocol used to securely log onto remote systems.\n> It can be used for logging or executing commands on a remote server.\n> More information: <https://man.openbsd.org/ssh>.\n\n- Connect to a remote server:\n\n`ssh {{username}}@{{remote_host}}`\n\n- Connect to a remote server with a specific identity (private key):\n\n`ssh -i {{path/to/key_file}} {{username}}@{{remote_host}}`\n\n- Connect to a remote server using a specific [p]ort:\n\n`ssh {{username}}@{{remote_host}} -p {{2222}}`\n\n- Run a command on a remote server with a [t]ty allocation allowing interaction with the remote command:\n\n`ssh {{username}}@{{remote_host}} -t {{command}} {{command_arguments}}`\n\n- SSH tunneling: [D]ynamic port forwarding (SOCKS proxy on `localhost:1080`):\n\n`ssh -D {{1080}} {{username}}@{{remote_host}}`\n\n- SSH tunneling: Forward a specific port (`localhost:9999` to `example.org:80`) along with disabling pseudo-[T]ty allocation and executio[N] of remote commands:\n\n`ssh -L {{9999}}:{{example.org}}:{{80}} -N -T {{username}}@{{remote_host}}`\n\n- SSH [J]umping: Connect through a jumphost to a remote server (Multiple jump hops may be specified separated by comma characters):\n\n`ssh -J {{username}}@{{jump_host}} {{username}}@{{remote_host}}`\n\n- Agent forwarding: Forward the authentication information to the remote machine (see `man ssh_config` for available options):\n\n`ssh -A {{username}}@{{remote_host}}`\n # hostname\n\n> Show or set the system's host name.\n> More information: <https://manned.org/hostname>.\n\n- Show current host name:\n\n`hostname`\n\n- Show the network address of the host name:\n\n`hostname -i`\n\n- Show all network addresses of the host:\n\n`hostname -I`\n\n- Show the FQDN (Fully Qualified Domain Name):\n\n`hostname --fqdn`\n\n- Set current host name:\n\n`hostname {{new_hostname}}`\n Task: ssh into "hostname" as user "buck" Bash Command:<START>ssh -l buck hostname<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: ssh(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ssh(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHENTICATION | ESCAPE CHARACTERS | TCP FORWARDING | X11 FORWARDING | VERIFYING HOST KEYS | SSH-BASED VIRTUAL PRIVATE NETWORKS | ENVIRONMENT | FILES | EXIT STATUS | SEE ALSO | STANDARDS | AUTHORS | COLOPHON SSH(1) General Commands Manual SSH(1) NAME top ssh OpenSSH remote login client SYNOPSIS top ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-J destination] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] destination [command [argument ...]] [-Q query_option] DESCRIPTION top (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections, arbitrary TCP ports and Unix-domain sockets can also be forwarded over the secure channel. connects and logs into the specified destination, which may be specified as either [user@]hostname or a URI of the form ssh://[user@]hostname[:port]. The user must prove their identity to the remote machine using one of several methods (see below). If a command is specified, it will be executed on the remote host instead of a login shell. A complete command line may be specified as command, or it may have additional arguments. If supplied, the arguments will be appended to the command, separated by spaces, before it is sent to the server to be executed. The options are as follows: -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Enables forwarding of connections from an authentication agent such as ssh-agent(1). This can also be specified on a per-host basis in a configuration file. Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent. A safer alternative may be to use a jump host (see -J). -a Disables forwarding of the authentication agent connection. -B bind_interface Bind to the address of bind_interface before attempting to connect to the destination host. This is only useful on systems with more than one address. -b bind_address Use bind_address on the local machine as the source address of the connection. Only useful on systems with more than one address. -C Requests compression of all data (including stdin, stdout, stderr, and data for forwarded X11, TCP and Unix-domain connections). The compression algorithm is the same used by gzip(1). Compression is desirable on modem lines and other slow connections, but will only slow down things on fast networks. The default value can be set on a host-by-host basis in the configuration files; see the Compression option in ssh_config(5). -c cipher_spec Selects the cipher specification for encrypting the session. cipher_spec is a comma-separated list of ciphers listed in order of preference. See the Ciphers keyword in ssh_config(5) for more information. -D [bind_address:]port Specifies a local dynamic application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. Currently the SOCKS4 and SOCKS5 protocols are supported, and will act as a SOCKS server. Only root can forward privileged ports. Dynamic port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -E log_file Append debug logs to log_file instead of standard error. -e escape_char Sets the escape character for sessions with a pty (default: ~). The escape character is only recognized at the beginning of a line. The escape character followed by a dot (.) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to none disables any escapes and makes the session fully transparent. -F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config. If set to none, no configuration files will be read. -f Requests to go to background just before command execution. This is useful if is going to ask for passwords or passphrases, but the user wants it in the background. This implies -n. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm. If the ExitOnForwardFailure configuration option is set to yes, then a client started with -f will wait for all remote port forwards to be successfully established before placing itself in the background. Refer to the description of ForkAfterAuthentication in ssh_config(5) for details. -G Causes to print its configuration after evaluating Host and Match blocks and exit. -g Allows remote hosts to connect to local forwarded ports. If used on a multiplexed connection, then this option must be specified on the master process. -I pkcs11 Specify the PKCS#11 shared library should use to communicate with a PKCS#11 token providing keys for user authentication. -i identity_file Selects a file from which the identity (private key) for public key authentication is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519, ~/.ssh/id_ed25519_sk and ~/.ssh/id_dsa. Identity files may also be specified on a per-host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in configuration files). If no certificates have been explicitly specified by the CertificateFile directive, will also try to load certificate information from the filename obtained by appending -cert.pub to identity filenames. -J destination Connect to the target host by first making an connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there. Multiple jump hops may be specified separated by comma characters. This is a shortcut to specify a ProxyJump configuration directive. Note that configuration directives supplied on the command-line generally apply to the destination host and not any specified jump hosts. Use ~/.ssh/config to specify configuration for jump hosts. -K Enables GSSAPI-based authentication and forwarding (delegation) of GSSAPI credentials to the server. -k Disables forwarding (delegation) of GSSAPI credentials to the server. -L [bind_address:]port:host:hostport -L [bind_address:]port:remote_socket -L local_socket:host:hostport -L local_socket:remote_socket Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. This works by allocating a socket to listen to either a TCP port on the local side, optionally bound to the specified bind_address, or to a Unix socket. Whenever a connection is made to the local port or socket, the connection is forwarded over the secure channel, and a connection is made to either host port hostport, or the Unix socket remote_socket, from the remote machine. Port forwardings can also be specified in the configuration file. Only the superuser can forward privileged ports. IPv6 addresses can be specified by enclosing the address in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -l login_name Specifies the user to log in as on the remote machine. This also may be specified on a per-host basis in the configuration file. -M Places the client into master mode for connection sharing. Multiple -M options places into master mode but with confirmation required using ssh-askpass(1) before each operation that changes the multiplexing state (e.g. opening a new session). Refer to the description of ControlMaster in ssh_config(5) for details. -m mac_spec A comma-separated list of MAC (message authentication code) algorithms, specified in order of preference. See the MACs keyword in ssh_config(5) for more information. -N Do not execute a remote command. This is useful for just forwarding ports. Refer to the description of SessionType in ssh_config(5) for details. -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The program will be put in the background. (This does not work if needs to ask for a password or passphrase; see also the -f option.) Refer to the description of StdinNull in ssh_config(5) for details. -O ctl_cmd Control an active connection multiplexing master process. When the -O option is specified, the ctl_cmd argument is interpreted and passed to the master process. Valid commands are: check (check that the master process is running), forward (request forwardings without command execution), cancel (cancel forwardings), exit (request the master to exit), and stop (request the master to stop accepting further multiplexing requests). -o option Can be used to give options in the format used in the configuration file. This is useful for specifying options for which there is no separate command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddKeysToAgent AddressFamily BatchMode BindAddress CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers ClearAllForwardings Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist DynamicForward EnableEscapeCommandline EscapeChar ExitOnForwardFailure FingerprintHash ForkAfterAuthentication ForwardAgent ForwardX11 ForwardX11Timeout ForwardX11Trusted GatewayPorts GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LocalCommand LocalForward LogLevel MACs Match NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PermitLocalCommand PermitRemoteOpen PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump ProxyUseFdpass PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RemoteCommand RemoteForward RequestTTY RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SessionType SetEnv StdinNull StreamLocalBindMask StreamLocalBindUnlink StrictHostKeyChecking TCPKeepAlive Tunnel TunnelDevice UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS VisualHostKey XAuthLocation -P tag Specify a tag name that may be used to select configuration in ssh_config(5). Refer to the Tag and Match keywords in ssh_config(5) for more information. -p port Port to connect to on the remote host. This can be specified on a per-host basis in the configuration file. -Q query_option Queries for the algorithms supported by one of the following features: cipher (supported symmetric ciphers), cipher-auth (supported symmetric ciphers that support authenticated encryption), help (supported query terms for use with the -Q flag), mac (supported message integrity codes), kex (key exchange algorithms), key (key types), key-ca-sign (valid CA signature algorithms for certificates), key-cert (certificate key types), key-plain (non-certificate key types), key-sig (all key types and signature algorithms), protocol-version (supported SSH protocol versions), and sig (supported signature algorithms). Alternatively, any keyword from ssh_config(5) or sshd_config(5) that takes an algorithm list may be used as an alias for the corresponding query_option. -q Quiet mode. Causes most warning and diagnostic messages to be suppressed. -R [bind_address:]port:host:hostport -R [bind_address:]port:local_socket -R remote_socket:host:hostport -R remote_socket:local_socket -R [bind_address:]port Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side. This works by allocating a socket to listen to either a TCP port or to a Unix socket on the remote side. Whenever a connection is made to this port or Unix socket, the connection is forwarded over the secure channel, and a connection is made from the local machine to either an explicit destination specified by host port hostport, or local_socket, or, if no explicit destination was specified, will act as a SOCKS 4/5 proxy and forward connections to the destinations requested by the remote SOCKS client. Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square brackets. By default, TCP listening sockets on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address *, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)). If the port argument is 0, the listen port will be dynamically allocated on the server and reported to the client at run time. When used together with -O forward, the allocated port will be printed to the standard output. -S ctl_path Specifies the location of a control socket for connection sharing, or the string none to disable connection sharing. Refer to the description of ControlPath and ControlMaster in ssh_config(5) for details. -s May be used to request invocation of a subsystem on the remote system. Subsystems facilitate the use of SSH as a secure transport for other applications (e.g. sftp(1)). The subsystem is specified as the remote command. Refer to the description of SessionType in ssh_config(5) for details. -T Disable pseudo-terminal allocation. -t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if has no local tty. -V Display the version number and exit. -v Verbose mode. Causes to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3. -W host:port Requests that standard input and output on the client be forwarded to host on port over the secure channel. Implies -N, -T, ExitOnForwardFailure and ClearAllForwardings, though these can be overridden in the configuration file or using -o command line options. -w local_tun[:remote_tun] Requests tunnel device forwarding with the specified tun(4) devices between the client (local_tun) and the server (remote_tun). The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. See also the Tunnel and TunnelDevice directives in ssh_config(5). If the Tunnel directive is unset, it will be set to the default tunnel mode, which is point-to-point. If a different Tunnel forwarding mode it desired, then it should be specified before -w. -X Enables X11 forwarding. This can also be specified on a per-host basis in a configuration file. X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring. For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. Refer to the -Y option and the ForwardX11Trusted directive in ssh_config(5) for more information. -x Disables X11 forwarding. -Y Enables trusted X11 forwarding. Trusted X11 forwardings are not subjected to the X11 SECURITY extension controls. -y Send log information using the syslog(3) system module. By default this information is sent to stderr. may additionally obtain configuration data from a per-user configuration file and a system-wide configuration file. The file format and configuration options are described in ssh_config(5). AUTHENTICATION top The OpenSSH SSH client supports SSH protocol 2. The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, keyboard-interactive authentication, and password authentication. Authentication methods are tried in the order specified above, though PreferredAuthentications can be used to change the default order. Host-based authentication works as follows: If the machine the user logs in from is listed in /etc/hosts.equiv or /etc/shosts.equiv on the remote machine, the user is non-root and the user names are the same on both sides, or if the files ~/.rhosts or ~/.shosts exist in the user's home directory on the remote machine and contain a line containing the name of the client machine and the name of the user on that machine, the user is considered for login. Additionally, the server must be able to verify the client's host key (see the description of /etc/ssh/ssh_known_hosts and ~/.ssh/known_hosts, below) for login to be permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing, and routing spoofing. [Note to the administrator: /etc/hosts.equiv, ~/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.] Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. implements public key authentication protocol automatically, using one of the DSA, ECDSA, Ed25519 or RSA algorithms. The HISTORY section of ssl(8) contains a brief discussion of the DSA and RSA algorithms. The file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. When the user logs in, the program tells the server which key pair it would like to use for authentication. The client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account. The server may inform the client of errors that prevented public key authentication from succeeding after authentication completes using a different method. These may be viewed by increasing the LogLevel to DEBUG or higher (e.g. by using the -v flag). The user creates their key pair by running ssh-keygen(1). This stores the private key in ~/.ssh/id_dsa (DSA), ~/.ssh/id_ecdsa (ECDSA), ~/.ssh/id_ecdsa_sk (authenticator-hosted ECDSA), ~/.ssh/id_ed25519 (Ed25519), ~/.ssh/id_ed25519_sk (authenticator- hosted Ed25519), or ~/.ssh/id_rsa (RSA) and stores the public key in ~/.ssh/id_dsa.pub (DSA), ~/.ssh/id_ecdsa.pub (ECDSA), ~/.ssh/id_ecdsa_sk.pub (authenticator-hosted ECDSA), ~/.ssh/id_ed25519.pub (Ed25519), ~/.ssh/id_ed25519_sk.pub (authenticator-hosted Ed25519), or ~/.ssh/id_rsa.pub (RSA) in the user's home directory. The user should then copy the public key to ~/.ssh/authorized_keys in their home directory on the remote machine. The authorized_keys file corresponds to the conventional ~/.rhosts file, and has one key per line, though the lines can be very long. After this, the user can log in without giving the password. A variation on public key authentication is available in the form of certificate authentication: instead of a set of public/private keys, signed certificates are used. This has the advantage that a single trusted certification authority can be used in place of many public/private keys. See the CERTIFICATES section of ssh-keygen(1) for more information. The most convenient way to use public key or certificate authentication may be with an authentication agent. See ssh-agent(1) and (optionally) the AddKeysToAgent directive in ssh_config(5) for more information. Keyboard-interactive authentication works as follows: The server sends an arbitrary "challenge" text and prompts for a response, possibly multiple times. Examples of keyboard-interactive authentication include BSD Authentication (see login.conf(5)) and PAM (some non-OpenBSD systems). Finally, if other authentication methods fail, prompts the user for a password. The password is sent to the remote host for checking; however, since all communications are encrypted, the password cannot be seen by someone listening on the network. automatically maintains and checks a database containing identification for all hosts it has ever been used with. Host keys are stored in ~/.ssh/known_hosts in the user's home directory. Additionally, the file /etc/ssh/ssh_known_hosts is automatically checked for known hosts. Any new hosts are automatically added to the user's file. If a host's identification ever changes, warns about this and disables password authentication to prevent server spoofing or man-in-the- middle attacks, which could otherwise be used to circumvent the encryption. The StrictHostKeyChecking option can be used to control logins to machines whose host key is not known or has changed. When the user's identity has been accepted by the server, the server either executes the given command in a non-interactive session or, if no command has been specified, logs into the machine and gives the user a normal shell as an interactive session. All communication with the remote command or shell will be automatically encrypted. If an interactive session is requested, by default will only request a pseudo-terminal (pty) for interactive sessions when the client has one. The flags -T and -t can be used to override this behaviour. If a pseudo-terminal has been allocated, the user may use the escape characters noted below. If no pseudo-terminal has been allocated, the session is transparent and can be used to reliably transfer binary data. On most systems, setting the escape character to none will also make the session transparent even if a tty is used. The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed. ESCAPE CHARACTERS top When a pseudo-terminal has been requested, supports a number of functions through the use of an escape character. A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option. The supported escapes (assuming the default ~) are: ~. Disconnect. ~^Z Background . ~# List forwarded connections. ~& Background at logout when waiting for forwarded connection / X11 sessions to terminate. ~? Display a list of escape characters. ~B Send a BREAK to the remote system (only useful if the peer supports it). ~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing port-forwardings with -KL[bind_address:]port for local, -KR[bind_address:]port for remote and -KD[bind_address:]port for dynamic port-forwardings. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is available, using the -h option. ~R Request rekeying of the connection (only useful if the peer supports it). ~V Decrease the verbosity (LogLevel) when errors are being written to stderr. ~v Increase the verbosity (LogLevel) when errors are being written to stderr. TCP FORWARDING top Forwarding of arbitrary TCP connections over a secure channel can be specified either on the command line or in a configuration file. One possible application of TCP forwarding is a secure connection to a mail server; another is going through firewalls. In the example below, we look at encrypting communication for an IRC client, even though the IRC server it connects to does not directly support encrypted communication. This works as follows: the user connects to the remote host using , specifying the ports to be used to forward the connection. After that it is possible to start the program locally, and will encrypt and forward the connection to the remote server. The following example tunnels an IRC session from the client to an IRC server at server.example.com, joining channel #users, nickname pinky, using the standard IRC port, 6667: $ ssh -f -L 6667:localhost:6667 server.example.com sleep 10 $ irc -c '#users' pinky IRC/127.0.0.1 The -f option backgrounds and the remote command sleep 10 is specified to allow an amount of time (10 seconds, in the example) to start the program which is going to use the tunnel. If no connections are made within the time specified, will exit. X11 FORWARDING top If the ForwardX11 variable is set to yes (or see the description of the -X, -x, and -Y options above) and the user is using X11 (the DISPLAY environment variable is set), the connection to the X11 display is automatically forwarded to the remote side in such a way that any X11 programs started from the shell (or command) will go through the encrypted channel, and the connection to the real X server will be made from the local machine. The user should not manually set DISPLAY. Forwarding of X11 connections can be configured on the command line or in configuration files. The DISPLAY value set by will point to the server machine, but with a display number greater than zero. This is normal, and happens because creates a proxy X server on the server machine for forwarding the connections over the encrypted channel. will also automatically set up Xauthority data on the server machine. For this purpose, it will generate a random authorization cookie, store it in Xauthority on the server, and verify that any forwarded connections carry this cookie and replace it by the real cookie when the connection is opened. The real authentication cookie is never sent to the server machine (and no cookies are sent in the plain). If the ForwardAgent variable is set to yes (or see the description of the -A and -a options above) and the user is using an authentication agent, the connection to the agent is automatically forwarded to the remote side. VERIFYING HOST KEYS top When connecting to a server for the first time, a fingerprint of the server's public key is presented to the user (unless the option StrictHostKeyChecking has been disabled). Fingerprints can be determined using ssh-keygen(1): $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key If the fingerprint is already known, it can be matched and the key can be accepted or rejected. If only legacy (MD5) fingerprints for the server are available, the ssh-keygen(1) -E option may be used to downgrade the fingerprint algorithm to match. Because of the difficulty of comparing host keys just by looking at fingerprint strings, there is also support to compare host keys visually, using random art. By setting the VisualHostKey option to yes, a small ASCII graphic gets displayed on every login to a server, no matter if the session itself is interactive or not. By learning the pattern a known server produces, a user can easily find out that the host key has changed when a completely different pattern is displayed. Because these patterns are not unambiguous however, a pattern that looks similar to the pattern remembered only gives a good probability that the host key is the same, not guaranteed proof. To get a listing of the fingerprints along with their random art for all known hosts, the following command line can be used: $ ssh-keygen -lv -f ~/.ssh/known_hosts If the fingerprint is unknown, an alternative method of verification is available: SSH fingerprints verified by DNS. An additional resource record (RR), SSHFP, is added to a zonefile and the connecting client is able to match the fingerprint with that of the key presented. In this example, we are connecting a client to a server, host.example.com. The SSHFP resource records should first be added to the zonefile for host.example.com: $ ssh-keygen -r host.example.com. The output lines will have to be added to the zonefile. To check that the zone is answering fingerprint queries: $ dig -t SSHFP host.example.com Finally the client connects: $ ssh -o "VerifyHostKeyDNS ask" host.example.com [...] Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? See the VerifyHostKeyDNS option in ssh_config(5) for more information. SSH-BASED VIRTUAL PRIVATE NETWORKS top contains support for Virtual Private Network (VPN) tunnelling using the tun(4) network pseudo-device, allowing two networks to be joined securely. The sshd_config(5) configuration option PermitTunnel controls whether the server supports this, and at what level (layer 2 or 3 traffic). The following example would connect client network 10.0.50.0/24 with remote network 10.0.99.0/24 using a point-to-point connection from 10.1.1.1 to 10.1.1.2, provided that the SSH server running on the gateway to the remote network, at 192.168.1.15, allows it. On the client: # ssh -f -w 0:1 192.168.1.15 true # ifconfig tun0 10.1.1.1 10.1.1.2 netmask 255.255.255.252 # route add 10.0.99.0/24 10.1.1.2 On the server: # ifconfig tun1 10.1.1.2 10.1.1.1 netmask 255.255.255.252 # route add 10.0.50.0/24 10.1.1.1 Client access may be more finely tuned via the /root/.ssh/authorized_keys file (see below) and the PermitRootLogin server option. The following entry would permit connections on tun(4) device 1 from user jane and on tun device 2 from user john, if PermitRootLogin is set to forced-commands-only: tunnel="1",command="sh /etc/netstart tun1" ssh-rsa ... jane tunnel="2",command="sh /etc/netstart tun2" ssh-rsa ... john Since an SSH-based setup entails a fair amount of overhead, it may be more suited to temporary setups, such as for wireless VPNs. More permanent VPNs are better provided by tools such as ipsecctl(8) and isakmpd(8). ENVIRONMENT top will normally set the following environment variables: DISPLAY The DISPLAY variable indicates the location of the X11 server. It is automatically set by to point to a value of the form hostname:n, where hostname indicates the host where the shell runs, and n is an integer 1. uses this special value to forward X11 connections over the secure channel. The user should normally not set DISPLAY explicitly, as that will render the X11 connection insecure (and will require the user to manually copy any required authorization cookies). HOME Set to the path of the user's home directory. LOGNAME Synonym for USER; set for compatibility with systems that use this variable. MAIL Set to the path of the user's mailbox. PATH Set to the default PATH, as specified when compiling . SSH_ASKPASS If needs a passphrase, it will read the passphrase from the current terminal if it was run from a terminal. If does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS and open an X11 window to read the passphrase. This is particularly useful when calling from a .xsession or related script. (Note that on some machines it may be necessary to redirect the input from /dev/null to make this work.) SSH_ASKPASS_REQUIRE Allows further control over the use of an askpass program. If this variable is set to never then will never attempt to use one. If it is set to prefer, then will prefer to use the askpass program instead of the TTY when requesting passwords. Finally, if the variable is set to force, then the askpass program will be used for all passphrase input regardless of whether DISPLAY is set. SSH_AUTH_SOCK Identifies the path of a Unix-domain socket used to communicate with the agent. SSH_CONNECTION Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number. SSH_ORIGINAL_COMMAND This variable contains the original command line if a forced command is executed. It can be used to extract the original arguments. SSH_TTY This is set to the name of the tty (path to the device) associated with the current shell or command. If the current session has no tty, this variable is not set. SSH_TUNNEL Optionally set by sshd(8) to contain the interface names assigned if tunnel forwarding was requested by the client. SSH_USER_AUTH Optionally set by sshd(8), this variable may contain a pathname to a file that lists the authentication methods successfully used when the session was established, including any public keys that were used. TZ This variable is set to indicate the present time zone if it was set when the daemon was started (i.e. the daemon passes the value on to new connections). USER Set to the name of the user logging in. Additionally, reads ~/.ssh/environment, and adds lines of the format VARNAME=value to the environment if the file exists and users are allowed to change their environment. For more information, see the PermitUserEnvironment option in sshd_config(5). FILES top ~/.rhosts This file is used for host-based authentication (see above). On some machines this file may need to be world- readable if the user's home directory is on an NFS partition, because sshd(8) reads it as root. Additionally, this file must be owned by the user, and must not have write permissions for anyone else. The recommended permission for most machines is read/write for the user, and not accessible by others. ~/.shosts This file is used in exactly the same way as .rhosts, but allows host-based authentication without permitting login with rlogin/rsh. ~/.ssh/ This directory is the default location for all user- specific configuration and authentication information. There is no general requirement to keep the entire contents of this directory secret, but the recommended permissions are read/write/execute for the user, and not accessible by others. ~/.ssh/authorized_keys Lists the public keys (DSA, ECDSA, Ed25519, RSA) that can be used for logging in as this user. The format of this file is described in the sshd(8) manual page. This file is not highly sensitive, but the recommended permissions are read/write for the user, and not accessible by others. ~/.ssh/config This is the per-user configuration file. The file format and configuration options are described in ssh_config(5). Because of the potential for abuse, this file must have strict permissions: read/write for the user, and not writable by others. ~/.ssh/environment Contains additional definitions for environment variables; see ENVIRONMENT, above. ~/.ssh/id_dsa ~/.ssh/id_ecdsa ~/.ssh/id_ecdsa_sk ~/.ssh/id_ed25519 ~/.ssh/id_ed25519_sk ~/.ssh/id_rsa Contains the private key for authentication. These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute). will simply ignore a private key file if it is accessible by others. It is possible to specify a passphrase when generating the key which will be used to encrypt the sensitive part of this file using AES-128. ~/.ssh/id_dsa.pub ~/.ssh/id_ecdsa.pub ~/.ssh/id_ecdsa_sk.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_ed25519_sk.pub ~/.ssh/id_rsa.pub Contains the public key for authentication. These files are not sensitive and can (but need not) be readable by anyone. ~/.ssh/known_hosts Contains a list of host keys for all hosts the user has logged into that are not already in the systemwide list of known host keys. See sshd(8) for further details of the format of this file. ~/.ssh/rc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. /etc/hosts.equiv This file is for host-based authentication (see above). It should only be writable by root. /etc/shosts.equiv This file is used in exactly the same way as hosts.equiv, but allows host-based authentication without permitting login with rlogin/rsh. /etc/ssh/ssh_config Systemwide configuration file. The file format and configuration options are described in ssh_config(5). /etc/ssh/ssh_host_key /etc/ssh/ssh_host_dsa_key /etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_ed25519_key /etc/ssh/ssh_host_rsa_key These files contain the private parts of the host keys and are used for host-based authentication. /etc/ssh/ssh_known_hosts Systemwide list of known host keys. This file should be prepared by the system administrator to contain the public host keys of all machines in the organization. It should be world-readable. See sshd(8) for further details of the format of this file. /etc/ssh/sshrc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. EXIT STATUS top exits with the exit status of the remote command or with 255 if an error occurred. SEE ALSO top scp(1), sftp(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh-keyscan(1), tun(4), ssh_config(5), ssh-keysign(8), sshd(8) STANDARDS top S. Lehtinen and C. Lonvick, The Secure Shell (SSH) Protocol Assigned Numbers, RFC 4250, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Protocol Architecture, RFC 4251, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Authentication Protocol, RFC 4252, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Transport Layer Protocol, RFC 4253, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Connection Protocol, RFC 4254, January 2006. J. Schlyter and W. Griffin, Using DNS to Securely Publish Secure Shell (SSH) Key Fingerprints, RFC 4255, January 2006. F. Cusack and M. Forssen, Generic Message Exchange Authentication for the Secure Shell Protocol (SSH), RFC 4256, January 2006. J. Galbraith and P. Remaker, The Secure Shell (SSH) Session Channel Break Extension, RFC 4335, January 2006. M. Bellare, T. Kohno, and C. Namprempre, The Secure Shell (SSH) Transport Layer Encryption Modes, RFC 4344, January 2006. B. Harris, Improved Arcfour Modes for the Secure Shell (SSH) Transport Layer Protocol, RFC 4345, January 2006. M. Friedl, N. Provos, and W. Simpson, Diffie-Hellman Group Exchange for the Secure Shell (SSH) Transport Layer Protocol, RFC 4419, March 2006. J. Galbraith and R. Thayer, The Secure Shell (SSH) Public Key File Format, RFC 4716, November 2006. D. Stebila and J. Green, Elliptic Curve Algorithm Integration in the Secure Shell Transport Layer, RFC 5656, December 2009. A. Perrig and D. Song, Hash Visualization: a New Technique to improve Real-World Security, 1999, International Workshop on Cryptographic Techniques and E-Commerce (CrypTEC '99). AUTHORS top OpenSSH is a derivative of the original and free ssh 1.2.12 release by Tatu Ylonen. Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo de Raadt and Dug Song removed many bugs, re- added newer features and created OpenSSH. Markus Friedl contributed the support for SSH protocol versions 1.5 and 2.0. COLOPHON top This page is part of the openssh (Portable OpenSSH) project. Information about the project can be found at http://www.openssh.com/portable.html. If you have a bug report for this manual page, see http://www.openssh.com/report.html. This page was obtained from the tarball openssh-9.6p1.tar.gz fetched from http://ftp.eu.openbsd.org/pub/OpenBSD/OpenSSH/portable/ 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 October 11, 2023 SSH(1) Pages that refer to this page: stap-jupyter(1), systemd-stdio-bridge(1), tar(1), sd_bus_default(3), environment.d(5), proc(5), user@.service(5), pty(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. hostname(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training Another version of this page is provided by the coreutils project hostname(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | FILES | AUTHOR | COLOPHON HOSTNAME(1) Linux System Administrator's Manual HOSTNAME(1) NAME top hostname - show or set the system's host name dnsdomainname - show the system's DNS domain name domainname - show or set the system's NIS/YP domain name nisdomainname - show or set system's NIS/YP domain name nodename - show or set the system's DECnet node name ypdomainname - show or set the system's NIS/YP domain name SYNOPSIS top hostname [-v] [-s|--short] hostname [-v] [-a|--alias] [-d|--domain] [-f|--fqdn|--long] [-i|--ip-address] hostname [-v] [-y|--yp|--nis] [-n|--node] hostname [-v] [-F filename|--file filename] [newname] domainname [-v] [-F filename|--file filename] [newname] nodename [-v] [-F filename|--file filename] [newname] hostname [-v|--verbose] [-h|--help] [-V|--version] dnsdomainname [-v] nisdomainname [-v] ypdomainname [-v] DESCRIPTION top Hostname is the program that is used to either set or display the current host, domain or node name of the system. These names are used by many of the networking programs to identify the machine. The domain name is also used by NIS/YP. GET NAME When called without any arguments, the program displays the current names: hostname will print the name of the system as returned by the gethostname(2) function. domainname, nisdomainname, ypdomainname will print the name of the system as returned by the getdomainname(2) function. This is also known as the YP/NIS domain name of the system. nodename will print the DECnet node name of the system as returned by the getnodename(2) function. dnsdomainname will print the domain part of the FQDN (Fully Qualified Domain Name). The complete FQDN of the system is returned with hostname --fqdn. SET NAME When called with one argument or with the --file option, the commands set the host name, the NIS/YP domain name or the node name. Note, that only the super-user can change the names. It is not possible to set the FQDN or the DNS domain name with the dnsdomainname command (see THE FQDN below). The host name is usually set once at system startup by reading the contents of a file which contains the host name, e.g. /etc/hostname). THE FQDN You can't change the FQDN (as returned by hostname --fqdn) or the DNS domain name (as returned by dnsdomainname) with this command. The FQDN of the system is the name that the resolver(3) returns for the host name. Technically: The FQDN is the canonical name returned by gethostbyname2(2) when resolving the result of the gethostname(2) name. The DNS domain name is the part after the first dot. Therefore it depends on the configuration (usually in /etc/host.conf) how you can change it. If hosts is the first lookup method, you can change the FQDN in /etc/hosts. OPTIONS top -a, --alias Display the alias name of the host (if used). -d, --domain Display the name of the DNS domain (this is the FQDN without the segment up to the first dot). This is equivalent to using the dnsdomainname command. -F, --file filename Read the new host name from the specified file. Comments (lines starting with a `#') are ignored. -f, --fqdn, --long Display the FQDN (Fully Qualified Domain Name). A FQDN consists of name including the DNS domain. -h, --help Print a usage message and exit. -i, --ip-address Display the IP address(es) of the host. -n, --node Display the DECnet node name. If a parameter is given (or --file name ) the root can also set a new node name. -s, --short Display the short host name. This is the host name cut at the first dot. -V, --version Print version information on standard output and exit successfully. -v, --verbose Be verbose and tell what's going on. -y, --yp, --nis Display the NIS domain name. If a parameter is given (or --file name ) then root can also set a new NIS domain. FILES top /etc/hostname /etc/hosts /etc/host.conf AUTHOR top Peter Tobias, <tobias@et-inf.fho-emden.de> Bernd Eckenfels, <net-tools@lina.inka.de> (NIS and manpage). Steve Whitehouse, <SteveW@ACM.org> (DECnet support and manpage). COLOPHON top This page is part of the net-tools (networking utilities) project. Information about the project can be found at http://net-tools.sourceforge.net/. If you have a bug report for this manual page, see http://net-tools.sourceforge.net/. This page was obtained from the project's upstream Git repository git://git.code.sf.net/p/net-tools/code on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-06-29.) 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 net-tools 2013-08-29 HOSTNAME(1) Pages that refer to this page: hostnamectl(1), ippeveprinter(1), gethostname(2), cupsd.conf(5), hostname(5), hosts(5), proc(5) 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: ssh into "hostname" as user "buck" Bash Command:<START>ssh -l buck hostname<END>
ssh into "hostname" as user "buck"
ssh buck@hostname
['ssh']
Output a Bash command to accomplish the following task. Task: ssh into "hostname" as user "buck" Bash Command:<START>ssh buck@hostname<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # ssh\n\n> Secure Shell is a protocol used to securely log onto remote systems.\n> It can be used for logging or executing commands on a remote server.\n> More information: <https://man.openbsd.org/ssh>.\n\n- Connect to a remote server:\n\n`ssh {{username}}@{{remote_host}}`\n\n- Connect to a remote server with a specific identity (private key):\n\n`ssh -i {{path/to/key_file}} {{username}}@{{remote_host}}`\n\n- Connect to a remote server using a specific [p]ort:\n\n`ssh {{username}}@{{remote_host}} -p {{2222}}`\n\n- Run a command on a remote server with a [t]ty allocation allowing interaction with the remote command:\n\n`ssh {{username}}@{{remote_host}} -t {{command}} {{command_arguments}}`\n\n- SSH tunneling: [D]ynamic port forwarding (SOCKS proxy on `localhost:1080`):\n\n`ssh -D {{1080}} {{username}}@{{remote_host}}`\n\n- SSH tunneling: Forward a specific port (`localhost:9999` to `example.org:80`) along with disabling pseudo-[T]ty allocation and executio[N] of remote commands:\n\n`ssh -L {{9999}}:{{example.org}}:{{80}} -N -T {{username}}@{{remote_host}}`\n\n- SSH [J]umping: Connect through a jumphost to a remote server (Multiple jump hops may be specified separated by comma characters):\n\n`ssh -J {{username}}@{{jump_host}} {{username}}@{{remote_host}}`\n\n- Agent forwarding: Forward the authentication information to the remote machine (see `man ssh_config` for available options):\n\n`ssh -A {{username}}@{{remote_host}}`\n Task: ssh into "hostname" as user "buck" Bash Command:<START>ssh buck@hostname<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: ssh(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ssh(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHENTICATION | ESCAPE CHARACTERS | TCP FORWARDING | X11 FORWARDING | VERIFYING HOST KEYS | SSH-BASED VIRTUAL PRIVATE NETWORKS | ENVIRONMENT | FILES | EXIT STATUS | SEE ALSO | STANDARDS | AUTHORS | COLOPHON SSH(1) General Commands Manual SSH(1) NAME top ssh OpenSSH remote login client SYNOPSIS top ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-J destination] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] destination [command [argument ...]] [-Q query_option] DESCRIPTION top (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections, arbitrary TCP ports and Unix-domain sockets can also be forwarded over the secure channel. connects and logs into the specified destination, which may be specified as either [user@]hostname or a URI of the form ssh://[user@]hostname[:port]. The user must prove their identity to the remote machine using one of several methods (see below). If a command is specified, it will be executed on the remote host instead of a login shell. A complete command line may be specified as command, or it may have additional arguments. If supplied, the arguments will be appended to the command, separated by spaces, before it is sent to the server to be executed. The options are as follows: -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Enables forwarding of connections from an authentication agent such as ssh-agent(1). This can also be specified on a per-host basis in a configuration file. Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent. A safer alternative may be to use a jump host (see -J). -a Disables forwarding of the authentication agent connection. -B bind_interface Bind to the address of bind_interface before attempting to connect to the destination host. This is only useful on systems with more than one address. -b bind_address Use bind_address on the local machine as the source address of the connection. Only useful on systems with more than one address. -C Requests compression of all data (including stdin, stdout, stderr, and data for forwarded X11, TCP and Unix-domain connections). The compression algorithm is the same used by gzip(1). Compression is desirable on modem lines and other slow connections, but will only slow down things on fast networks. The default value can be set on a host-by-host basis in the configuration files; see the Compression option in ssh_config(5). -c cipher_spec Selects the cipher specification for encrypting the session. cipher_spec is a comma-separated list of ciphers listed in order of preference. See the Ciphers keyword in ssh_config(5) for more information. -D [bind_address:]port Specifies a local dynamic application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. Currently the SOCKS4 and SOCKS5 protocols are supported, and will act as a SOCKS server. Only root can forward privileged ports. Dynamic port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -E log_file Append debug logs to log_file instead of standard error. -e escape_char Sets the escape character for sessions with a pty (default: ~). The escape character is only recognized at the beginning of a line. The escape character followed by a dot (.) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to none disables any escapes and makes the session fully transparent. -F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config. If set to none, no configuration files will be read. -f Requests to go to background just before command execution. This is useful if is going to ask for passwords or passphrases, but the user wants it in the background. This implies -n. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm. If the ExitOnForwardFailure configuration option is set to yes, then a client started with -f will wait for all remote port forwards to be successfully established before placing itself in the background. Refer to the description of ForkAfterAuthentication in ssh_config(5) for details. -G Causes to print its configuration after evaluating Host and Match blocks and exit. -g Allows remote hosts to connect to local forwarded ports. If used on a multiplexed connection, then this option must be specified on the master process. -I pkcs11 Specify the PKCS#11 shared library should use to communicate with a PKCS#11 token providing keys for user authentication. -i identity_file Selects a file from which the identity (private key) for public key authentication is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519, ~/.ssh/id_ed25519_sk and ~/.ssh/id_dsa. Identity files may also be specified on a per-host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in configuration files). If no certificates have been explicitly specified by the CertificateFile directive, will also try to load certificate information from the filename obtained by appending -cert.pub to identity filenames. -J destination Connect to the target host by first making an connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there. Multiple jump hops may be specified separated by comma characters. This is a shortcut to specify a ProxyJump configuration directive. Note that configuration directives supplied on the command-line generally apply to the destination host and not any specified jump hosts. Use ~/.ssh/config to specify configuration for jump hosts. -K Enables GSSAPI-based authentication and forwarding (delegation) of GSSAPI credentials to the server. -k Disables forwarding (delegation) of GSSAPI credentials to the server. -L [bind_address:]port:host:hostport -L [bind_address:]port:remote_socket -L local_socket:host:hostport -L local_socket:remote_socket Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. This works by allocating a socket to listen to either a TCP port on the local side, optionally bound to the specified bind_address, or to a Unix socket. Whenever a connection is made to the local port or socket, the connection is forwarded over the secure channel, and a connection is made to either host port hostport, or the Unix socket remote_socket, from the remote machine. Port forwardings can also be specified in the configuration file. Only the superuser can forward privileged ports. IPv6 addresses can be specified by enclosing the address in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -l login_name Specifies the user to log in as on the remote machine. This also may be specified on a per-host basis in the configuration file. -M Places the client into master mode for connection sharing. Multiple -M options places into master mode but with confirmation required using ssh-askpass(1) before each operation that changes the multiplexing state (e.g. opening a new session). Refer to the description of ControlMaster in ssh_config(5) for details. -m mac_spec A comma-separated list of MAC (message authentication code) algorithms, specified in order of preference. See the MACs keyword in ssh_config(5) for more information. -N Do not execute a remote command. This is useful for just forwarding ports. Refer to the description of SessionType in ssh_config(5) for details. -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The program will be put in the background. (This does not work if needs to ask for a password or passphrase; see also the -f option.) Refer to the description of StdinNull in ssh_config(5) for details. -O ctl_cmd Control an active connection multiplexing master process. When the -O option is specified, the ctl_cmd argument is interpreted and passed to the master process. Valid commands are: check (check that the master process is running), forward (request forwardings without command execution), cancel (cancel forwardings), exit (request the master to exit), and stop (request the master to stop accepting further multiplexing requests). -o option Can be used to give options in the format used in the configuration file. This is useful for specifying options for which there is no separate command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddKeysToAgent AddressFamily BatchMode BindAddress CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers ClearAllForwardings Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist DynamicForward EnableEscapeCommandline EscapeChar ExitOnForwardFailure FingerprintHash ForkAfterAuthentication ForwardAgent ForwardX11 ForwardX11Timeout ForwardX11Trusted GatewayPorts GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LocalCommand LocalForward LogLevel MACs Match NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PermitLocalCommand PermitRemoteOpen PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump ProxyUseFdpass PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RemoteCommand RemoteForward RequestTTY RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SessionType SetEnv StdinNull StreamLocalBindMask StreamLocalBindUnlink StrictHostKeyChecking TCPKeepAlive Tunnel TunnelDevice UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS VisualHostKey XAuthLocation -P tag Specify a tag name that may be used to select configuration in ssh_config(5). Refer to the Tag and Match keywords in ssh_config(5) for more information. -p port Port to connect to on the remote host. This can be specified on a per-host basis in the configuration file. -Q query_option Queries for the algorithms supported by one of the following features: cipher (supported symmetric ciphers), cipher-auth (supported symmetric ciphers that support authenticated encryption), help (supported query terms for use with the -Q flag), mac (supported message integrity codes), kex (key exchange algorithms), key (key types), key-ca-sign (valid CA signature algorithms for certificates), key-cert (certificate key types), key-plain (non-certificate key types), key-sig (all key types and signature algorithms), protocol-version (supported SSH protocol versions), and sig (supported signature algorithms). Alternatively, any keyword from ssh_config(5) or sshd_config(5) that takes an algorithm list may be used as an alias for the corresponding query_option. -q Quiet mode. Causes most warning and diagnostic messages to be suppressed. -R [bind_address:]port:host:hostport -R [bind_address:]port:local_socket -R remote_socket:host:hostport -R remote_socket:local_socket -R [bind_address:]port Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side. This works by allocating a socket to listen to either a TCP port or to a Unix socket on the remote side. Whenever a connection is made to this port or Unix socket, the connection is forwarded over the secure channel, and a connection is made from the local machine to either an explicit destination specified by host port hostport, or local_socket, or, if no explicit destination was specified, will act as a SOCKS 4/5 proxy and forward connections to the destinations requested by the remote SOCKS client. Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square brackets. By default, TCP listening sockets on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address *, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)). If the port argument is 0, the listen port will be dynamically allocated on the server and reported to the client at run time. When used together with -O forward, the allocated port will be printed to the standard output. -S ctl_path Specifies the location of a control socket for connection sharing, or the string none to disable connection sharing. Refer to the description of ControlPath and ControlMaster in ssh_config(5) for details. -s May be used to request invocation of a subsystem on the remote system. Subsystems facilitate the use of SSH as a secure transport for other applications (e.g. sftp(1)). The subsystem is specified as the remote command. Refer to the description of SessionType in ssh_config(5) for details. -T Disable pseudo-terminal allocation. -t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if has no local tty. -V Display the version number and exit. -v Verbose mode. Causes to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3. -W host:port Requests that standard input and output on the client be forwarded to host on port over the secure channel. Implies -N, -T, ExitOnForwardFailure and ClearAllForwardings, though these can be overridden in the configuration file or using -o command line options. -w local_tun[:remote_tun] Requests tunnel device forwarding with the specified tun(4) devices between the client (local_tun) and the server (remote_tun). The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. See also the Tunnel and TunnelDevice directives in ssh_config(5). If the Tunnel directive is unset, it will be set to the default tunnel mode, which is point-to-point. If a different Tunnel forwarding mode it desired, then it should be specified before -w. -X Enables X11 forwarding. This can also be specified on a per-host basis in a configuration file. X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring. For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. Refer to the -Y option and the ForwardX11Trusted directive in ssh_config(5) for more information. -x Disables X11 forwarding. -Y Enables trusted X11 forwarding. Trusted X11 forwardings are not subjected to the X11 SECURITY extension controls. -y Send log information using the syslog(3) system module. By default this information is sent to stderr. may additionally obtain configuration data from a per-user configuration file and a system-wide configuration file. The file format and configuration options are described in ssh_config(5). AUTHENTICATION top The OpenSSH SSH client supports SSH protocol 2. The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, keyboard-interactive authentication, and password authentication. Authentication methods are tried in the order specified above, though PreferredAuthentications can be used to change the default order. Host-based authentication works as follows: If the machine the user logs in from is listed in /etc/hosts.equiv or /etc/shosts.equiv on the remote machine, the user is non-root and the user names are the same on both sides, or if the files ~/.rhosts or ~/.shosts exist in the user's home directory on the remote machine and contain a line containing the name of the client machine and the name of the user on that machine, the user is considered for login. Additionally, the server must be able to verify the client's host key (see the description of /etc/ssh/ssh_known_hosts and ~/.ssh/known_hosts, below) for login to be permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing, and routing spoofing. [Note to the administrator: /etc/hosts.equiv, ~/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.] Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. implements public key authentication protocol automatically, using one of the DSA, ECDSA, Ed25519 or RSA algorithms. The HISTORY section of ssl(8) contains a brief discussion of the DSA and RSA algorithms. The file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. When the user logs in, the program tells the server which key pair it would like to use for authentication. The client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account. The server may inform the client of errors that prevented public key authentication from succeeding after authentication completes using a different method. These may be viewed by increasing the LogLevel to DEBUG or higher (e.g. by using the -v flag). The user creates their key pair by running ssh-keygen(1). This stores the private key in ~/.ssh/id_dsa (DSA), ~/.ssh/id_ecdsa (ECDSA), ~/.ssh/id_ecdsa_sk (authenticator-hosted ECDSA), ~/.ssh/id_ed25519 (Ed25519), ~/.ssh/id_ed25519_sk (authenticator- hosted Ed25519), or ~/.ssh/id_rsa (RSA) and stores the public key in ~/.ssh/id_dsa.pub (DSA), ~/.ssh/id_ecdsa.pub (ECDSA), ~/.ssh/id_ecdsa_sk.pub (authenticator-hosted ECDSA), ~/.ssh/id_ed25519.pub (Ed25519), ~/.ssh/id_ed25519_sk.pub (authenticator-hosted Ed25519), or ~/.ssh/id_rsa.pub (RSA) in the user's home directory. The user should then copy the public key to ~/.ssh/authorized_keys in their home directory on the remote machine. The authorized_keys file corresponds to the conventional ~/.rhosts file, and has one key per line, though the lines can be very long. After this, the user can log in without giving the password. A variation on public key authentication is available in the form of certificate authentication: instead of a set of public/private keys, signed certificates are used. This has the advantage that a single trusted certification authority can be used in place of many public/private keys. See the CERTIFICATES section of ssh-keygen(1) for more information. The most convenient way to use public key or certificate authentication may be with an authentication agent. See ssh-agent(1) and (optionally) the AddKeysToAgent directive in ssh_config(5) for more information. Keyboard-interactive authentication works as follows: The server sends an arbitrary "challenge" text and prompts for a response, possibly multiple times. Examples of keyboard-interactive authentication include BSD Authentication (see login.conf(5)) and PAM (some non-OpenBSD systems). Finally, if other authentication methods fail, prompts the user for a password. The password is sent to the remote host for checking; however, since all communications are encrypted, the password cannot be seen by someone listening on the network. automatically maintains and checks a database containing identification for all hosts it has ever been used with. Host keys are stored in ~/.ssh/known_hosts in the user's home directory. Additionally, the file /etc/ssh/ssh_known_hosts is automatically checked for known hosts. Any new hosts are automatically added to the user's file. If a host's identification ever changes, warns about this and disables password authentication to prevent server spoofing or man-in-the- middle attacks, which could otherwise be used to circumvent the encryption. The StrictHostKeyChecking option can be used to control logins to machines whose host key is not known or has changed. When the user's identity has been accepted by the server, the server either executes the given command in a non-interactive session or, if no command has been specified, logs into the machine and gives the user a normal shell as an interactive session. All communication with the remote command or shell will be automatically encrypted. If an interactive session is requested, by default will only request a pseudo-terminal (pty) for interactive sessions when the client has one. The flags -T and -t can be used to override this behaviour. If a pseudo-terminal has been allocated, the user may use the escape characters noted below. If no pseudo-terminal has been allocated, the session is transparent and can be used to reliably transfer binary data. On most systems, setting the escape character to none will also make the session transparent even if a tty is used. The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed. ESCAPE CHARACTERS top When a pseudo-terminal has been requested, supports a number of functions through the use of an escape character. A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option. The supported escapes (assuming the default ~) are: ~. Disconnect. ~^Z Background . ~# List forwarded connections. ~& Background at logout when waiting for forwarded connection / X11 sessions to terminate. ~? Display a list of escape characters. ~B Send a BREAK to the remote system (only useful if the peer supports it). ~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing port-forwardings with -KL[bind_address:]port for local, -KR[bind_address:]port for remote and -KD[bind_address:]port for dynamic port-forwardings. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is available, using the -h option. ~R Request rekeying of the connection (only useful if the peer supports it). ~V Decrease the verbosity (LogLevel) when errors are being written to stderr. ~v Increase the verbosity (LogLevel) when errors are being written to stderr. TCP FORWARDING top Forwarding of arbitrary TCP connections over a secure channel can be specified either on the command line or in a configuration file. One possible application of TCP forwarding is a secure connection to a mail server; another is going through firewalls. In the example below, we look at encrypting communication for an IRC client, even though the IRC server it connects to does not directly support encrypted communication. This works as follows: the user connects to the remote host using , specifying the ports to be used to forward the connection. After that it is possible to start the program locally, and will encrypt and forward the connection to the remote server. The following example tunnels an IRC session from the client to an IRC server at server.example.com, joining channel #users, nickname pinky, using the standard IRC port, 6667: $ ssh -f -L 6667:localhost:6667 server.example.com sleep 10 $ irc -c '#users' pinky IRC/127.0.0.1 The -f option backgrounds and the remote command sleep 10 is specified to allow an amount of time (10 seconds, in the example) to start the program which is going to use the tunnel. If no connections are made within the time specified, will exit. X11 FORWARDING top If the ForwardX11 variable is set to yes (or see the description of the -X, -x, and -Y options above) and the user is using X11 (the DISPLAY environment variable is set), the connection to the X11 display is automatically forwarded to the remote side in such a way that any X11 programs started from the shell (or command) will go through the encrypted channel, and the connection to the real X server will be made from the local machine. The user should not manually set DISPLAY. Forwarding of X11 connections can be configured on the command line or in configuration files. The DISPLAY value set by will point to the server machine, but with a display number greater than zero. This is normal, and happens because creates a proxy X server on the server machine for forwarding the connections over the encrypted channel. will also automatically set up Xauthority data on the server machine. For this purpose, it will generate a random authorization cookie, store it in Xauthority on the server, and verify that any forwarded connections carry this cookie and replace it by the real cookie when the connection is opened. The real authentication cookie is never sent to the server machine (and no cookies are sent in the plain). If the ForwardAgent variable is set to yes (or see the description of the -A and -a options above) and the user is using an authentication agent, the connection to the agent is automatically forwarded to the remote side. VERIFYING HOST KEYS top When connecting to a server for the first time, a fingerprint of the server's public key is presented to the user (unless the option StrictHostKeyChecking has been disabled). Fingerprints can be determined using ssh-keygen(1): $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key If the fingerprint is already known, it can be matched and the key can be accepted or rejected. If only legacy (MD5) fingerprints for the server are available, the ssh-keygen(1) -E option may be used to downgrade the fingerprint algorithm to match. Because of the difficulty of comparing host keys just by looking at fingerprint strings, there is also support to compare host keys visually, using random art. By setting the VisualHostKey option to yes, a small ASCII graphic gets displayed on every login to a server, no matter if the session itself is interactive or not. By learning the pattern a known server produces, a user can easily find out that the host key has changed when a completely different pattern is displayed. Because these patterns are not unambiguous however, a pattern that looks similar to the pattern remembered only gives a good probability that the host key is the same, not guaranteed proof. To get a listing of the fingerprints along with their random art for all known hosts, the following command line can be used: $ ssh-keygen -lv -f ~/.ssh/known_hosts If the fingerprint is unknown, an alternative method of verification is available: SSH fingerprints verified by DNS. An additional resource record (RR), SSHFP, is added to a zonefile and the connecting client is able to match the fingerprint with that of the key presented. In this example, we are connecting a client to a server, host.example.com. The SSHFP resource records should first be added to the zonefile for host.example.com: $ ssh-keygen -r host.example.com. The output lines will have to be added to the zonefile. To check that the zone is answering fingerprint queries: $ dig -t SSHFP host.example.com Finally the client connects: $ ssh -o "VerifyHostKeyDNS ask" host.example.com [...] Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? See the VerifyHostKeyDNS option in ssh_config(5) for more information. SSH-BASED VIRTUAL PRIVATE NETWORKS top contains support for Virtual Private Network (VPN) tunnelling using the tun(4) network pseudo-device, allowing two networks to be joined securely. The sshd_config(5) configuration option PermitTunnel controls whether the server supports this, and at what level (layer 2 or 3 traffic). The following example would connect client network 10.0.50.0/24 with remote network 10.0.99.0/24 using a point-to-point connection from 10.1.1.1 to 10.1.1.2, provided that the SSH server running on the gateway to the remote network, at 192.168.1.15, allows it. On the client: # ssh -f -w 0:1 192.168.1.15 true # ifconfig tun0 10.1.1.1 10.1.1.2 netmask 255.255.255.252 # route add 10.0.99.0/24 10.1.1.2 On the server: # ifconfig tun1 10.1.1.2 10.1.1.1 netmask 255.255.255.252 # route add 10.0.50.0/24 10.1.1.1 Client access may be more finely tuned via the /root/.ssh/authorized_keys file (see below) and the PermitRootLogin server option. The following entry would permit connections on tun(4) device 1 from user jane and on tun device 2 from user john, if PermitRootLogin is set to forced-commands-only: tunnel="1",command="sh /etc/netstart tun1" ssh-rsa ... jane tunnel="2",command="sh /etc/netstart tun2" ssh-rsa ... john Since an SSH-based setup entails a fair amount of overhead, it may be more suited to temporary setups, such as for wireless VPNs. More permanent VPNs are better provided by tools such as ipsecctl(8) and isakmpd(8). ENVIRONMENT top will normally set the following environment variables: DISPLAY The DISPLAY variable indicates the location of the X11 server. It is automatically set by to point to a value of the form hostname:n, where hostname indicates the host where the shell runs, and n is an integer 1. uses this special value to forward X11 connections over the secure channel. The user should normally not set DISPLAY explicitly, as that will render the X11 connection insecure (and will require the user to manually copy any required authorization cookies). HOME Set to the path of the user's home directory. LOGNAME Synonym for USER; set for compatibility with systems that use this variable. MAIL Set to the path of the user's mailbox. PATH Set to the default PATH, as specified when compiling . SSH_ASKPASS If needs a passphrase, it will read the passphrase from the current terminal if it was run from a terminal. If does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS and open an X11 window to read the passphrase. This is particularly useful when calling from a .xsession or related script. (Note that on some machines it may be necessary to redirect the input from /dev/null to make this work.) SSH_ASKPASS_REQUIRE Allows further control over the use of an askpass program. If this variable is set to never then will never attempt to use one. If it is set to prefer, then will prefer to use the askpass program instead of the TTY when requesting passwords. Finally, if the variable is set to force, then the askpass program will be used for all passphrase input regardless of whether DISPLAY is set. SSH_AUTH_SOCK Identifies the path of a Unix-domain socket used to communicate with the agent. SSH_CONNECTION Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number. SSH_ORIGINAL_COMMAND This variable contains the original command line if a forced command is executed. It can be used to extract the original arguments. SSH_TTY This is set to the name of the tty (path to the device) associated with the current shell or command. If the current session has no tty, this variable is not set. SSH_TUNNEL Optionally set by sshd(8) to contain the interface names assigned if tunnel forwarding was requested by the client. SSH_USER_AUTH Optionally set by sshd(8), this variable may contain a pathname to a file that lists the authentication methods successfully used when the session was established, including any public keys that were used. TZ This variable is set to indicate the present time zone if it was set when the daemon was started (i.e. the daemon passes the value on to new connections). USER Set to the name of the user logging in. Additionally, reads ~/.ssh/environment, and adds lines of the format VARNAME=value to the environment if the file exists and users are allowed to change their environment. For more information, see the PermitUserEnvironment option in sshd_config(5). FILES top ~/.rhosts This file is used for host-based authentication (see above). On some machines this file may need to be world- readable if the user's home directory is on an NFS partition, because sshd(8) reads it as root. Additionally, this file must be owned by the user, and must not have write permissions for anyone else. The recommended permission for most machines is read/write for the user, and not accessible by others. ~/.shosts This file is used in exactly the same way as .rhosts, but allows host-based authentication without permitting login with rlogin/rsh. ~/.ssh/ This directory is the default location for all user- specific configuration and authentication information. There is no general requirement to keep the entire contents of this directory secret, but the recommended permissions are read/write/execute for the user, and not accessible by others. ~/.ssh/authorized_keys Lists the public keys (DSA, ECDSA, Ed25519, RSA) that can be used for logging in as this user. The format of this file is described in the sshd(8) manual page. This file is not highly sensitive, but the recommended permissions are read/write for the user, and not accessible by others. ~/.ssh/config This is the per-user configuration file. The file format and configuration options are described in ssh_config(5). Because of the potential for abuse, this file must have strict permissions: read/write for the user, and not writable by others. ~/.ssh/environment Contains additional definitions for environment variables; see ENVIRONMENT, above. ~/.ssh/id_dsa ~/.ssh/id_ecdsa ~/.ssh/id_ecdsa_sk ~/.ssh/id_ed25519 ~/.ssh/id_ed25519_sk ~/.ssh/id_rsa Contains the private key for authentication. These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute). will simply ignore a private key file if it is accessible by others. It is possible to specify a passphrase when generating the key which will be used to encrypt the sensitive part of this file using AES-128. ~/.ssh/id_dsa.pub ~/.ssh/id_ecdsa.pub ~/.ssh/id_ecdsa_sk.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_ed25519_sk.pub ~/.ssh/id_rsa.pub Contains the public key for authentication. These files are not sensitive and can (but need not) be readable by anyone. ~/.ssh/known_hosts Contains a list of host keys for all hosts the user has logged into that are not already in the systemwide list of known host keys. See sshd(8) for further details of the format of this file. ~/.ssh/rc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. /etc/hosts.equiv This file is for host-based authentication (see above). It should only be writable by root. /etc/shosts.equiv This file is used in exactly the same way as hosts.equiv, but allows host-based authentication without permitting login with rlogin/rsh. /etc/ssh/ssh_config Systemwide configuration file. The file format and configuration options are described in ssh_config(5). /etc/ssh/ssh_host_key /etc/ssh/ssh_host_dsa_key /etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_ed25519_key /etc/ssh/ssh_host_rsa_key These files contain the private parts of the host keys and are used for host-based authentication. /etc/ssh/ssh_known_hosts Systemwide list of known host keys. This file should be prepared by the system administrator to contain the public host keys of all machines in the organization. It should be world-readable. See sshd(8) for further details of the format of this file. /etc/ssh/sshrc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. EXIT STATUS top exits with the exit status of the remote command or with 255 if an error occurred. SEE ALSO top scp(1), sftp(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh-keyscan(1), tun(4), ssh_config(5), ssh-keysign(8), sshd(8) STANDARDS top S. Lehtinen and C. Lonvick, The Secure Shell (SSH) Protocol Assigned Numbers, RFC 4250, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Protocol Architecture, RFC 4251, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Authentication Protocol, RFC 4252, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Transport Layer Protocol, RFC 4253, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Connection Protocol, RFC 4254, January 2006. J. Schlyter and W. Griffin, Using DNS to Securely Publish Secure Shell (SSH) Key Fingerprints, RFC 4255, January 2006. F. Cusack and M. Forssen, Generic Message Exchange Authentication for the Secure Shell Protocol (SSH), RFC 4256, January 2006. J. Galbraith and P. Remaker, The Secure Shell (SSH) Session Channel Break Extension, RFC 4335, January 2006. M. Bellare, T. Kohno, and C. Namprempre, The Secure Shell (SSH) Transport Layer Encryption Modes, RFC 4344, January 2006. B. Harris, Improved Arcfour Modes for the Secure Shell (SSH) Transport Layer Protocol, RFC 4345, January 2006. M. Friedl, N. Provos, and W. Simpson, Diffie-Hellman Group Exchange for the Secure Shell (SSH) Transport Layer Protocol, RFC 4419, March 2006. J. Galbraith and R. Thayer, The Secure Shell (SSH) Public Key File Format, RFC 4716, November 2006. D. Stebila and J. Green, Elliptic Curve Algorithm Integration in the Secure Shell Transport Layer, RFC 5656, December 2009. A. Perrig and D. Song, Hash Visualization: a New Technique to improve Real-World Security, 1999, International Workshop on Cryptographic Techniques and E-Commerce (CrypTEC '99). AUTHORS top OpenSSH is a derivative of the original and free ssh 1.2.12 release by Tatu Ylonen. Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo de Raadt and Dug Song removed many bugs, re- added newer features and created OpenSSH. Markus Friedl contributed the support for SSH protocol versions 1.5 and 2.0. COLOPHON top This page is part of the openssh (Portable OpenSSH) project. Information about the project can be found at http://www.openssh.com/portable.html. If you have a bug report for this manual page, see http://www.openssh.com/report.html. This page was obtained from the tarball openssh-9.6p1.tar.gz fetched from http://ftp.eu.openbsd.org/pub/OpenBSD/OpenSSH/portable/ 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 October 11, 2023 SSH(1) Pages that refer to this page: stap-jupyter(1), systemd-stdio-bridge(1), tar(1), sd_bus_default(3), environment.d(5), proc(5), user@.service(5), pty(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: ssh into "hostname" as user "buck" Bash Command:<START>ssh buck@hostname<END>
ssh into "ssh.myhost.net" as user "myusername" and run command "mkdir -p $2"
ssh myusername@ssh.myhost.net "mkdir -p $2"
['ssh']
Output a Bash command to accomplish the following task. Task: ssh into "ssh.myhost.net" as user "myusername" and run command "mkdir -p $2" Bash Command:<START>ssh myusername@ssh.myhost.net "mkdir -p $2"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # ssh\n\n> Secure Shell is a protocol used to securely log onto remote systems.\n> It can be used for logging or executing commands on a remote server.\n> More information: <https://man.openbsd.org/ssh>.\n\n- Connect to a remote server:\n\n`ssh {{username}}@{{remote_host}}`\n\n- Connect to a remote server with a specific identity (private key):\n\n`ssh -i {{path/to/key_file}} {{username}}@{{remote_host}}`\n\n- Connect to a remote server using a specific [p]ort:\n\n`ssh {{username}}@{{remote_host}} -p {{2222}}`\n\n- Run a command on a remote server with a [t]ty allocation allowing interaction with the remote command:\n\n`ssh {{username}}@{{remote_host}} -t {{command}} {{command_arguments}}`\n\n- SSH tunneling: [D]ynamic port forwarding (SOCKS proxy on `localhost:1080`):\n\n`ssh -D {{1080}} {{username}}@{{remote_host}}`\n\n- SSH tunneling: Forward a specific port (`localhost:9999` to `example.org:80`) along with disabling pseudo-[T]ty allocation and executio[N] of remote commands:\n\n`ssh -L {{9999}}:{{example.org}}:{{80}} -N -T {{username}}@{{remote_host}}`\n\n- SSH [J]umping: Connect through a jumphost to a remote server (Multiple jump hops may be specified separated by comma characters):\n\n`ssh -J {{username}}@{{jump_host}} {{username}}@{{remote_host}}`\n\n- Agent forwarding: Forward the authentication information to the remote machine (see `man ssh_config` for available options):\n\n`ssh -A {{username}}@{{remote_host}}`\n Task: ssh into "ssh.myhost.net" as user "myusername" and run command "mkdir -p $2" Bash Command:<START>ssh myusername@ssh.myhost.net "mkdir -p $2"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: ssh(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ssh(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHENTICATION | ESCAPE CHARACTERS | TCP FORWARDING | X11 FORWARDING | VERIFYING HOST KEYS | SSH-BASED VIRTUAL PRIVATE NETWORKS | ENVIRONMENT | FILES | EXIT STATUS | SEE ALSO | STANDARDS | AUTHORS | COLOPHON SSH(1) General Commands Manual SSH(1) NAME top ssh OpenSSH remote login client SYNOPSIS top ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-J destination] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] destination [command [argument ...]] [-Q query_option] DESCRIPTION top (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections, arbitrary TCP ports and Unix-domain sockets can also be forwarded over the secure channel. connects and logs into the specified destination, which may be specified as either [user@]hostname or a URI of the form ssh://[user@]hostname[:port]. The user must prove their identity to the remote machine using one of several methods (see below). If a command is specified, it will be executed on the remote host instead of a login shell. A complete command line may be specified as command, or it may have additional arguments. If supplied, the arguments will be appended to the command, separated by spaces, before it is sent to the server to be executed. The options are as follows: -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Enables forwarding of connections from an authentication agent such as ssh-agent(1). This can also be specified on a per-host basis in a configuration file. Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent. A safer alternative may be to use a jump host (see -J). -a Disables forwarding of the authentication agent connection. -B bind_interface Bind to the address of bind_interface before attempting to connect to the destination host. This is only useful on systems with more than one address. -b bind_address Use bind_address on the local machine as the source address of the connection. Only useful on systems with more than one address. -C Requests compression of all data (including stdin, stdout, stderr, and data for forwarded X11, TCP and Unix-domain connections). The compression algorithm is the same used by gzip(1). Compression is desirable on modem lines and other slow connections, but will only slow down things on fast networks. The default value can be set on a host-by-host basis in the configuration files; see the Compression option in ssh_config(5). -c cipher_spec Selects the cipher specification for encrypting the session. cipher_spec is a comma-separated list of ciphers listed in order of preference. See the Ciphers keyword in ssh_config(5) for more information. -D [bind_address:]port Specifies a local dynamic application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. Currently the SOCKS4 and SOCKS5 protocols are supported, and will act as a SOCKS server. Only root can forward privileged ports. Dynamic port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -E log_file Append debug logs to log_file instead of standard error. -e escape_char Sets the escape character for sessions with a pty (default: ~). The escape character is only recognized at the beginning of a line. The escape character followed by a dot (.) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to none disables any escapes and makes the session fully transparent. -F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config. If set to none, no configuration files will be read. -f Requests to go to background just before command execution. This is useful if is going to ask for passwords or passphrases, but the user wants it in the background. This implies -n. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm. If the ExitOnForwardFailure configuration option is set to yes, then a client started with -f will wait for all remote port forwards to be successfully established before placing itself in the background. Refer to the description of ForkAfterAuthentication in ssh_config(5) for details. -G Causes to print its configuration after evaluating Host and Match blocks and exit. -g Allows remote hosts to connect to local forwarded ports. If used on a multiplexed connection, then this option must be specified on the master process. -I pkcs11 Specify the PKCS#11 shared library should use to communicate with a PKCS#11 token providing keys for user authentication. -i identity_file Selects a file from which the identity (private key) for public key authentication is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519, ~/.ssh/id_ed25519_sk and ~/.ssh/id_dsa. Identity files may also be specified on a per-host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in configuration files). If no certificates have been explicitly specified by the CertificateFile directive, will also try to load certificate information from the filename obtained by appending -cert.pub to identity filenames. -J destination Connect to the target host by first making an connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there. Multiple jump hops may be specified separated by comma characters. This is a shortcut to specify a ProxyJump configuration directive. Note that configuration directives supplied on the command-line generally apply to the destination host and not any specified jump hosts. Use ~/.ssh/config to specify configuration for jump hosts. -K Enables GSSAPI-based authentication and forwarding (delegation) of GSSAPI credentials to the server. -k Disables forwarding (delegation) of GSSAPI credentials to the server. -L [bind_address:]port:host:hostport -L [bind_address:]port:remote_socket -L local_socket:host:hostport -L local_socket:remote_socket Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. This works by allocating a socket to listen to either a TCP port on the local side, optionally bound to the specified bind_address, or to a Unix socket. Whenever a connection is made to the local port or socket, the connection is forwarded over the secure channel, and a connection is made to either host port hostport, or the Unix socket remote_socket, from the remote machine. Port forwardings can also be specified in the configuration file. Only the superuser can forward privileged ports. IPv6 addresses can be specified by enclosing the address in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -l login_name Specifies the user to log in as on the remote machine. This also may be specified on a per-host basis in the configuration file. -M Places the client into master mode for connection sharing. Multiple -M options places into master mode but with confirmation required using ssh-askpass(1) before each operation that changes the multiplexing state (e.g. opening a new session). Refer to the description of ControlMaster in ssh_config(5) for details. -m mac_spec A comma-separated list of MAC (message authentication code) algorithms, specified in order of preference. See the MACs keyword in ssh_config(5) for more information. -N Do not execute a remote command. This is useful for just forwarding ports. Refer to the description of SessionType in ssh_config(5) for details. -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The program will be put in the background. (This does not work if needs to ask for a password or passphrase; see also the -f option.) Refer to the description of StdinNull in ssh_config(5) for details. -O ctl_cmd Control an active connection multiplexing master process. When the -O option is specified, the ctl_cmd argument is interpreted and passed to the master process. Valid commands are: check (check that the master process is running), forward (request forwardings without command execution), cancel (cancel forwardings), exit (request the master to exit), and stop (request the master to stop accepting further multiplexing requests). -o option Can be used to give options in the format used in the configuration file. This is useful for specifying options for which there is no separate command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddKeysToAgent AddressFamily BatchMode BindAddress CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers ClearAllForwardings Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist DynamicForward EnableEscapeCommandline EscapeChar ExitOnForwardFailure FingerprintHash ForkAfterAuthentication ForwardAgent ForwardX11 ForwardX11Timeout ForwardX11Trusted GatewayPorts GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LocalCommand LocalForward LogLevel MACs Match NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PermitLocalCommand PermitRemoteOpen PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump ProxyUseFdpass PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RemoteCommand RemoteForward RequestTTY RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SessionType SetEnv StdinNull StreamLocalBindMask StreamLocalBindUnlink StrictHostKeyChecking TCPKeepAlive Tunnel TunnelDevice UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS VisualHostKey XAuthLocation -P tag Specify a tag name that may be used to select configuration in ssh_config(5). Refer to the Tag and Match keywords in ssh_config(5) for more information. -p port Port to connect to on the remote host. This can be specified on a per-host basis in the configuration file. -Q query_option Queries for the algorithms supported by one of the following features: cipher (supported symmetric ciphers), cipher-auth (supported symmetric ciphers that support authenticated encryption), help (supported query terms for use with the -Q flag), mac (supported message integrity codes), kex (key exchange algorithms), key (key types), key-ca-sign (valid CA signature algorithms for certificates), key-cert (certificate key types), key-plain (non-certificate key types), key-sig (all key types and signature algorithms), protocol-version (supported SSH protocol versions), and sig (supported signature algorithms). Alternatively, any keyword from ssh_config(5) or sshd_config(5) that takes an algorithm list may be used as an alias for the corresponding query_option. -q Quiet mode. Causes most warning and diagnostic messages to be suppressed. -R [bind_address:]port:host:hostport -R [bind_address:]port:local_socket -R remote_socket:host:hostport -R remote_socket:local_socket -R [bind_address:]port Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side. This works by allocating a socket to listen to either a TCP port or to a Unix socket on the remote side. Whenever a connection is made to this port or Unix socket, the connection is forwarded over the secure channel, and a connection is made from the local machine to either an explicit destination specified by host port hostport, or local_socket, or, if no explicit destination was specified, will act as a SOCKS 4/5 proxy and forward connections to the destinations requested by the remote SOCKS client. Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square brackets. By default, TCP listening sockets on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address *, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)). If the port argument is 0, the listen port will be dynamically allocated on the server and reported to the client at run time. When used together with -O forward, the allocated port will be printed to the standard output. -S ctl_path Specifies the location of a control socket for connection sharing, or the string none to disable connection sharing. Refer to the description of ControlPath and ControlMaster in ssh_config(5) for details. -s May be used to request invocation of a subsystem on the remote system. Subsystems facilitate the use of SSH as a secure transport for other applications (e.g. sftp(1)). The subsystem is specified as the remote command. Refer to the description of SessionType in ssh_config(5) for details. -T Disable pseudo-terminal allocation. -t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if has no local tty. -V Display the version number and exit. -v Verbose mode. Causes to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3. -W host:port Requests that standard input and output on the client be forwarded to host on port over the secure channel. Implies -N, -T, ExitOnForwardFailure and ClearAllForwardings, though these can be overridden in the configuration file or using -o command line options. -w local_tun[:remote_tun] Requests tunnel device forwarding with the specified tun(4) devices between the client (local_tun) and the server (remote_tun). The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. See also the Tunnel and TunnelDevice directives in ssh_config(5). If the Tunnel directive is unset, it will be set to the default tunnel mode, which is point-to-point. If a different Tunnel forwarding mode it desired, then it should be specified before -w. -X Enables X11 forwarding. This can also be specified on a per-host basis in a configuration file. X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring. For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. Refer to the -Y option and the ForwardX11Trusted directive in ssh_config(5) for more information. -x Disables X11 forwarding. -Y Enables trusted X11 forwarding. Trusted X11 forwardings are not subjected to the X11 SECURITY extension controls. -y Send log information using the syslog(3) system module. By default this information is sent to stderr. may additionally obtain configuration data from a per-user configuration file and a system-wide configuration file. The file format and configuration options are described in ssh_config(5). AUTHENTICATION top The OpenSSH SSH client supports SSH protocol 2. The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, keyboard-interactive authentication, and password authentication. Authentication methods are tried in the order specified above, though PreferredAuthentications can be used to change the default order. Host-based authentication works as follows: If the machine the user logs in from is listed in /etc/hosts.equiv or /etc/shosts.equiv on the remote machine, the user is non-root and the user names are the same on both sides, or if the files ~/.rhosts or ~/.shosts exist in the user's home directory on the remote machine and contain a line containing the name of the client machine and the name of the user on that machine, the user is considered for login. Additionally, the server must be able to verify the client's host key (see the description of /etc/ssh/ssh_known_hosts and ~/.ssh/known_hosts, below) for login to be permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing, and routing spoofing. [Note to the administrator: /etc/hosts.equiv, ~/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.] Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. implements public key authentication protocol automatically, using one of the DSA, ECDSA, Ed25519 or RSA algorithms. The HISTORY section of ssl(8) contains a brief discussion of the DSA and RSA algorithms. The file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. When the user logs in, the program tells the server which key pair it would like to use for authentication. The client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account. The server may inform the client of errors that prevented public key authentication from succeeding after authentication completes using a different method. These may be viewed by increasing the LogLevel to DEBUG or higher (e.g. by using the -v flag). The user creates their key pair by running ssh-keygen(1). This stores the private key in ~/.ssh/id_dsa (DSA), ~/.ssh/id_ecdsa (ECDSA), ~/.ssh/id_ecdsa_sk (authenticator-hosted ECDSA), ~/.ssh/id_ed25519 (Ed25519), ~/.ssh/id_ed25519_sk (authenticator- hosted Ed25519), or ~/.ssh/id_rsa (RSA) and stores the public key in ~/.ssh/id_dsa.pub (DSA), ~/.ssh/id_ecdsa.pub (ECDSA), ~/.ssh/id_ecdsa_sk.pub (authenticator-hosted ECDSA), ~/.ssh/id_ed25519.pub (Ed25519), ~/.ssh/id_ed25519_sk.pub (authenticator-hosted Ed25519), or ~/.ssh/id_rsa.pub (RSA) in the user's home directory. The user should then copy the public key to ~/.ssh/authorized_keys in their home directory on the remote machine. The authorized_keys file corresponds to the conventional ~/.rhosts file, and has one key per line, though the lines can be very long. After this, the user can log in without giving the password. A variation on public key authentication is available in the form of certificate authentication: instead of a set of public/private keys, signed certificates are used. This has the advantage that a single trusted certification authority can be used in place of many public/private keys. See the CERTIFICATES section of ssh-keygen(1) for more information. The most convenient way to use public key or certificate authentication may be with an authentication agent. See ssh-agent(1) and (optionally) the AddKeysToAgent directive in ssh_config(5) for more information. Keyboard-interactive authentication works as follows: The server sends an arbitrary "challenge" text and prompts for a response, possibly multiple times. Examples of keyboard-interactive authentication include BSD Authentication (see login.conf(5)) and PAM (some non-OpenBSD systems). Finally, if other authentication methods fail, prompts the user for a password. The password is sent to the remote host for checking; however, since all communications are encrypted, the password cannot be seen by someone listening on the network. automatically maintains and checks a database containing identification for all hosts it has ever been used with. Host keys are stored in ~/.ssh/known_hosts in the user's home directory. Additionally, the file /etc/ssh/ssh_known_hosts is automatically checked for known hosts. Any new hosts are automatically added to the user's file. If a host's identification ever changes, warns about this and disables password authentication to prevent server spoofing or man-in-the- middle attacks, which could otherwise be used to circumvent the encryption. The StrictHostKeyChecking option can be used to control logins to machines whose host key is not known or has changed. When the user's identity has been accepted by the server, the server either executes the given command in a non-interactive session or, if no command has been specified, logs into the machine and gives the user a normal shell as an interactive session. All communication with the remote command or shell will be automatically encrypted. If an interactive session is requested, by default will only request a pseudo-terminal (pty) for interactive sessions when the client has one. The flags -T and -t can be used to override this behaviour. If a pseudo-terminal has been allocated, the user may use the escape characters noted below. If no pseudo-terminal has been allocated, the session is transparent and can be used to reliably transfer binary data. On most systems, setting the escape character to none will also make the session transparent even if a tty is used. The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed. ESCAPE CHARACTERS top When a pseudo-terminal has been requested, supports a number of functions through the use of an escape character. A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option. The supported escapes (assuming the default ~) are: ~. Disconnect. ~^Z Background . ~# List forwarded connections. ~& Background at logout when waiting for forwarded connection / X11 sessions to terminate. ~? Display a list of escape characters. ~B Send a BREAK to the remote system (only useful if the peer supports it). ~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing port-forwardings with -KL[bind_address:]port for local, -KR[bind_address:]port for remote and -KD[bind_address:]port for dynamic port-forwardings. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is available, using the -h option. ~R Request rekeying of the connection (only useful if the peer supports it). ~V Decrease the verbosity (LogLevel) when errors are being written to stderr. ~v Increase the verbosity (LogLevel) when errors are being written to stderr. TCP FORWARDING top Forwarding of arbitrary TCP connections over a secure channel can be specified either on the command line or in a configuration file. One possible application of TCP forwarding is a secure connection to a mail server; another is going through firewalls. In the example below, we look at encrypting communication for an IRC client, even though the IRC server it connects to does not directly support encrypted communication. This works as follows: the user connects to the remote host using , specifying the ports to be used to forward the connection. After that it is possible to start the program locally, and will encrypt and forward the connection to the remote server. The following example tunnels an IRC session from the client to an IRC server at server.example.com, joining channel #users, nickname pinky, using the standard IRC port, 6667: $ ssh -f -L 6667:localhost:6667 server.example.com sleep 10 $ irc -c '#users' pinky IRC/127.0.0.1 The -f option backgrounds and the remote command sleep 10 is specified to allow an amount of time (10 seconds, in the example) to start the program which is going to use the tunnel. If no connections are made within the time specified, will exit. X11 FORWARDING top If the ForwardX11 variable is set to yes (or see the description of the -X, -x, and -Y options above) and the user is using X11 (the DISPLAY environment variable is set), the connection to the X11 display is automatically forwarded to the remote side in such a way that any X11 programs started from the shell (or command) will go through the encrypted channel, and the connection to the real X server will be made from the local machine. The user should not manually set DISPLAY. Forwarding of X11 connections can be configured on the command line or in configuration files. The DISPLAY value set by will point to the server machine, but with a display number greater than zero. This is normal, and happens because creates a proxy X server on the server machine for forwarding the connections over the encrypted channel. will also automatically set up Xauthority data on the server machine. For this purpose, it will generate a random authorization cookie, store it in Xauthority on the server, and verify that any forwarded connections carry this cookie and replace it by the real cookie when the connection is opened. The real authentication cookie is never sent to the server machine (and no cookies are sent in the plain). If the ForwardAgent variable is set to yes (or see the description of the -A and -a options above) and the user is using an authentication agent, the connection to the agent is automatically forwarded to the remote side. VERIFYING HOST KEYS top When connecting to a server for the first time, a fingerprint of the server's public key is presented to the user (unless the option StrictHostKeyChecking has been disabled). Fingerprints can be determined using ssh-keygen(1): $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key If the fingerprint is already known, it can be matched and the key can be accepted or rejected. If only legacy (MD5) fingerprints for the server are available, the ssh-keygen(1) -E option may be used to downgrade the fingerprint algorithm to match. Because of the difficulty of comparing host keys just by looking at fingerprint strings, there is also support to compare host keys visually, using random art. By setting the VisualHostKey option to yes, a small ASCII graphic gets displayed on every login to a server, no matter if the session itself is interactive or not. By learning the pattern a known server produces, a user can easily find out that the host key has changed when a completely different pattern is displayed. Because these patterns are not unambiguous however, a pattern that looks similar to the pattern remembered only gives a good probability that the host key is the same, not guaranteed proof. To get a listing of the fingerprints along with their random art for all known hosts, the following command line can be used: $ ssh-keygen -lv -f ~/.ssh/known_hosts If the fingerprint is unknown, an alternative method of verification is available: SSH fingerprints verified by DNS. An additional resource record (RR), SSHFP, is added to a zonefile and the connecting client is able to match the fingerprint with that of the key presented. In this example, we are connecting a client to a server, host.example.com. The SSHFP resource records should first be added to the zonefile for host.example.com: $ ssh-keygen -r host.example.com. The output lines will have to be added to the zonefile. To check that the zone is answering fingerprint queries: $ dig -t SSHFP host.example.com Finally the client connects: $ ssh -o "VerifyHostKeyDNS ask" host.example.com [...] Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? See the VerifyHostKeyDNS option in ssh_config(5) for more information. SSH-BASED VIRTUAL PRIVATE NETWORKS top contains support for Virtual Private Network (VPN) tunnelling using the tun(4) network pseudo-device, allowing two networks to be joined securely. The sshd_config(5) configuration option PermitTunnel controls whether the server supports this, and at what level (layer 2 or 3 traffic). The following example would connect client network 10.0.50.0/24 with remote network 10.0.99.0/24 using a point-to-point connection from 10.1.1.1 to 10.1.1.2, provided that the SSH server running on the gateway to the remote network, at 192.168.1.15, allows it. On the client: # ssh -f -w 0:1 192.168.1.15 true # ifconfig tun0 10.1.1.1 10.1.1.2 netmask 255.255.255.252 # route add 10.0.99.0/24 10.1.1.2 On the server: # ifconfig tun1 10.1.1.2 10.1.1.1 netmask 255.255.255.252 # route add 10.0.50.0/24 10.1.1.1 Client access may be more finely tuned via the /root/.ssh/authorized_keys file (see below) and the PermitRootLogin server option. The following entry would permit connections on tun(4) device 1 from user jane and on tun device 2 from user john, if PermitRootLogin is set to forced-commands-only: tunnel="1",command="sh /etc/netstart tun1" ssh-rsa ... jane tunnel="2",command="sh /etc/netstart tun2" ssh-rsa ... john Since an SSH-based setup entails a fair amount of overhead, it may be more suited to temporary setups, such as for wireless VPNs. More permanent VPNs are better provided by tools such as ipsecctl(8) and isakmpd(8). ENVIRONMENT top will normally set the following environment variables: DISPLAY The DISPLAY variable indicates the location of the X11 server. It is automatically set by to point to a value of the form hostname:n, where hostname indicates the host where the shell runs, and n is an integer 1. uses this special value to forward X11 connections over the secure channel. The user should normally not set DISPLAY explicitly, as that will render the X11 connection insecure (and will require the user to manually copy any required authorization cookies). HOME Set to the path of the user's home directory. LOGNAME Synonym for USER; set for compatibility with systems that use this variable. MAIL Set to the path of the user's mailbox. PATH Set to the default PATH, as specified when compiling . SSH_ASKPASS If needs a passphrase, it will read the passphrase from the current terminal if it was run from a terminal. If does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS and open an X11 window to read the passphrase. This is particularly useful when calling from a .xsession or related script. (Note that on some machines it may be necessary to redirect the input from /dev/null to make this work.) SSH_ASKPASS_REQUIRE Allows further control over the use of an askpass program. If this variable is set to never then will never attempt to use one. If it is set to prefer, then will prefer to use the askpass program instead of the TTY when requesting passwords. Finally, if the variable is set to force, then the askpass program will be used for all passphrase input regardless of whether DISPLAY is set. SSH_AUTH_SOCK Identifies the path of a Unix-domain socket used to communicate with the agent. SSH_CONNECTION Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number. SSH_ORIGINAL_COMMAND This variable contains the original command line if a forced command is executed. It can be used to extract the original arguments. SSH_TTY This is set to the name of the tty (path to the device) associated with the current shell or command. If the current session has no tty, this variable is not set. SSH_TUNNEL Optionally set by sshd(8) to contain the interface names assigned if tunnel forwarding was requested by the client. SSH_USER_AUTH Optionally set by sshd(8), this variable may contain a pathname to a file that lists the authentication methods successfully used when the session was established, including any public keys that were used. TZ This variable is set to indicate the present time zone if it was set when the daemon was started (i.e. the daemon passes the value on to new connections). USER Set to the name of the user logging in. Additionally, reads ~/.ssh/environment, and adds lines of the format VARNAME=value to the environment if the file exists and users are allowed to change their environment. For more information, see the PermitUserEnvironment option in sshd_config(5). FILES top ~/.rhosts This file is used for host-based authentication (see above). On some machines this file may need to be world- readable if the user's home directory is on an NFS partition, because sshd(8) reads it as root. Additionally, this file must be owned by the user, and must not have write permissions for anyone else. The recommended permission for most machines is read/write for the user, and not accessible by others. ~/.shosts This file is used in exactly the same way as .rhosts, but allows host-based authentication without permitting login with rlogin/rsh. ~/.ssh/ This directory is the default location for all user- specific configuration and authentication information. There is no general requirement to keep the entire contents of this directory secret, but the recommended permissions are read/write/execute for the user, and not accessible by others. ~/.ssh/authorized_keys Lists the public keys (DSA, ECDSA, Ed25519, RSA) that can be used for logging in as this user. The format of this file is described in the sshd(8) manual page. This file is not highly sensitive, but the recommended permissions are read/write for the user, and not accessible by others. ~/.ssh/config This is the per-user configuration file. The file format and configuration options are described in ssh_config(5). Because of the potential for abuse, this file must have strict permissions: read/write for the user, and not writable by others. ~/.ssh/environment Contains additional definitions for environment variables; see ENVIRONMENT, above. ~/.ssh/id_dsa ~/.ssh/id_ecdsa ~/.ssh/id_ecdsa_sk ~/.ssh/id_ed25519 ~/.ssh/id_ed25519_sk ~/.ssh/id_rsa Contains the private key for authentication. These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute). will simply ignore a private key file if it is accessible by others. It is possible to specify a passphrase when generating the key which will be used to encrypt the sensitive part of this file using AES-128. ~/.ssh/id_dsa.pub ~/.ssh/id_ecdsa.pub ~/.ssh/id_ecdsa_sk.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_ed25519_sk.pub ~/.ssh/id_rsa.pub Contains the public key for authentication. These files are not sensitive and can (but need not) be readable by anyone. ~/.ssh/known_hosts Contains a list of host keys for all hosts the user has logged into that are not already in the systemwide list of known host keys. See sshd(8) for further details of the format of this file. ~/.ssh/rc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. /etc/hosts.equiv This file is for host-based authentication (see above). It should only be writable by root. /etc/shosts.equiv This file is used in exactly the same way as hosts.equiv, but allows host-based authentication without permitting login with rlogin/rsh. /etc/ssh/ssh_config Systemwide configuration file. The file format and configuration options are described in ssh_config(5). /etc/ssh/ssh_host_key /etc/ssh/ssh_host_dsa_key /etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_ed25519_key /etc/ssh/ssh_host_rsa_key These files contain the private parts of the host keys and are used for host-based authentication. /etc/ssh/ssh_known_hosts Systemwide list of known host keys. This file should be prepared by the system administrator to contain the public host keys of all machines in the organization. It should be world-readable. See sshd(8) for further details of the format of this file. /etc/ssh/sshrc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. EXIT STATUS top exits with the exit status of the remote command or with 255 if an error occurred. SEE ALSO top scp(1), sftp(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh-keyscan(1), tun(4), ssh_config(5), ssh-keysign(8), sshd(8) STANDARDS top S. Lehtinen and C. Lonvick, The Secure Shell (SSH) Protocol Assigned Numbers, RFC 4250, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Protocol Architecture, RFC 4251, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Authentication Protocol, RFC 4252, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Transport Layer Protocol, RFC 4253, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Connection Protocol, RFC 4254, January 2006. J. Schlyter and W. Griffin, Using DNS to Securely Publish Secure Shell (SSH) Key Fingerprints, RFC 4255, January 2006. F. Cusack and M. Forssen, Generic Message Exchange Authentication for the Secure Shell Protocol (SSH), RFC 4256, January 2006. J. Galbraith and P. Remaker, The Secure Shell (SSH) Session Channel Break Extension, RFC 4335, January 2006. M. Bellare, T. Kohno, and C. Namprempre, The Secure Shell (SSH) Transport Layer Encryption Modes, RFC 4344, January 2006. B. Harris, Improved Arcfour Modes for the Secure Shell (SSH) Transport Layer Protocol, RFC 4345, January 2006. M. Friedl, N. Provos, and W. Simpson, Diffie-Hellman Group Exchange for the Secure Shell (SSH) Transport Layer Protocol, RFC 4419, March 2006. J. Galbraith and R. Thayer, The Secure Shell (SSH) Public Key File Format, RFC 4716, November 2006. D. Stebila and J. Green, Elliptic Curve Algorithm Integration in the Secure Shell Transport Layer, RFC 5656, December 2009. A. Perrig and D. Song, Hash Visualization: a New Technique to improve Real-World Security, 1999, International Workshop on Cryptographic Techniques and E-Commerce (CrypTEC '99). AUTHORS top OpenSSH is a derivative of the original and free ssh 1.2.12 release by Tatu Ylonen. Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo de Raadt and Dug Song removed many bugs, re- added newer features and created OpenSSH. Markus Friedl contributed the support for SSH protocol versions 1.5 and 2.0. COLOPHON top This page is part of the openssh (Portable OpenSSH) project. Information about the project can be found at http://www.openssh.com/portable.html. If you have a bug report for this manual page, see http://www.openssh.com/report.html. This page was obtained from the tarball openssh-9.6p1.tar.gz fetched from http://ftp.eu.openbsd.org/pub/OpenBSD/OpenSSH/portable/ 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 October 11, 2023 SSH(1) Pages that refer to this page: stap-jupyter(1), systemd-stdio-bridge(1), tar(1), sd_bus_default(3), environment.d(5), proc(5), user@.service(5), pty(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: ssh into "ssh.myhost.net" as user "myusername" and run command "mkdir -p $2" Bash Command:<START>ssh myusername@ssh.myhost.net "mkdir -p $2"<END>
ssh into default vagrant host without running "vagrant ssh" by passing the configuration parameters vagrant uses for ssh
ssh vagrant@127.0.0.1 -p 2222 -o Compression=yes -o DSAAuthentication=yes -o LogLevel=FATAL -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -i ~/.vagrant.d/less_insecure_private_key -o ForwardAgent=yes
['ssh']
Output a Bash command to accomplish the following task. Task: ssh into default vagrant host without running "vagrant ssh" by passing the configuration parameters vagrant uses for ssh Bash Command:<START>ssh vagrant@127.0.0.1 -p 2222 -o Compression=yes -o DSAAuthentication=yes -o LogLevel=FATAL -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -i ~/.vagrant.d/less_insecure_private_key -o ForwardAgent=yes<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # ssh\n\n> Secure Shell is a protocol used to securely log onto remote systems.\n> It can be used for logging or executing commands on a remote server.\n> More information: <https://man.openbsd.org/ssh>.\n\n- Connect to a remote server:\n\n`ssh {{username}}@{{remote_host}}`\n\n- Connect to a remote server with a specific identity (private key):\n\n`ssh -i {{path/to/key_file}} {{username}}@{{remote_host}}`\n\n- Connect to a remote server using a specific [p]ort:\n\n`ssh {{username}}@{{remote_host}} -p {{2222}}`\n\n- Run a command on a remote server with a [t]ty allocation allowing interaction with the remote command:\n\n`ssh {{username}}@{{remote_host}} -t {{command}} {{command_arguments}}`\n\n- SSH tunneling: [D]ynamic port forwarding (SOCKS proxy on `localhost:1080`):\n\n`ssh -D {{1080}} {{username}}@{{remote_host}}`\n\n- SSH tunneling: Forward a specific port (`localhost:9999` to `example.org:80`) along with disabling pseudo-[T]ty allocation and executio[N] of remote commands:\n\n`ssh -L {{9999}}:{{example.org}}:{{80}} -N -T {{username}}@{{remote_host}}`\n\n- SSH [J]umping: Connect through a jumphost to a remote server (Multiple jump hops may be specified separated by comma characters):\n\n`ssh -J {{username}}@{{jump_host}} {{username}}@{{remote_host}}`\n\n- Agent forwarding: Forward the authentication information to the remote machine (see `man ssh_config` for available options):\n\n`ssh -A {{username}}@{{remote_host}}`\n Task: ssh into default vagrant host without running "vagrant ssh" by passing the configuration parameters vagrant uses for ssh Bash Command:<START>ssh vagrant@127.0.0.1 -p 2222 -o Compression=yes -o DSAAuthentication=yes -o LogLevel=FATAL -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -i ~/.vagrant.d/less_insecure_private_key -o ForwardAgent=yes<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: ssh(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ssh(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHENTICATION | ESCAPE CHARACTERS | TCP FORWARDING | X11 FORWARDING | VERIFYING HOST KEYS | SSH-BASED VIRTUAL PRIVATE NETWORKS | ENVIRONMENT | FILES | EXIT STATUS | SEE ALSO | STANDARDS | AUTHORS | COLOPHON SSH(1) General Commands Manual SSH(1) NAME top ssh OpenSSH remote login client SYNOPSIS top ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-J destination] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] destination [command [argument ...]] [-Q query_option] DESCRIPTION top (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections, arbitrary TCP ports and Unix-domain sockets can also be forwarded over the secure channel. connects and logs into the specified destination, which may be specified as either [user@]hostname or a URI of the form ssh://[user@]hostname[:port]. The user must prove their identity to the remote machine using one of several methods (see below). If a command is specified, it will be executed on the remote host instead of a login shell. A complete command line may be specified as command, or it may have additional arguments. If supplied, the arguments will be appended to the command, separated by spaces, before it is sent to the server to be executed. The options are as follows: -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Enables forwarding of connections from an authentication agent such as ssh-agent(1). This can also be specified on a per-host basis in a configuration file. Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent. A safer alternative may be to use a jump host (see -J). -a Disables forwarding of the authentication agent connection. -B bind_interface Bind to the address of bind_interface before attempting to connect to the destination host. This is only useful on systems with more than one address. -b bind_address Use bind_address on the local machine as the source address of the connection. Only useful on systems with more than one address. -C Requests compression of all data (including stdin, stdout, stderr, and data for forwarded X11, TCP and Unix-domain connections). The compression algorithm is the same used by gzip(1). Compression is desirable on modem lines and other slow connections, but will only slow down things on fast networks. The default value can be set on a host-by-host basis in the configuration files; see the Compression option in ssh_config(5). -c cipher_spec Selects the cipher specification for encrypting the session. cipher_spec is a comma-separated list of ciphers listed in order of preference. See the Ciphers keyword in ssh_config(5) for more information. -D [bind_address:]port Specifies a local dynamic application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. Currently the SOCKS4 and SOCKS5 protocols are supported, and will act as a SOCKS server. Only root can forward privileged ports. Dynamic port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -E log_file Append debug logs to log_file instead of standard error. -e escape_char Sets the escape character for sessions with a pty (default: ~). The escape character is only recognized at the beginning of a line. The escape character followed by a dot (.) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to none disables any escapes and makes the session fully transparent. -F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config. If set to none, no configuration files will be read. -f Requests to go to background just before command execution. This is useful if is going to ask for passwords or passphrases, but the user wants it in the background. This implies -n. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm. If the ExitOnForwardFailure configuration option is set to yes, then a client started with -f will wait for all remote port forwards to be successfully established before placing itself in the background. Refer to the description of ForkAfterAuthentication in ssh_config(5) for details. -G Causes to print its configuration after evaluating Host and Match blocks and exit. -g Allows remote hosts to connect to local forwarded ports. If used on a multiplexed connection, then this option must be specified on the master process. -I pkcs11 Specify the PKCS#11 shared library should use to communicate with a PKCS#11 token providing keys for user authentication. -i identity_file Selects a file from which the identity (private key) for public key authentication is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519, ~/.ssh/id_ed25519_sk and ~/.ssh/id_dsa. Identity files may also be specified on a per-host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in configuration files). If no certificates have been explicitly specified by the CertificateFile directive, will also try to load certificate information from the filename obtained by appending -cert.pub to identity filenames. -J destination Connect to the target host by first making an connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there. Multiple jump hops may be specified separated by comma characters. This is a shortcut to specify a ProxyJump configuration directive. Note that configuration directives supplied on the command-line generally apply to the destination host and not any specified jump hosts. Use ~/.ssh/config to specify configuration for jump hosts. -K Enables GSSAPI-based authentication and forwarding (delegation) of GSSAPI credentials to the server. -k Disables forwarding (delegation) of GSSAPI credentials to the server. -L [bind_address:]port:host:hostport -L [bind_address:]port:remote_socket -L local_socket:host:hostport -L local_socket:remote_socket Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. This works by allocating a socket to listen to either a TCP port on the local side, optionally bound to the specified bind_address, or to a Unix socket. Whenever a connection is made to the local port or socket, the connection is forwarded over the secure channel, and a connection is made to either host port hostport, or the Unix socket remote_socket, from the remote machine. Port forwardings can also be specified in the configuration file. Only the superuser can forward privileged ports. IPv6 addresses can be specified by enclosing the address in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -l login_name Specifies the user to log in as on the remote machine. This also may be specified on a per-host basis in the configuration file. -M Places the client into master mode for connection sharing. Multiple -M options places into master mode but with confirmation required using ssh-askpass(1) before each operation that changes the multiplexing state (e.g. opening a new session). Refer to the description of ControlMaster in ssh_config(5) for details. -m mac_spec A comma-separated list of MAC (message authentication code) algorithms, specified in order of preference. See the MACs keyword in ssh_config(5) for more information. -N Do not execute a remote command. This is useful for just forwarding ports. Refer to the description of SessionType in ssh_config(5) for details. -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The program will be put in the background. (This does not work if needs to ask for a password or passphrase; see also the -f option.) Refer to the description of StdinNull in ssh_config(5) for details. -O ctl_cmd Control an active connection multiplexing master process. When the -O option is specified, the ctl_cmd argument is interpreted and passed to the master process. Valid commands are: check (check that the master process is running), forward (request forwardings without command execution), cancel (cancel forwardings), exit (request the master to exit), and stop (request the master to stop accepting further multiplexing requests). -o option Can be used to give options in the format used in the configuration file. This is useful for specifying options for which there is no separate command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddKeysToAgent AddressFamily BatchMode BindAddress CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers ClearAllForwardings Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist DynamicForward EnableEscapeCommandline EscapeChar ExitOnForwardFailure FingerprintHash ForkAfterAuthentication ForwardAgent ForwardX11 ForwardX11Timeout ForwardX11Trusted GatewayPorts GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LocalCommand LocalForward LogLevel MACs Match NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PermitLocalCommand PermitRemoteOpen PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump ProxyUseFdpass PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RemoteCommand RemoteForward RequestTTY RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SessionType SetEnv StdinNull StreamLocalBindMask StreamLocalBindUnlink StrictHostKeyChecking TCPKeepAlive Tunnel TunnelDevice UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS VisualHostKey XAuthLocation -P tag Specify a tag name that may be used to select configuration in ssh_config(5). Refer to the Tag and Match keywords in ssh_config(5) for more information. -p port Port to connect to on the remote host. This can be specified on a per-host basis in the configuration file. -Q query_option Queries for the algorithms supported by one of the following features: cipher (supported symmetric ciphers), cipher-auth (supported symmetric ciphers that support authenticated encryption), help (supported query terms for use with the -Q flag), mac (supported message integrity codes), kex (key exchange algorithms), key (key types), key-ca-sign (valid CA signature algorithms for certificates), key-cert (certificate key types), key-plain (non-certificate key types), key-sig (all key types and signature algorithms), protocol-version (supported SSH protocol versions), and sig (supported signature algorithms). Alternatively, any keyword from ssh_config(5) or sshd_config(5) that takes an algorithm list may be used as an alias for the corresponding query_option. -q Quiet mode. Causes most warning and diagnostic messages to be suppressed. -R [bind_address:]port:host:hostport -R [bind_address:]port:local_socket -R remote_socket:host:hostport -R remote_socket:local_socket -R [bind_address:]port Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side. This works by allocating a socket to listen to either a TCP port or to a Unix socket on the remote side. Whenever a connection is made to this port or Unix socket, the connection is forwarded over the secure channel, and a connection is made from the local machine to either an explicit destination specified by host port hostport, or local_socket, or, if no explicit destination was specified, will act as a SOCKS 4/5 proxy and forward connections to the destinations requested by the remote SOCKS client. Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square brackets. By default, TCP listening sockets on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address *, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)). If the port argument is 0, the listen port will be dynamically allocated on the server and reported to the client at run time. When used together with -O forward, the allocated port will be printed to the standard output. -S ctl_path Specifies the location of a control socket for connection sharing, or the string none to disable connection sharing. Refer to the description of ControlPath and ControlMaster in ssh_config(5) for details. -s May be used to request invocation of a subsystem on the remote system. Subsystems facilitate the use of SSH as a secure transport for other applications (e.g. sftp(1)). The subsystem is specified as the remote command. Refer to the description of SessionType in ssh_config(5) for details. -T Disable pseudo-terminal allocation. -t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if has no local tty. -V Display the version number and exit. -v Verbose mode. Causes to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3. -W host:port Requests that standard input and output on the client be forwarded to host on port over the secure channel. Implies -N, -T, ExitOnForwardFailure and ClearAllForwardings, though these can be overridden in the configuration file or using -o command line options. -w local_tun[:remote_tun] Requests tunnel device forwarding with the specified tun(4) devices between the client (local_tun) and the server (remote_tun). The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. See also the Tunnel and TunnelDevice directives in ssh_config(5). If the Tunnel directive is unset, it will be set to the default tunnel mode, which is point-to-point. If a different Tunnel forwarding mode it desired, then it should be specified before -w. -X Enables X11 forwarding. This can also be specified on a per-host basis in a configuration file. X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring. For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. Refer to the -Y option and the ForwardX11Trusted directive in ssh_config(5) for more information. -x Disables X11 forwarding. -Y Enables trusted X11 forwarding. Trusted X11 forwardings are not subjected to the X11 SECURITY extension controls. -y Send log information using the syslog(3) system module. By default this information is sent to stderr. may additionally obtain configuration data from a per-user configuration file and a system-wide configuration file. The file format and configuration options are described in ssh_config(5). AUTHENTICATION top The OpenSSH SSH client supports SSH protocol 2. The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, keyboard-interactive authentication, and password authentication. Authentication methods are tried in the order specified above, though PreferredAuthentications can be used to change the default order. Host-based authentication works as follows: If the machine the user logs in from is listed in /etc/hosts.equiv or /etc/shosts.equiv on the remote machine, the user is non-root and the user names are the same on both sides, or if the files ~/.rhosts or ~/.shosts exist in the user's home directory on the remote machine and contain a line containing the name of the client machine and the name of the user on that machine, the user is considered for login. Additionally, the server must be able to verify the client's host key (see the description of /etc/ssh/ssh_known_hosts and ~/.ssh/known_hosts, below) for login to be permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing, and routing spoofing. [Note to the administrator: /etc/hosts.equiv, ~/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.] Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. implements public key authentication protocol automatically, using one of the DSA, ECDSA, Ed25519 or RSA algorithms. The HISTORY section of ssl(8) contains a brief discussion of the DSA and RSA algorithms. The file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. When the user logs in, the program tells the server which key pair it would like to use for authentication. The client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account. The server may inform the client of errors that prevented public key authentication from succeeding after authentication completes using a different method. These may be viewed by increasing the LogLevel to DEBUG or higher (e.g. by using the -v flag). The user creates their key pair by running ssh-keygen(1). This stores the private key in ~/.ssh/id_dsa (DSA), ~/.ssh/id_ecdsa (ECDSA), ~/.ssh/id_ecdsa_sk (authenticator-hosted ECDSA), ~/.ssh/id_ed25519 (Ed25519), ~/.ssh/id_ed25519_sk (authenticator- hosted Ed25519), or ~/.ssh/id_rsa (RSA) and stores the public key in ~/.ssh/id_dsa.pub (DSA), ~/.ssh/id_ecdsa.pub (ECDSA), ~/.ssh/id_ecdsa_sk.pub (authenticator-hosted ECDSA), ~/.ssh/id_ed25519.pub (Ed25519), ~/.ssh/id_ed25519_sk.pub (authenticator-hosted Ed25519), or ~/.ssh/id_rsa.pub (RSA) in the user's home directory. The user should then copy the public key to ~/.ssh/authorized_keys in their home directory on the remote machine. The authorized_keys file corresponds to the conventional ~/.rhosts file, and has one key per line, though the lines can be very long. After this, the user can log in without giving the password. A variation on public key authentication is available in the form of certificate authentication: instead of a set of public/private keys, signed certificates are used. This has the advantage that a single trusted certification authority can be used in place of many public/private keys. See the CERTIFICATES section of ssh-keygen(1) for more information. The most convenient way to use public key or certificate authentication may be with an authentication agent. See ssh-agent(1) and (optionally) the AddKeysToAgent directive in ssh_config(5) for more information. Keyboard-interactive authentication works as follows: The server sends an arbitrary "challenge" text and prompts for a response, possibly multiple times. Examples of keyboard-interactive authentication include BSD Authentication (see login.conf(5)) and PAM (some non-OpenBSD systems). Finally, if other authentication methods fail, prompts the user for a password. The password is sent to the remote host for checking; however, since all communications are encrypted, the password cannot be seen by someone listening on the network. automatically maintains and checks a database containing identification for all hosts it has ever been used with. Host keys are stored in ~/.ssh/known_hosts in the user's home directory. Additionally, the file /etc/ssh/ssh_known_hosts is automatically checked for known hosts. Any new hosts are automatically added to the user's file. If a host's identification ever changes, warns about this and disables password authentication to prevent server spoofing or man-in-the- middle attacks, which could otherwise be used to circumvent the encryption. The StrictHostKeyChecking option can be used to control logins to machines whose host key is not known or has changed. When the user's identity has been accepted by the server, the server either executes the given command in a non-interactive session or, if no command has been specified, logs into the machine and gives the user a normal shell as an interactive session. All communication with the remote command or shell will be automatically encrypted. If an interactive session is requested, by default will only request a pseudo-terminal (pty) for interactive sessions when the client has one. The flags -T and -t can be used to override this behaviour. If a pseudo-terminal has been allocated, the user may use the escape characters noted below. If no pseudo-terminal has been allocated, the session is transparent and can be used to reliably transfer binary data. On most systems, setting the escape character to none will also make the session transparent even if a tty is used. The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed. ESCAPE CHARACTERS top When a pseudo-terminal has been requested, supports a number of functions through the use of an escape character. A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option. The supported escapes (assuming the default ~) are: ~. Disconnect. ~^Z Background . ~# List forwarded connections. ~& Background at logout when waiting for forwarded connection / X11 sessions to terminate. ~? Display a list of escape characters. ~B Send a BREAK to the remote system (only useful if the peer supports it). ~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing port-forwardings with -KL[bind_address:]port for local, -KR[bind_address:]port for remote and -KD[bind_address:]port for dynamic port-forwardings. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is available, using the -h option. ~R Request rekeying of the connection (only useful if the peer supports it). ~V Decrease the verbosity (LogLevel) when errors are being written to stderr. ~v Increase the verbosity (LogLevel) when errors are being written to stderr. TCP FORWARDING top Forwarding of arbitrary TCP connections over a secure channel can be specified either on the command line or in a configuration file. One possible application of TCP forwarding is a secure connection to a mail server; another is going through firewalls. In the example below, we look at encrypting communication for an IRC client, even though the IRC server it connects to does not directly support encrypted communication. This works as follows: the user connects to the remote host using , specifying the ports to be used to forward the connection. After that it is possible to start the program locally, and will encrypt and forward the connection to the remote server. The following example tunnels an IRC session from the client to an IRC server at server.example.com, joining channel #users, nickname pinky, using the standard IRC port, 6667: $ ssh -f -L 6667:localhost:6667 server.example.com sleep 10 $ irc -c '#users' pinky IRC/127.0.0.1 The -f option backgrounds and the remote command sleep 10 is specified to allow an amount of time (10 seconds, in the example) to start the program which is going to use the tunnel. If no connections are made within the time specified, will exit. X11 FORWARDING top If the ForwardX11 variable is set to yes (or see the description of the -X, -x, and -Y options above) and the user is using X11 (the DISPLAY environment variable is set), the connection to the X11 display is automatically forwarded to the remote side in such a way that any X11 programs started from the shell (or command) will go through the encrypted channel, and the connection to the real X server will be made from the local machine. The user should not manually set DISPLAY. Forwarding of X11 connections can be configured on the command line or in configuration files. The DISPLAY value set by will point to the server machine, but with a display number greater than zero. This is normal, and happens because creates a proxy X server on the server machine for forwarding the connections over the encrypted channel. will also automatically set up Xauthority data on the server machine. For this purpose, it will generate a random authorization cookie, store it in Xauthority on the server, and verify that any forwarded connections carry this cookie and replace it by the real cookie when the connection is opened. The real authentication cookie is never sent to the server machine (and no cookies are sent in the plain). If the ForwardAgent variable is set to yes (or see the description of the -A and -a options above) and the user is using an authentication agent, the connection to the agent is automatically forwarded to the remote side. VERIFYING HOST KEYS top When connecting to a server for the first time, a fingerprint of the server's public key is presented to the user (unless the option StrictHostKeyChecking has been disabled). Fingerprints can be determined using ssh-keygen(1): $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key If the fingerprint is already known, it can be matched and the key can be accepted or rejected. If only legacy (MD5) fingerprints for the server are available, the ssh-keygen(1) -E option may be used to downgrade the fingerprint algorithm to match. Because of the difficulty of comparing host keys just by looking at fingerprint strings, there is also support to compare host keys visually, using random art. By setting the VisualHostKey option to yes, a small ASCII graphic gets displayed on every login to a server, no matter if the session itself is interactive or not. By learning the pattern a known server produces, a user can easily find out that the host key has changed when a completely different pattern is displayed. Because these patterns are not unambiguous however, a pattern that looks similar to the pattern remembered only gives a good probability that the host key is the same, not guaranteed proof. To get a listing of the fingerprints along with their random art for all known hosts, the following command line can be used: $ ssh-keygen -lv -f ~/.ssh/known_hosts If the fingerprint is unknown, an alternative method of verification is available: SSH fingerprints verified by DNS. An additional resource record (RR), SSHFP, is added to a zonefile and the connecting client is able to match the fingerprint with that of the key presented. In this example, we are connecting a client to a server, host.example.com. The SSHFP resource records should first be added to the zonefile for host.example.com: $ ssh-keygen -r host.example.com. The output lines will have to be added to the zonefile. To check that the zone is answering fingerprint queries: $ dig -t SSHFP host.example.com Finally the client connects: $ ssh -o "VerifyHostKeyDNS ask" host.example.com [...] Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? See the VerifyHostKeyDNS option in ssh_config(5) for more information. SSH-BASED VIRTUAL PRIVATE NETWORKS top contains support for Virtual Private Network (VPN) tunnelling using the tun(4) network pseudo-device, allowing two networks to be joined securely. The sshd_config(5) configuration option PermitTunnel controls whether the server supports this, and at what level (layer 2 or 3 traffic). The following example would connect client network 10.0.50.0/24 with remote network 10.0.99.0/24 using a point-to-point connection from 10.1.1.1 to 10.1.1.2, provided that the SSH server running on the gateway to the remote network, at 192.168.1.15, allows it. On the client: # ssh -f -w 0:1 192.168.1.15 true # ifconfig tun0 10.1.1.1 10.1.1.2 netmask 255.255.255.252 # route add 10.0.99.0/24 10.1.1.2 On the server: # ifconfig tun1 10.1.1.2 10.1.1.1 netmask 255.255.255.252 # route add 10.0.50.0/24 10.1.1.1 Client access may be more finely tuned via the /root/.ssh/authorized_keys file (see below) and the PermitRootLogin server option. The following entry would permit connections on tun(4) device 1 from user jane and on tun device 2 from user john, if PermitRootLogin is set to forced-commands-only: tunnel="1",command="sh /etc/netstart tun1" ssh-rsa ... jane tunnel="2",command="sh /etc/netstart tun2" ssh-rsa ... john Since an SSH-based setup entails a fair amount of overhead, it may be more suited to temporary setups, such as for wireless VPNs. More permanent VPNs are better provided by tools such as ipsecctl(8) and isakmpd(8). ENVIRONMENT top will normally set the following environment variables: DISPLAY The DISPLAY variable indicates the location of the X11 server. It is automatically set by to point to a value of the form hostname:n, where hostname indicates the host where the shell runs, and n is an integer 1. uses this special value to forward X11 connections over the secure channel. The user should normally not set DISPLAY explicitly, as that will render the X11 connection insecure (and will require the user to manually copy any required authorization cookies). HOME Set to the path of the user's home directory. LOGNAME Synonym for USER; set for compatibility with systems that use this variable. MAIL Set to the path of the user's mailbox. PATH Set to the default PATH, as specified when compiling . SSH_ASKPASS If needs a passphrase, it will read the passphrase from the current terminal if it was run from a terminal. If does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS and open an X11 window to read the passphrase. This is particularly useful when calling from a .xsession or related script. (Note that on some machines it may be necessary to redirect the input from /dev/null to make this work.) SSH_ASKPASS_REQUIRE Allows further control over the use of an askpass program. If this variable is set to never then will never attempt to use one. If it is set to prefer, then will prefer to use the askpass program instead of the TTY when requesting passwords. Finally, if the variable is set to force, then the askpass program will be used for all passphrase input regardless of whether DISPLAY is set. SSH_AUTH_SOCK Identifies the path of a Unix-domain socket used to communicate with the agent. SSH_CONNECTION Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number. SSH_ORIGINAL_COMMAND This variable contains the original command line if a forced command is executed. It can be used to extract the original arguments. SSH_TTY This is set to the name of the tty (path to the device) associated with the current shell or command. If the current session has no tty, this variable is not set. SSH_TUNNEL Optionally set by sshd(8) to contain the interface names assigned if tunnel forwarding was requested by the client. SSH_USER_AUTH Optionally set by sshd(8), this variable may contain a pathname to a file that lists the authentication methods successfully used when the session was established, including any public keys that were used. TZ This variable is set to indicate the present time zone if it was set when the daemon was started (i.e. the daemon passes the value on to new connections). USER Set to the name of the user logging in. Additionally, reads ~/.ssh/environment, and adds lines of the format VARNAME=value to the environment if the file exists and users are allowed to change their environment. For more information, see the PermitUserEnvironment option in sshd_config(5). FILES top ~/.rhosts This file is used for host-based authentication (see above). On some machines this file may need to be world- readable if the user's home directory is on an NFS partition, because sshd(8) reads it as root. Additionally, this file must be owned by the user, and must not have write permissions for anyone else. The recommended permission for most machines is read/write for the user, and not accessible by others. ~/.shosts This file is used in exactly the same way as .rhosts, but allows host-based authentication without permitting login with rlogin/rsh. ~/.ssh/ This directory is the default location for all user- specific configuration and authentication information. There is no general requirement to keep the entire contents of this directory secret, but the recommended permissions are read/write/execute for the user, and not accessible by others. ~/.ssh/authorized_keys Lists the public keys (DSA, ECDSA, Ed25519, RSA) that can be used for logging in as this user. The format of this file is described in the sshd(8) manual page. This file is not highly sensitive, but the recommended permissions are read/write for the user, and not accessible by others. ~/.ssh/config This is the per-user configuration file. The file format and configuration options are described in ssh_config(5). Because of the potential for abuse, this file must have strict permissions: read/write for the user, and not writable by others. ~/.ssh/environment Contains additional definitions for environment variables; see ENVIRONMENT, above. ~/.ssh/id_dsa ~/.ssh/id_ecdsa ~/.ssh/id_ecdsa_sk ~/.ssh/id_ed25519 ~/.ssh/id_ed25519_sk ~/.ssh/id_rsa Contains the private key for authentication. These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute). will simply ignore a private key file if it is accessible by others. It is possible to specify a passphrase when generating the key which will be used to encrypt the sensitive part of this file using AES-128. ~/.ssh/id_dsa.pub ~/.ssh/id_ecdsa.pub ~/.ssh/id_ecdsa_sk.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_ed25519_sk.pub ~/.ssh/id_rsa.pub Contains the public key for authentication. These files are not sensitive and can (but need not) be readable by anyone. ~/.ssh/known_hosts Contains a list of host keys for all hosts the user has logged into that are not already in the systemwide list of known host keys. See sshd(8) for further details of the format of this file. ~/.ssh/rc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. /etc/hosts.equiv This file is for host-based authentication (see above). It should only be writable by root. /etc/shosts.equiv This file is used in exactly the same way as hosts.equiv, but allows host-based authentication without permitting login with rlogin/rsh. /etc/ssh/ssh_config Systemwide configuration file. The file format and configuration options are described in ssh_config(5). /etc/ssh/ssh_host_key /etc/ssh/ssh_host_dsa_key /etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_ed25519_key /etc/ssh/ssh_host_rsa_key These files contain the private parts of the host keys and are used for host-based authentication. /etc/ssh/ssh_known_hosts Systemwide list of known host keys. This file should be prepared by the system administrator to contain the public host keys of all machines in the organization. It should be world-readable. See sshd(8) for further details of the format of this file. /etc/ssh/sshrc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. EXIT STATUS top exits with the exit status of the remote command or with 255 if an error occurred. SEE ALSO top scp(1), sftp(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh-keyscan(1), tun(4), ssh_config(5), ssh-keysign(8), sshd(8) STANDARDS top S. Lehtinen and C. Lonvick, The Secure Shell (SSH) Protocol Assigned Numbers, RFC 4250, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Protocol Architecture, RFC 4251, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Authentication Protocol, RFC 4252, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Transport Layer Protocol, RFC 4253, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Connection Protocol, RFC 4254, January 2006. J. Schlyter and W. Griffin, Using DNS to Securely Publish Secure Shell (SSH) Key Fingerprints, RFC 4255, January 2006. F. Cusack and M. Forssen, Generic Message Exchange Authentication for the Secure Shell Protocol (SSH), RFC 4256, January 2006. J. Galbraith and P. Remaker, The Secure Shell (SSH) Session Channel Break Extension, RFC 4335, January 2006. M. Bellare, T. Kohno, and C. Namprempre, The Secure Shell (SSH) Transport Layer Encryption Modes, RFC 4344, January 2006. B. Harris, Improved Arcfour Modes for the Secure Shell (SSH) Transport Layer Protocol, RFC 4345, January 2006. M. Friedl, N. Provos, and W. Simpson, Diffie-Hellman Group Exchange for the Secure Shell (SSH) Transport Layer Protocol, RFC 4419, March 2006. J. Galbraith and R. Thayer, The Secure Shell (SSH) Public Key File Format, RFC 4716, November 2006. D. Stebila and J. Green, Elliptic Curve Algorithm Integration in the Secure Shell Transport Layer, RFC 5656, December 2009. A. Perrig and D. Song, Hash Visualization: a New Technique to improve Real-World Security, 1999, International Workshop on Cryptographic Techniques and E-Commerce (CrypTEC '99). AUTHORS top OpenSSH is a derivative of the original and free ssh 1.2.12 release by Tatu Ylonen. Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo de Raadt and Dug Song removed many bugs, re- added newer features and created OpenSSH. Markus Friedl contributed the support for SSH protocol versions 1.5 and 2.0. COLOPHON top This page is part of the openssh (Portable OpenSSH) project. Information about the project can be found at http://www.openssh.com/portable.html. If you have a bug report for this manual page, see http://www.openssh.com/report.html. This page was obtained from the tarball openssh-9.6p1.tar.gz fetched from http://ftp.eu.openbsd.org/pub/OpenBSD/OpenSSH/portable/ 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 October 11, 2023 SSH(1) Pages that refer to this page: stap-jupyter(1), systemd-stdio-bridge(1), tar(1), sd_bus_default(3), environment.d(5), proc(5), user@.service(5), pty(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: ssh into default vagrant host without running "vagrant ssh" by passing the configuration parameters vagrant uses for ssh Bash Command:<START>ssh vagrant@127.0.0.1 -p 2222 -o Compression=yes -o DSAAuthentication=yes -o LogLevel=FATAL -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o IdentitiesOnly=yes -i ~/.vagrant.d/less_insecure_private_key -o ForwardAgent=yes<END>
ssh into localhost on port 10022
ssh -p 10022 localhost
['ssh']
Output a Bash command to accomplish the following task. Task: ssh into localhost on port 10022 Bash Command:<START>ssh -p 10022 localhost<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # ssh\n\n> Secure Shell is a protocol used to securely log onto remote systems.\n> It can be used for logging or executing commands on a remote server.\n> More information: <https://man.openbsd.org/ssh>.\n\n- Connect to a remote server:\n\n`ssh {{username}}@{{remote_host}}`\n\n- Connect to a remote server with a specific identity (private key):\n\n`ssh -i {{path/to/key_file}} {{username}}@{{remote_host}}`\n\n- Connect to a remote server using a specific [p]ort:\n\n`ssh {{username}}@{{remote_host}} -p {{2222}}`\n\n- Run a command on a remote server with a [t]ty allocation allowing interaction with the remote command:\n\n`ssh {{username}}@{{remote_host}} -t {{command}} {{command_arguments}}`\n\n- SSH tunneling: [D]ynamic port forwarding (SOCKS proxy on `localhost:1080`):\n\n`ssh -D {{1080}} {{username}}@{{remote_host}}`\n\n- SSH tunneling: Forward a specific port (`localhost:9999` to `example.org:80`) along with disabling pseudo-[T]ty allocation and executio[N] of remote commands:\n\n`ssh -L {{9999}}:{{example.org}}:{{80}} -N -T {{username}}@{{remote_host}}`\n\n- SSH [J]umping: Connect through a jumphost to a remote server (Multiple jump hops may be specified separated by comma characters):\n\n`ssh -J {{username}}@{{jump_host}} {{username}}@{{remote_host}}`\n\n- Agent forwarding: Forward the authentication information to the remote machine (see `man ssh_config` for available options):\n\n`ssh -A {{username}}@{{remote_host}}`\n Task: ssh into localhost on port 10022 Bash Command:<START>ssh -p 10022 localhost<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: ssh(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ssh(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHENTICATION | ESCAPE CHARACTERS | TCP FORWARDING | X11 FORWARDING | VERIFYING HOST KEYS | SSH-BASED VIRTUAL PRIVATE NETWORKS | ENVIRONMENT | FILES | EXIT STATUS | SEE ALSO | STANDARDS | AUTHORS | COLOPHON SSH(1) General Commands Manual SSH(1) NAME top ssh OpenSSH remote login client SYNOPSIS top ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-J destination] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] destination [command [argument ...]] [-Q query_option] DESCRIPTION top (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections, arbitrary TCP ports and Unix-domain sockets can also be forwarded over the secure channel. connects and logs into the specified destination, which may be specified as either [user@]hostname or a URI of the form ssh://[user@]hostname[:port]. The user must prove their identity to the remote machine using one of several methods (see below). If a command is specified, it will be executed on the remote host instead of a login shell. A complete command line may be specified as command, or it may have additional arguments. If supplied, the arguments will be appended to the command, separated by spaces, before it is sent to the server to be executed. The options are as follows: -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Enables forwarding of connections from an authentication agent such as ssh-agent(1). This can also be specified on a per-host basis in a configuration file. Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent. A safer alternative may be to use a jump host (see -J). -a Disables forwarding of the authentication agent connection. -B bind_interface Bind to the address of bind_interface before attempting to connect to the destination host. This is only useful on systems with more than one address. -b bind_address Use bind_address on the local machine as the source address of the connection. Only useful on systems with more than one address. -C Requests compression of all data (including stdin, stdout, stderr, and data for forwarded X11, TCP and Unix-domain connections). The compression algorithm is the same used by gzip(1). Compression is desirable on modem lines and other slow connections, but will only slow down things on fast networks. The default value can be set on a host-by-host basis in the configuration files; see the Compression option in ssh_config(5). -c cipher_spec Selects the cipher specification for encrypting the session. cipher_spec is a comma-separated list of ciphers listed in order of preference. See the Ciphers keyword in ssh_config(5) for more information. -D [bind_address:]port Specifies a local dynamic application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. Currently the SOCKS4 and SOCKS5 protocols are supported, and will act as a SOCKS server. Only root can forward privileged ports. Dynamic port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -E log_file Append debug logs to log_file instead of standard error. -e escape_char Sets the escape character for sessions with a pty (default: ~). The escape character is only recognized at the beginning of a line. The escape character followed by a dot (.) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to none disables any escapes and makes the session fully transparent. -F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config. If set to none, no configuration files will be read. -f Requests to go to background just before command execution. This is useful if is going to ask for passwords or passphrases, but the user wants it in the background. This implies -n. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm. If the ExitOnForwardFailure configuration option is set to yes, then a client started with -f will wait for all remote port forwards to be successfully established before placing itself in the background. Refer to the description of ForkAfterAuthentication in ssh_config(5) for details. -G Causes to print its configuration after evaluating Host and Match blocks and exit. -g Allows remote hosts to connect to local forwarded ports. If used on a multiplexed connection, then this option must be specified on the master process. -I pkcs11 Specify the PKCS#11 shared library should use to communicate with a PKCS#11 token providing keys for user authentication. -i identity_file Selects a file from which the identity (private key) for public key authentication is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519, ~/.ssh/id_ed25519_sk and ~/.ssh/id_dsa. Identity files may also be specified on a per-host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in configuration files). If no certificates have been explicitly specified by the CertificateFile directive, will also try to load certificate information from the filename obtained by appending -cert.pub to identity filenames. -J destination Connect to the target host by first making an connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there. Multiple jump hops may be specified separated by comma characters. This is a shortcut to specify a ProxyJump configuration directive. Note that configuration directives supplied on the command-line generally apply to the destination host and not any specified jump hosts. Use ~/.ssh/config to specify configuration for jump hosts. -K Enables GSSAPI-based authentication and forwarding (delegation) of GSSAPI credentials to the server. -k Disables forwarding (delegation) of GSSAPI credentials to the server. -L [bind_address:]port:host:hostport -L [bind_address:]port:remote_socket -L local_socket:host:hostport -L local_socket:remote_socket Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. This works by allocating a socket to listen to either a TCP port on the local side, optionally bound to the specified bind_address, or to a Unix socket. Whenever a connection is made to the local port or socket, the connection is forwarded over the secure channel, and a connection is made to either host port hostport, or the Unix socket remote_socket, from the remote machine. Port forwardings can also be specified in the configuration file. Only the superuser can forward privileged ports. IPv6 addresses can be specified by enclosing the address in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -l login_name Specifies the user to log in as on the remote machine. This also may be specified on a per-host basis in the configuration file. -M Places the client into master mode for connection sharing. Multiple -M options places into master mode but with confirmation required using ssh-askpass(1) before each operation that changes the multiplexing state (e.g. opening a new session). Refer to the description of ControlMaster in ssh_config(5) for details. -m mac_spec A comma-separated list of MAC (message authentication code) algorithms, specified in order of preference. See the MACs keyword in ssh_config(5) for more information. -N Do not execute a remote command. This is useful for just forwarding ports. Refer to the description of SessionType in ssh_config(5) for details. -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The program will be put in the background. (This does not work if needs to ask for a password or passphrase; see also the -f option.) Refer to the description of StdinNull in ssh_config(5) for details. -O ctl_cmd Control an active connection multiplexing master process. When the -O option is specified, the ctl_cmd argument is interpreted and passed to the master process. Valid commands are: check (check that the master process is running), forward (request forwardings without command execution), cancel (cancel forwardings), exit (request the master to exit), and stop (request the master to stop accepting further multiplexing requests). -o option Can be used to give options in the format used in the configuration file. This is useful for specifying options for which there is no separate command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddKeysToAgent AddressFamily BatchMode BindAddress CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers ClearAllForwardings Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist DynamicForward EnableEscapeCommandline EscapeChar ExitOnForwardFailure FingerprintHash ForkAfterAuthentication ForwardAgent ForwardX11 ForwardX11Timeout ForwardX11Trusted GatewayPorts GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LocalCommand LocalForward LogLevel MACs Match NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PermitLocalCommand PermitRemoteOpen PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump ProxyUseFdpass PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RemoteCommand RemoteForward RequestTTY RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SessionType SetEnv StdinNull StreamLocalBindMask StreamLocalBindUnlink StrictHostKeyChecking TCPKeepAlive Tunnel TunnelDevice UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS VisualHostKey XAuthLocation -P tag Specify a tag name that may be used to select configuration in ssh_config(5). Refer to the Tag and Match keywords in ssh_config(5) for more information. -p port Port to connect to on the remote host. This can be specified on a per-host basis in the configuration file. -Q query_option Queries for the algorithms supported by one of the following features: cipher (supported symmetric ciphers), cipher-auth (supported symmetric ciphers that support authenticated encryption), help (supported query terms for use with the -Q flag), mac (supported message integrity codes), kex (key exchange algorithms), key (key types), key-ca-sign (valid CA signature algorithms for certificates), key-cert (certificate key types), key-plain (non-certificate key types), key-sig (all key types and signature algorithms), protocol-version (supported SSH protocol versions), and sig (supported signature algorithms). Alternatively, any keyword from ssh_config(5) or sshd_config(5) that takes an algorithm list may be used as an alias for the corresponding query_option. -q Quiet mode. Causes most warning and diagnostic messages to be suppressed. -R [bind_address:]port:host:hostport -R [bind_address:]port:local_socket -R remote_socket:host:hostport -R remote_socket:local_socket -R [bind_address:]port Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side. This works by allocating a socket to listen to either a TCP port or to a Unix socket on the remote side. Whenever a connection is made to this port or Unix socket, the connection is forwarded over the secure channel, and a connection is made from the local machine to either an explicit destination specified by host port hostport, or local_socket, or, if no explicit destination was specified, will act as a SOCKS 4/5 proxy and forward connections to the destinations requested by the remote SOCKS client. Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square brackets. By default, TCP listening sockets on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address *, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)). If the port argument is 0, the listen port will be dynamically allocated on the server and reported to the client at run time. When used together with -O forward, the allocated port will be printed to the standard output. -S ctl_path Specifies the location of a control socket for connection sharing, or the string none to disable connection sharing. Refer to the description of ControlPath and ControlMaster in ssh_config(5) for details. -s May be used to request invocation of a subsystem on the remote system. Subsystems facilitate the use of SSH as a secure transport for other applications (e.g. sftp(1)). The subsystem is specified as the remote command. Refer to the description of SessionType in ssh_config(5) for details. -T Disable pseudo-terminal allocation. -t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if has no local tty. -V Display the version number and exit. -v Verbose mode. Causes to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3. -W host:port Requests that standard input and output on the client be forwarded to host on port over the secure channel. Implies -N, -T, ExitOnForwardFailure and ClearAllForwardings, though these can be overridden in the configuration file or using -o command line options. -w local_tun[:remote_tun] Requests tunnel device forwarding with the specified tun(4) devices between the client (local_tun) and the server (remote_tun). The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. See also the Tunnel and TunnelDevice directives in ssh_config(5). If the Tunnel directive is unset, it will be set to the default tunnel mode, which is point-to-point. If a different Tunnel forwarding mode it desired, then it should be specified before -w. -X Enables X11 forwarding. This can also be specified on a per-host basis in a configuration file. X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring. For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. Refer to the -Y option and the ForwardX11Trusted directive in ssh_config(5) for more information. -x Disables X11 forwarding. -Y Enables trusted X11 forwarding. Trusted X11 forwardings are not subjected to the X11 SECURITY extension controls. -y Send log information using the syslog(3) system module. By default this information is sent to stderr. may additionally obtain configuration data from a per-user configuration file and a system-wide configuration file. The file format and configuration options are described in ssh_config(5). AUTHENTICATION top The OpenSSH SSH client supports SSH protocol 2. The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, keyboard-interactive authentication, and password authentication. Authentication methods are tried in the order specified above, though PreferredAuthentications can be used to change the default order. Host-based authentication works as follows: If the machine the user logs in from is listed in /etc/hosts.equiv or /etc/shosts.equiv on the remote machine, the user is non-root and the user names are the same on both sides, or if the files ~/.rhosts or ~/.shosts exist in the user's home directory on the remote machine and contain a line containing the name of the client machine and the name of the user on that machine, the user is considered for login. Additionally, the server must be able to verify the client's host key (see the description of /etc/ssh/ssh_known_hosts and ~/.ssh/known_hosts, below) for login to be permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing, and routing spoofing. [Note to the administrator: /etc/hosts.equiv, ~/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.] Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. implements public key authentication protocol automatically, using one of the DSA, ECDSA, Ed25519 or RSA algorithms. The HISTORY section of ssl(8) contains a brief discussion of the DSA and RSA algorithms. The file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. When the user logs in, the program tells the server which key pair it would like to use for authentication. The client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account. The server may inform the client of errors that prevented public key authentication from succeeding after authentication completes using a different method. These may be viewed by increasing the LogLevel to DEBUG or higher (e.g. by using the -v flag). The user creates their key pair by running ssh-keygen(1). This stores the private key in ~/.ssh/id_dsa (DSA), ~/.ssh/id_ecdsa (ECDSA), ~/.ssh/id_ecdsa_sk (authenticator-hosted ECDSA), ~/.ssh/id_ed25519 (Ed25519), ~/.ssh/id_ed25519_sk (authenticator- hosted Ed25519), or ~/.ssh/id_rsa (RSA) and stores the public key in ~/.ssh/id_dsa.pub (DSA), ~/.ssh/id_ecdsa.pub (ECDSA), ~/.ssh/id_ecdsa_sk.pub (authenticator-hosted ECDSA), ~/.ssh/id_ed25519.pub (Ed25519), ~/.ssh/id_ed25519_sk.pub (authenticator-hosted Ed25519), or ~/.ssh/id_rsa.pub (RSA) in the user's home directory. The user should then copy the public key to ~/.ssh/authorized_keys in their home directory on the remote machine. The authorized_keys file corresponds to the conventional ~/.rhosts file, and has one key per line, though the lines can be very long. After this, the user can log in without giving the password. A variation on public key authentication is available in the form of certificate authentication: instead of a set of public/private keys, signed certificates are used. This has the advantage that a single trusted certification authority can be used in place of many public/private keys. See the CERTIFICATES section of ssh-keygen(1) for more information. The most convenient way to use public key or certificate authentication may be with an authentication agent. See ssh-agent(1) and (optionally) the AddKeysToAgent directive in ssh_config(5) for more information. Keyboard-interactive authentication works as follows: The server sends an arbitrary "challenge" text and prompts for a response, possibly multiple times. Examples of keyboard-interactive authentication include BSD Authentication (see login.conf(5)) and PAM (some non-OpenBSD systems). Finally, if other authentication methods fail, prompts the user for a password. The password is sent to the remote host for checking; however, since all communications are encrypted, the password cannot be seen by someone listening on the network. automatically maintains and checks a database containing identification for all hosts it has ever been used with. Host keys are stored in ~/.ssh/known_hosts in the user's home directory. Additionally, the file /etc/ssh/ssh_known_hosts is automatically checked for known hosts. Any new hosts are automatically added to the user's file. If a host's identification ever changes, warns about this and disables password authentication to prevent server spoofing or man-in-the- middle attacks, which could otherwise be used to circumvent the encryption. The StrictHostKeyChecking option can be used to control logins to machines whose host key is not known or has changed. When the user's identity has been accepted by the server, the server either executes the given command in a non-interactive session or, if no command has been specified, logs into the machine and gives the user a normal shell as an interactive session. All communication with the remote command or shell will be automatically encrypted. If an interactive session is requested, by default will only request a pseudo-terminal (pty) for interactive sessions when the client has one. The flags -T and -t can be used to override this behaviour. If a pseudo-terminal has been allocated, the user may use the escape characters noted below. If no pseudo-terminal has been allocated, the session is transparent and can be used to reliably transfer binary data. On most systems, setting the escape character to none will also make the session transparent even if a tty is used. The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed. ESCAPE CHARACTERS top When a pseudo-terminal has been requested, supports a number of functions through the use of an escape character. A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option. The supported escapes (assuming the default ~) are: ~. Disconnect. ~^Z Background . ~# List forwarded connections. ~& Background at logout when waiting for forwarded connection / X11 sessions to terminate. ~? Display a list of escape characters. ~B Send a BREAK to the remote system (only useful if the peer supports it). ~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing port-forwardings with -KL[bind_address:]port for local, -KR[bind_address:]port for remote and -KD[bind_address:]port for dynamic port-forwardings. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is available, using the -h option. ~R Request rekeying of the connection (only useful if the peer supports it). ~V Decrease the verbosity (LogLevel) when errors are being written to stderr. ~v Increase the verbosity (LogLevel) when errors are being written to stderr. TCP FORWARDING top Forwarding of arbitrary TCP connections over a secure channel can be specified either on the command line or in a configuration file. One possible application of TCP forwarding is a secure connection to a mail server; another is going through firewalls. In the example below, we look at encrypting communication for an IRC client, even though the IRC server it connects to does not directly support encrypted communication. This works as follows: the user connects to the remote host using , specifying the ports to be used to forward the connection. After that it is possible to start the program locally, and will encrypt and forward the connection to the remote server. The following example tunnels an IRC session from the client to an IRC server at server.example.com, joining channel #users, nickname pinky, using the standard IRC port, 6667: $ ssh -f -L 6667:localhost:6667 server.example.com sleep 10 $ irc -c '#users' pinky IRC/127.0.0.1 The -f option backgrounds and the remote command sleep 10 is specified to allow an amount of time (10 seconds, in the example) to start the program which is going to use the tunnel. If no connections are made within the time specified, will exit. X11 FORWARDING top If the ForwardX11 variable is set to yes (or see the description of the -X, -x, and -Y options above) and the user is using X11 (the DISPLAY environment variable is set), the connection to the X11 display is automatically forwarded to the remote side in such a way that any X11 programs started from the shell (or command) will go through the encrypted channel, and the connection to the real X server will be made from the local machine. The user should not manually set DISPLAY. Forwarding of X11 connections can be configured on the command line or in configuration files. The DISPLAY value set by will point to the server machine, but with a display number greater than zero. This is normal, and happens because creates a proxy X server on the server machine for forwarding the connections over the encrypted channel. will also automatically set up Xauthority data on the server machine. For this purpose, it will generate a random authorization cookie, store it in Xauthority on the server, and verify that any forwarded connections carry this cookie and replace it by the real cookie when the connection is opened. The real authentication cookie is never sent to the server machine (and no cookies are sent in the plain). If the ForwardAgent variable is set to yes (or see the description of the -A and -a options above) and the user is using an authentication agent, the connection to the agent is automatically forwarded to the remote side. VERIFYING HOST KEYS top When connecting to a server for the first time, a fingerprint of the server's public key is presented to the user (unless the option StrictHostKeyChecking has been disabled). Fingerprints can be determined using ssh-keygen(1): $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key If the fingerprint is already known, it can be matched and the key can be accepted or rejected. If only legacy (MD5) fingerprints for the server are available, the ssh-keygen(1) -E option may be used to downgrade the fingerprint algorithm to match. Because of the difficulty of comparing host keys just by looking at fingerprint strings, there is also support to compare host keys visually, using random art. By setting the VisualHostKey option to yes, a small ASCII graphic gets displayed on every login to a server, no matter if the session itself is interactive or not. By learning the pattern a known server produces, a user can easily find out that the host key has changed when a completely different pattern is displayed. Because these patterns are not unambiguous however, a pattern that looks similar to the pattern remembered only gives a good probability that the host key is the same, not guaranteed proof. To get a listing of the fingerprints along with their random art for all known hosts, the following command line can be used: $ ssh-keygen -lv -f ~/.ssh/known_hosts If the fingerprint is unknown, an alternative method of verification is available: SSH fingerprints verified by DNS. An additional resource record (RR), SSHFP, is added to a zonefile and the connecting client is able to match the fingerprint with that of the key presented. In this example, we are connecting a client to a server, host.example.com. The SSHFP resource records should first be added to the zonefile for host.example.com: $ ssh-keygen -r host.example.com. The output lines will have to be added to the zonefile. To check that the zone is answering fingerprint queries: $ dig -t SSHFP host.example.com Finally the client connects: $ ssh -o "VerifyHostKeyDNS ask" host.example.com [...] Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? See the VerifyHostKeyDNS option in ssh_config(5) for more information. SSH-BASED VIRTUAL PRIVATE NETWORKS top contains support for Virtual Private Network (VPN) tunnelling using the tun(4) network pseudo-device, allowing two networks to be joined securely. The sshd_config(5) configuration option PermitTunnel controls whether the server supports this, and at what level (layer 2 or 3 traffic). The following example would connect client network 10.0.50.0/24 with remote network 10.0.99.0/24 using a point-to-point connection from 10.1.1.1 to 10.1.1.2, provided that the SSH server running on the gateway to the remote network, at 192.168.1.15, allows it. On the client: # ssh -f -w 0:1 192.168.1.15 true # ifconfig tun0 10.1.1.1 10.1.1.2 netmask 255.255.255.252 # route add 10.0.99.0/24 10.1.1.2 On the server: # ifconfig tun1 10.1.1.2 10.1.1.1 netmask 255.255.255.252 # route add 10.0.50.0/24 10.1.1.1 Client access may be more finely tuned via the /root/.ssh/authorized_keys file (see below) and the PermitRootLogin server option. The following entry would permit connections on tun(4) device 1 from user jane and on tun device 2 from user john, if PermitRootLogin is set to forced-commands-only: tunnel="1",command="sh /etc/netstart tun1" ssh-rsa ... jane tunnel="2",command="sh /etc/netstart tun2" ssh-rsa ... john Since an SSH-based setup entails a fair amount of overhead, it may be more suited to temporary setups, such as for wireless VPNs. More permanent VPNs are better provided by tools such as ipsecctl(8) and isakmpd(8). ENVIRONMENT top will normally set the following environment variables: DISPLAY The DISPLAY variable indicates the location of the X11 server. It is automatically set by to point to a value of the form hostname:n, where hostname indicates the host where the shell runs, and n is an integer 1. uses this special value to forward X11 connections over the secure channel. The user should normally not set DISPLAY explicitly, as that will render the X11 connection insecure (and will require the user to manually copy any required authorization cookies). HOME Set to the path of the user's home directory. LOGNAME Synonym for USER; set for compatibility with systems that use this variable. MAIL Set to the path of the user's mailbox. PATH Set to the default PATH, as specified when compiling . SSH_ASKPASS If needs a passphrase, it will read the passphrase from the current terminal if it was run from a terminal. If does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS and open an X11 window to read the passphrase. This is particularly useful when calling from a .xsession or related script. (Note that on some machines it may be necessary to redirect the input from /dev/null to make this work.) SSH_ASKPASS_REQUIRE Allows further control over the use of an askpass program. If this variable is set to never then will never attempt to use one. If it is set to prefer, then will prefer to use the askpass program instead of the TTY when requesting passwords. Finally, if the variable is set to force, then the askpass program will be used for all passphrase input regardless of whether DISPLAY is set. SSH_AUTH_SOCK Identifies the path of a Unix-domain socket used to communicate with the agent. SSH_CONNECTION Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number. SSH_ORIGINAL_COMMAND This variable contains the original command line if a forced command is executed. It can be used to extract the original arguments. SSH_TTY This is set to the name of the tty (path to the device) associated with the current shell or command. If the current session has no tty, this variable is not set. SSH_TUNNEL Optionally set by sshd(8) to contain the interface names assigned if tunnel forwarding was requested by the client. SSH_USER_AUTH Optionally set by sshd(8), this variable may contain a pathname to a file that lists the authentication methods successfully used when the session was established, including any public keys that were used. TZ This variable is set to indicate the present time zone if it was set when the daemon was started (i.e. the daemon passes the value on to new connections). USER Set to the name of the user logging in. Additionally, reads ~/.ssh/environment, and adds lines of the format VARNAME=value to the environment if the file exists and users are allowed to change their environment. For more information, see the PermitUserEnvironment option in sshd_config(5). FILES top ~/.rhosts This file is used for host-based authentication (see above). On some machines this file may need to be world- readable if the user's home directory is on an NFS partition, because sshd(8) reads it as root. Additionally, this file must be owned by the user, and must not have write permissions for anyone else. The recommended permission for most machines is read/write for the user, and not accessible by others. ~/.shosts This file is used in exactly the same way as .rhosts, but allows host-based authentication without permitting login with rlogin/rsh. ~/.ssh/ This directory is the default location for all user- specific configuration and authentication information. There is no general requirement to keep the entire contents of this directory secret, but the recommended permissions are read/write/execute for the user, and not accessible by others. ~/.ssh/authorized_keys Lists the public keys (DSA, ECDSA, Ed25519, RSA) that can be used for logging in as this user. The format of this file is described in the sshd(8) manual page. This file is not highly sensitive, but the recommended permissions are read/write for the user, and not accessible by others. ~/.ssh/config This is the per-user configuration file. The file format and configuration options are described in ssh_config(5). Because of the potential for abuse, this file must have strict permissions: read/write for the user, and not writable by others. ~/.ssh/environment Contains additional definitions for environment variables; see ENVIRONMENT, above. ~/.ssh/id_dsa ~/.ssh/id_ecdsa ~/.ssh/id_ecdsa_sk ~/.ssh/id_ed25519 ~/.ssh/id_ed25519_sk ~/.ssh/id_rsa Contains the private key for authentication. These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute). will simply ignore a private key file if it is accessible by others. It is possible to specify a passphrase when generating the key which will be used to encrypt the sensitive part of this file using AES-128. ~/.ssh/id_dsa.pub ~/.ssh/id_ecdsa.pub ~/.ssh/id_ecdsa_sk.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_ed25519_sk.pub ~/.ssh/id_rsa.pub Contains the public key for authentication. These files are not sensitive and can (but need not) be readable by anyone. ~/.ssh/known_hosts Contains a list of host keys for all hosts the user has logged into that are not already in the systemwide list of known host keys. See sshd(8) for further details of the format of this file. ~/.ssh/rc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. /etc/hosts.equiv This file is for host-based authentication (see above). It should only be writable by root. /etc/shosts.equiv This file is used in exactly the same way as hosts.equiv, but allows host-based authentication without permitting login with rlogin/rsh. /etc/ssh/ssh_config Systemwide configuration file. The file format and configuration options are described in ssh_config(5). /etc/ssh/ssh_host_key /etc/ssh/ssh_host_dsa_key /etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_ed25519_key /etc/ssh/ssh_host_rsa_key These files contain the private parts of the host keys and are used for host-based authentication. /etc/ssh/ssh_known_hosts Systemwide list of known host keys. This file should be prepared by the system administrator to contain the public host keys of all machines in the organization. It should be world-readable. See sshd(8) for further details of the format of this file. /etc/ssh/sshrc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. EXIT STATUS top exits with the exit status of the remote command or with 255 if an error occurred. SEE ALSO top scp(1), sftp(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh-keyscan(1), tun(4), ssh_config(5), ssh-keysign(8), sshd(8) STANDARDS top S. Lehtinen and C. Lonvick, The Secure Shell (SSH) Protocol Assigned Numbers, RFC 4250, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Protocol Architecture, RFC 4251, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Authentication Protocol, RFC 4252, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Transport Layer Protocol, RFC 4253, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Connection Protocol, RFC 4254, January 2006. J. Schlyter and W. Griffin, Using DNS to Securely Publish Secure Shell (SSH) Key Fingerprints, RFC 4255, January 2006. F. Cusack and M. Forssen, Generic Message Exchange Authentication for the Secure Shell Protocol (SSH), RFC 4256, January 2006. J. Galbraith and P. Remaker, The Secure Shell (SSH) Session Channel Break Extension, RFC 4335, January 2006. M. Bellare, T. Kohno, and C. Namprempre, The Secure Shell (SSH) Transport Layer Encryption Modes, RFC 4344, January 2006. B. Harris, Improved Arcfour Modes for the Secure Shell (SSH) Transport Layer Protocol, RFC 4345, January 2006. M. Friedl, N. Provos, and W. Simpson, Diffie-Hellman Group Exchange for the Secure Shell (SSH) Transport Layer Protocol, RFC 4419, March 2006. J. Galbraith and R. Thayer, The Secure Shell (SSH) Public Key File Format, RFC 4716, November 2006. D. Stebila and J. Green, Elliptic Curve Algorithm Integration in the Secure Shell Transport Layer, RFC 5656, December 2009. A. Perrig and D. Song, Hash Visualization: a New Technique to improve Real-World Security, 1999, International Workshop on Cryptographic Techniques and E-Commerce (CrypTEC '99). AUTHORS top OpenSSH is a derivative of the original and free ssh 1.2.12 release by Tatu Ylonen. Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo de Raadt and Dug Song removed many bugs, re- added newer features and created OpenSSH. Markus Friedl contributed the support for SSH protocol versions 1.5 and 2.0. COLOPHON top This page is part of the openssh (Portable OpenSSH) project. Information about the project can be found at http://www.openssh.com/portable.html. If you have a bug report for this manual page, see http://www.openssh.com/report.html. This page was obtained from the tarball openssh-9.6p1.tar.gz fetched from http://ftp.eu.openbsd.org/pub/OpenBSD/OpenSSH/portable/ 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 October 11, 2023 SSH(1) Pages that refer to this page: stap-jupyter(1), systemd-stdio-bridge(1), tar(1), sd_bus_default(3), environment.d(5), proc(5), user@.service(5), pty(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: ssh into localhost on port 10022 Bash Command:<START>ssh -p 10022 localhost<END>
ssh into localhost on port 4444
ssh -p 4444 localhost
['ssh']
Output a Bash command to accomplish the following task. Task: ssh into localhost on port 4444 Bash Command:<START>ssh -p 4444 localhost<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # ssh\n\n> Secure Shell is a protocol used to securely log onto remote systems.\n> It can be used for logging or executing commands on a remote server.\n> More information: <https://man.openbsd.org/ssh>.\n\n- Connect to a remote server:\n\n`ssh {{username}}@{{remote_host}}`\n\n- Connect to a remote server with a specific identity (private key):\n\n`ssh -i {{path/to/key_file}} {{username}}@{{remote_host}}`\n\n- Connect to a remote server using a specific [p]ort:\n\n`ssh {{username}}@{{remote_host}} -p {{2222}}`\n\n- Run a command on a remote server with a [t]ty allocation allowing interaction with the remote command:\n\n`ssh {{username}}@{{remote_host}} -t {{command}} {{command_arguments}}`\n\n- SSH tunneling: [D]ynamic port forwarding (SOCKS proxy on `localhost:1080`):\n\n`ssh -D {{1080}} {{username}}@{{remote_host}}`\n\n- SSH tunneling: Forward a specific port (`localhost:9999` to `example.org:80`) along with disabling pseudo-[T]ty allocation and executio[N] of remote commands:\n\n`ssh -L {{9999}}:{{example.org}}:{{80}} -N -T {{username}}@{{remote_host}}`\n\n- SSH [J]umping: Connect through a jumphost to a remote server (Multiple jump hops may be specified separated by comma characters):\n\n`ssh -J {{username}}@{{jump_host}} {{username}}@{{remote_host}}`\n\n- Agent forwarding: Forward the authentication information to the remote machine (see `man ssh_config` for available options):\n\n`ssh -A {{username}}@{{remote_host}}`\n Task: ssh into localhost on port 4444 Bash Command:<START>ssh -p 4444 localhost<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: ssh(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ssh(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHENTICATION | ESCAPE CHARACTERS | TCP FORWARDING | X11 FORWARDING | VERIFYING HOST KEYS | SSH-BASED VIRTUAL PRIVATE NETWORKS | ENVIRONMENT | FILES | EXIT STATUS | SEE ALSO | STANDARDS | AUTHORS | COLOPHON SSH(1) General Commands Manual SSH(1) NAME top ssh OpenSSH remote login client SYNOPSIS top ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-J destination] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-P tag] [-p port] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] destination [command [argument ...]] [-Q query_option] DESCRIPTION top (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections, arbitrary TCP ports and Unix-domain sockets can also be forwarded over the secure channel. connects and logs into the specified destination, which may be specified as either [user@]hostname or a URI of the form ssh://[user@]hostname[:port]. The user must prove their identity to the remote machine using one of several methods (see below). If a command is specified, it will be executed on the remote host instead of a login shell. A complete command line may be specified as command, or it may have additional arguments. If supplied, the arguments will be appended to the command, separated by spaces, before it is sent to the server to be executed. The options are as follows: -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Enables forwarding of connections from an authentication agent such as ssh-agent(1). This can also be specified on a per-host basis in a configuration file. Agent forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the agent's Unix-domain socket) can access the local agent through the forwarded connection. An attacker cannot obtain key material from the agent, however they can perform operations on the keys that enable them to authenticate using the identities loaded into the agent. A safer alternative may be to use a jump host (see -J). -a Disables forwarding of the authentication agent connection. -B bind_interface Bind to the address of bind_interface before attempting to connect to the destination host. This is only useful on systems with more than one address. -b bind_address Use bind_address on the local machine as the source address of the connection. Only useful on systems with more than one address. -C Requests compression of all data (including stdin, stdout, stderr, and data for forwarded X11, TCP and Unix-domain connections). The compression algorithm is the same used by gzip(1). Compression is desirable on modem lines and other slow connections, but will only slow down things on fast networks. The default value can be set on a host-by-host basis in the configuration files; see the Compression option in ssh_config(5). -c cipher_spec Selects the cipher specification for encrypting the session. cipher_spec is a comma-separated list of ciphers listed in order of preference. See the Ciphers keyword in ssh_config(5) for more information. -D [bind_address:]port Specifies a local dynamic application-level port forwarding. This works by allocating a socket to listen to port on the local side, optionally bound to the specified bind_address. Whenever a connection is made to this port, the connection is forwarded over the secure channel, and the application protocol is then used to determine where to connect to from the remote machine. Currently the SOCKS4 and SOCKS5 protocols are supported, and will act as a SOCKS server. Only root can forward privileged ports. Dynamic port forwardings can also be specified in the configuration file. IPv6 addresses can be specified by enclosing the address in square brackets. Only the superuser can forward privileged ports. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -E log_file Append debug logs to log_file instead of standard error. -e escape_char Sets the escape character for sessions with a pty (default: ~). The escape character is only recognized at the beginning of a line. The escape character followed by a dot (.) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to none disables any escapes and makes the session fully transparent. -F configfile Specifies an alternative per-user configuration file. If a configuration file is given on the command line, the system-wide configuration file (/etc/ssh/ssh_config) will be ignored. The default for the per-user configuration file is ~/.ssh/config. If set to none, no configuration files will be read. -f Requests to go to background just before command execution. This is useful if is going to ask for passwords or passphrases, but the user wants it in the background. This implies -n. The recommended way to start X11 programs at a remote site is with something like ssh -f host xterm. If the ExitOnForwardFailure configuration option is set to yes, then a client started with -f will wait for all remote port forwards to be successfully established before placing itself in the background. Refer to the description of ForkAfterAuthentication in ssh_config(5) for details. -G Causes to print its configuration after evaluating Host and Match blocks and exit. -g Allows remote hosts to connect to local forwarded ports. If used on a multiplexed connection, then this option must be specified on the master process. -I pkcs11 Specify the PKCS#11 shared library should use to communicate with a PKCS#11 token providing keys for user authentication. -i identity_file Selects a file from which the identity (private key) for public key authentication is read. You can also specify a public key file to use the corresponding private key that is loaded in ssh-agent(1) when the private key file is not present locally. The default is ~/.ssh/id_rsa, ~/.ssh/id_ecdsa, ~/.ssh/id_ecdsa_sk, ~/.ssh/id_ed25519, ~/.ssh/id_ed25519_sk and ~/.ssh/id_dsa. Identity files may also be specified on a per-host basis in the configuration file. It is possible to have multiple -i options (and multiple identities specified in configuration files). If no certificates have been explicitly specified by the CertificateFile directive, will also try to load certificate information from the filename obtained by appending -cert.pub to identity filenames. -J destination Connect to the target host by first making an connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there. Multiple jump hops may be specified separated by comma characters. This is a shortcut to specify a ProxyJump configuration directive. Note that configuration directives supplied on the command-line generally apply to the destination host and not any specified jump hosts. Use ~/.ssh/config to specify configuration for jump hosts. -K Enables GSSAPI-based authentication and forwarding (delegation) of GSSAPI credentials to the server. -k Disables forwarding (delegation) of GSSAPI credentials to the server. -L [bind_address:]port:host:hostport -L [bind_address:]port:remote_socket -L local_socket:host:hostport -L local_socket:remote_socket Specifies that connections to the given TCP port or Unix socket on the local (client) host are to be forwarded to the given host and port, or Unix socket, on the remote side. This works by allocating a socket to listen to either a TCP port on the local side, optionally bound to the specified bind_address, or to a Unix socket. Whenever a connection is made to the local port or socket, the connection is forwarded over the secure channel, and a connection is made to either host port hostport, or the Unix socket remote_socket, from the remote machine. Port forwardings can also be specified in the configuration file. Only the superuser can forward privileged ports. IPv6 addresses can be specified by enclosing the address in square brackets. By default, the local port is bound in accordance with the GatewayPorts setting. However, an explicit bind_address may be used to bind the connection to a specific address. The bind_address of localhost indicates that the listening port be bound for local use only, while an empty address or * indicates that the port should be available from all interfaces. -l login_name Specifies the user to log in as on the remote machine. This also may be specified on a per-host basis in the configuration file. -M Places the client into master mode for connection sharing. Multiple -M options places into master mode but with confirmation required using ssh-askpass(1) before each operation that changes the multiplexing state (e.g. opening a new session). Refer to the description of ControlMaster in ssh_config(5) for details. -m mac_spec A comma-separated list of MAC (message authentication code) algorithms, specified in order of preference. See the MACs keyword in ssh_config(5) for more information. -N Do not execute a remote command. This is useful for just forwarding ports. Refer to the description of SessionType in ssh_config(5) for details. -n Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The program will be put in the background. (This does not work if needs to ask for a password or passphrase; see also the -f option.) Refer to the description of StdinNull in ssh_config(5) for details. -O ctl_cmd Control an active connection multiplexing master process. When the -O option is specified, the ctl_cmd argument is interpreted and passed to the master process. Valid commands are: check (check that the master process is running), forward (request forwardings without command execution), cancel (cancel forwardings), exit (request the master to exit), and stop (request the master to stop accepting further multiplexing requests). -o option Can be used to give options in the format used in the configuration file. This is useful for specifying options for which there is no separate command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddKeysToAgent AddressFamily BatchMode BindAddress CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers ClearAllForwardings Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist DynamicForward EnableEscapeCommandline EscapeChar ExitOnForwardFailure FingerprintHash ForkAfterAuthentication ForwardAgent ForwardX11 ForwardX11Timeout ForwardX11Trusted GatewayPorts GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LocalCommand LocalForward LogLevel MACs Match NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PermitLocalCommand PermitRemoteOpen PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump ProxyUseFdpass PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RemoteCommand RemoteForward RequestTTY RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SessionType SetEnv StdinNull StreamLocalBindMask StreamLocalBindUnlink StrictHostKeyChecking TCPKeepAlive Tunnel TunnelDevice UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS VisualHostKey XAuthLocation -P tag Specify a tag name that may be used to select configuration in ssh_config(5). Refer to the Tag and Match keywords in ssh_config(5) for more information. -p port Port to connect to on the remote host. This can be specified on a per-host basis in the configuration file. -Q query_option Queries for the algorithms supported by one of the following features: cipher (supported symmetric ciphers), cipher-auth (supported symmetric ciphers that support authenticated encryption), help (supported query terms for use with the -Q flag), mac (supported message integrity codes), kex (key exchange algorithms), key (key types), key-ca-sign (valid CA signature algorithms for certificates), key-cert (certificate key types), key-plain (non-certificate key types), key-sig (all key types and signature algorithms), protocol-version (supported SSH protocol versions), and sig (supported signature algorithms). Alternatively, any keyword from ssh_config(5) or sshd_config(5) that takes an algorithm list may be used as an alias for the corresponding query_option. -q Quiet mode. Causes most warning and diagnostic messages to be suppressed. -R [bind_address:]port:host:hostport -R [bind_address:]port:local_socket -R remote_socket:host:hostport -R remote_socket:local_socket -R [bind_address:]port Specifies that connections to the given TCP port or Unix socket on the remote (server) host are to be forwarded to the local side. This works by allocating a socket to listen to either a TCP port or to a Unix socket on the remote side. Whenever a connection is made to this port or Unix socket, the connection is forwarded over the secure channel, and a connection is made from the local machine to either an explicit destination specified by host port hostport, or local_socket, or, if no explicit destination was specified, will act as a SOCKS 4/5 proxy and forward connections to the destinations requested by the remote SOCKS client. Port forwardings can also be specified in the configuration file. Privileged ports can be forwarded only when logging in as root on the remote machine. IPv6 addresses can be specified by enclosing the address in square brackets. By default, TCP listening sockets on the server will be bound to the loopback interface only. This may be overridden by specifying a bind_address. An empty bind_address, or the address *, indicates that the remote socket should listen on all interfaces. Specifying a remote bind_address will only succeed if the server's GatewayPorts option is enabled (see sshd_config(5)). If the port argument is 0, the listen port will be dynamically allocated on the server and reported to the client at run time. When used together with -O forward, the allocated port will be printed to the standard output. -S ctl_path Specifies the location of a control socket for connection sharing, or the string none to disable connection sharing. Refer to the description of ControlPath and ControlMaster in ssh_config(5) for details. -s May be used to request invocation of a subsystem on the remote system. Subsystems facilitate the use of SSH as a secure transport for other applications (e.g. sftp(1)). The subsystem is specified as the remote command. Refer to the description of SessionType in ssh_config(5) for details. -T Disable pseudo-terminal allocation. -t Force pseudo-terminal allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if has no local tty. -V Display the version number and exit. -v Verbose mode. Causes to print debugging messages about its progress. This is helpful in debugging connection, authentication, and configuration problems. Multiple -v options increase the verbosity. The maximum is 3. -W host:port Requests that standard input and output on the client be forwarded to host on port over the secure channel. Implies -N, -T, ExitOnForwardFailure and ClearAllForwardings, though these can be overridden in the configuration file or using -o command line options. -w local_tun[:remote_tun] Requests tunnel device forwarding with the specified tun(4) devices between the client (local_tun) and the server (remote_tun). The devices may be specified by numerical ID or the keyword any, which uses the next available tunnel device. If remote_tun is not specified, it defaults to any. See also the Tunnel and TunnelDevice directives in ssh_config(5). If the Tunnel directive is unset, it will be set to the default tunnel mode, which is point-to-point. If a different Tunnel forwarding mode it desired, then it should be specified before -w. -X Enables X11 forwarding. This can also be specified on a per-host basis in a configuration file. X11 forwarding should be enabled with caution. Users with the ability to bypass file permissions on the remote host (for the user's X authorization database) can access the local X11 display through the forwarded connection. An attacker may then be able to perform activities such as keystroke monitoring. For this reason, X11 forwarding is subjected to X11 SECURITY extension restrictions by default. Refer to the -Y option and the ForwardX11Trusted directive in ssh_config(5) for more information. -x Disables X11 forwarding. -Y Enables trusted X11 forwarding. Trusted X11 forwardings are not subjected to the X11 SECURITY extension controls. -y Send log information using the syslog(3) system module. By default this information is sent to stderr. may additionally obtain configuration data from a per-user configuration file and a system-wide configuration file. The file format and configuration options are described in ssh_config(5). AUTHENTICATION top The OpenSSH SSH client supports SSH protocol 2. The methods available for authentication are: GSSAPI-based authentication, host-based authentication, public key authentication, keyboard-interactive authentication, and password authentication. Authentication methods are tried in the order specified above, though PreferredAuthentications can be used to change the default order. Host-based authentication works as follows: If the machine the user logs in from is listed in /etc/hosts.equiv or /etc/shosts.equiv on the remote machine, the user is non-root and the user names are the same on both sides, or if the files ~/.rhosts or ~/.shosts exist in the user's home directory on the remote machine and contain a line containing the name of the client machine and the name of the user on that machine, the user is considered for login. Additionally, the server must be able to verify the client's host key (see the description of /etc/ssh/ssh_known_hosts and ~/.ssh/known_hosts, below) for login to be permitted. This authentication method closes security holes due to IP spoofing, DNS spoofing, and routing spoofing. [Note to the administrator: /etc/hosts.equiv, ~/.rhosts, and the rlogin/rsh protocol in general, are inherently insecure and should be disabled if security is desired.] Public key authentication works as follows: The scheme is based on public-key cryptography, using cryptosystems where encryption and decryption are done using separate keys, and it is unfeasible to derive the decryption key from the encryption key. The idea is that each user creates a public/private key pair for authentication purposes. The server knows the public key, and only the user knows the private key. implements public key authentication protocol automatically, using one of the DSA, ECDSA, Ed25519 or RSA algorithms. The HISTORY section of ssl(8) contains a brief discussion of the DSA and RSA algorithms. The file ~/.ssh/authorized_keys lists the public keys that are permitted for logging in. When the user logs in, the program tells the server which key pair it would like to use for authentication. The client proves that it has access to the private key and the server checks that the corresponding public key is authorized to accept the account. The server may inform the client of errors that prevented public key authentication from succeeding after authentication completes using a different method. These may be viewed by increasing the LogLevel to DEBUG or higher (e.g. by using the -v flag). The user creates their key pair by running ssh-keygen(1). This stores the private key in ~/.ssh/id_dsa (DSA), ~/.ssh/id_ecdsa (ECDSA), ~/.ssh/id_ecdsa_sk (authenticator-hosted ECDSA), ~/.ssh/id_ed25519 (Ed25519), ~/.ssh/id_ed25519_sk (authenticator- hosted Ed25519), or ~/.ssh/id_rsa (RSA) and stores the public key in ~/.ssh/id_dsa.pub (DSA), ~/.ssh/id_ecdsa.pub (ECDSA), ~/.ssh/id_ecdsa_sk.pub (authenticator-hosted ECDSA), ~/.ssh/id_ed25519.pub (Ed25519), ~/.ssh/id_ed25519_sk.pub (authenticator-hosted Ed25519), or ~/.ssh/id_rsa.pub (RSA) in the user's home directory. The user should then copy the public key to ~/.ssh/authorized_keys in their home directory on the remote machine. The authorized_keys file corresponds to the conventional ~/.rhosts file, and has one key per line, though the lines can be very long. After this, the user can log in without giving the password. A variation on public key authentication is available in the form of certificate authentication: instead of a set of public/private keys, signed certificates are used. This has the advantage that a single trusted certification authority can be used in place of many public/private keys. See the CERTIFICATES section of ssh-keygen(1) for more information. The most convenient way to use public key or certificate authentication may be with an authentication agent. See ssh-agent(1) and (optionally) the AddKeysToAgent directive in ssh_config(5) for more information. Keyboard-interactive authentication works as follows: The server sends an arbitrary "challenge" text and prompts for a response, possibly multiple times. Examples of keyboard-interactive authentication include BSD Authentication (see login.conf(5)) and PAM (some non-OpenBSD systems). Finally, if other authentication methods fail, prompts the user for a password. The password is sent to the remote host for checking; however, since all communications are encrypted, the password cannot be seen by someone listening on the network. automatically maintains and checks a database containing identification for all hosts it has ever been used with. Host keys are stored in ~/.ssh/known_hosts in the user's home directory. Additionally, the file /etc/ssh/ssh_known_hosts is automatically checked for known hosts. Any new hosts are automatically added to the user's file. If a host's identification ever changes, warns about this and disables password authentication to prevent server spoofing or man-in-the- middle attacks, which could otherwise be used to circumvent the encryption. The StrictHostKeyChecking option can be used to control logins to machines whose host key is not known or has changed. When the user's identity has been accepted by the server, the server either executes the given command in a non-interactive session or, if no command has been specified, logs into the machine and gives the user a normal shell as an interactive session. All communication with the remote command or shell will be automatically encrypted. If an interactive session is requested, by default will only request a pseudo-terminal (pty) for interactive sessions when the client has one. The flags -T and -t can be used to override this behaviour. If a pseudo-terminal has been allocated, the user may use the escape characters noted below. If no pseudo-terminal has been allocated, the session is transparent and can be used to reliably transfer binary data. On most systems, setting the escape character to none will also make the session transparent even if a tty is used. The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed. ESCAPE CHARACTERS top When a pseudo-terminal has been requested, supports a number of functions through the use of an escape character. A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option. The supported escapes (assuming the default ~) are: ~. Disconnect. ~^Z Background . ~# List forwarded connections. ~& Background at logout when waiting for forwarded connection / X11 sessions to terminate. ~? Display a list of escape characters. ~B Send a BREAK to the remote system (only useful if the peer supports it). ~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing port-forwardings with -KL[bind_address:]port for local, -KR[bind_address:]port for remote and -KD[bind_address:]port for dynamic port-forwardings. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is available, using the -h option. ~R Request rekeying of the connection (only useful if the peer supports it). ~V Decrease the verbosity (LogLevel) when errors are being written to stderr. ~v Increase the verbosity (LogLevel) when errors are being written to stderr. TCP FORWARDING top Forwarding of arbitrary TCP connections over a secure channel can be specified either on the command line or in a configuration file. One possible application of TCP forwarding is a secure connection to a mail server; another is going through firewalls. In the example below, we look at encrypting communication for an IRC client, even though the IRC server it connects to does not directly support encrypted communication. This works as follows: the user connects to the remote host using , specifying the ports to be used to forward the connection. After that it is possible to start the program locally, and will encrypt and forward the connection to the remote server. The following example tunnels an IRC session from the client to an IRC server at server.example.com, joining channel #users, nickname pinky, using the standard IRC port, 6667: $ ssh -f -L 6667:localhost:6667 server.example.com sleep 10 $ irc -c '#users' pinky IRC/127.0.0.1 The -f option backgrounds and the remote command sleep 10 is specified to allow an amount of time (10 seconds, in the example) to start the program which is going to use the tunnel. If no connections are made within the time specified, will exit. X11 FORWARDING top If the ForwardX11 variable is set to yes (or see the description of the -X, -x, and -Y options above) and the user is using X11 (the DISPLAY environment variable is set), the connection to the X11 display is automatically forwarded to the remote side in such a way that any X11 programs started from the shell (or command) will go through the encrypted channel, and the connection to the real X server will be made from the local machine. The user should not manually set DISPLAY. Forwarding of X11 connections can be configured on the command line or in configuration files. The DISPLAY value set by will point to the server machine, but with a display number greater than zero. This is normal, and happens because creates a proxy X server on the server machine for forwarding the connections over the encrypted channel. will also automatically set up Xauthority data on the server machine. For this purpose, it will generate a random authorization cookie, store it in Xauthority on the server, and verify that any forwarded connections carry this cookie and replace it by the real cookie when the connection is opened. The real authentication cookie is never sent to the server machine (and no cookies are sent in the plain). If the ForwardAgent variable is set to yes (or see the description of the -A and -a options above) and the user is using an authentication agent, the connection to the agent is automatically forwarded to the remote side. VERIFYING HOST KEYS top When connecting to a server for the first time, a fingerprint of the server's public key is presented to the user (unless the option StrictHostKeyChecking has been disabled). Fingerprints can be determined using ssh-keygen(1): $ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key If the fingerprint is already known, it can be matched and the key can be accepted or rejected. If only legacy (MD5) fingerprints for the server are available, the ssh-keygen(1) -E option may be used to downgrade the fingerprint algorithm to match. Because of the difficulty of comparing host keys just by looking at fingerprint strings, there is also support to compare host keys visually, using random art. By setting the VisualHostKey option to yes, a small ASCII graphic gets displayed on every login to a server, no matter if the session itself is interactive or not. By learning the pattern a known server produces, a user can easily find out that the host key has changed when a completely different pattern is displayed. Because these patterns are not unambiguous however, a pattern that looks similar to the pattern remembered only gives a good probability that the host key is the same, not guaranteed proof. To get a listing of the fingerprints along with their random art for all known hosts, the following command line can be used: $ ssh-keygen -lv -f ~/.ssh/known_hosts If the fingerprint is unknown, an alternative method of verification is available: SSH fingerprints verified by DNS. An additional resource record (RR), SSHFP, is added to a zonefile and the connecting client is able to match the fingerprint with that of the key presented. In this example, we are connecting a client to a server, host.example.com. The SSHFP resource records should first be added to the zonefile for host.example.com: $ ssh-keygen -r host.example.com. The output lines will have to be added to the zonefile. To check that the zone is answering fingerprint queries: $ dig -t SSHFP host.example.com Finally the client connects: $ ssh -o "VerifyHostKeyDNS ask" host.example.com [...] Matching host key fingerprint found in DNS. Are you sure you want to continue connecting (yes/no)? See the VerifyHostKeyDNS option in ssh_config(5) for more information. SSH-BASED VIRTUAL PRIVATE NETWORKS top contains support for Virtual Private Network (VPN) tunnelling using the tun(4) network pseudo-device, allowing two networks to be joined securely. The sshd_config(5) configuration option PermitTunnel controls whether the server supports this, and at what level (layer 2 or 3 traffic). The following example would connect client network 10.0.50.0/24 with remote network 10.0.99.0/24 using a point-to-point connection from 10.1.1.1 to 10.1.1.2, provided that the SSH server running on the gateway to the remote network, at 192.168.1.15, allows it. On the client: # ssh -f -w 0:1 192.168.1.15 true # ifconfig tun0 10.1.1.1 10.1.1.2 netmask 255.255.255.252 # route add 10.0.99.0/24 10.1.1.2 On the server: # ifconfig tun1 10.1.1.2 10.1.1.1 netmask 255.255.255.252 # route add 10.0.50.0/24 10.1.1.1 Client access may be more finely tuned via the /root/.ssh/authorized_keys file (see below) and the PermitRootLogin server option. The following entry would permit connections on tun(4) device 1 from user jane and on tun device 2 from user john, if PermitRootLogin is set to forced-commands-only: tunnel="1",command="sh /etc/netstart tun1" ssh-rsa ... jane tunnel="2",command="sh /etc/netstart tun2" ssh-rsa ... john Since an SSH-based setup entails a fair amount of overhead, it may be more suited to temporary setups, such as for wireless VPNs. More permanent VPNs are better provided by tools such as ipsecctl(8) and isakmpd(8). ENVIRONMENT top will normally set the following environment variables: DISPLAY The DISPLAY variable indicates the location of the X11 server. It is automatically set by to point to a value of the form hostname:n, where hostname indicates the host where the shell runs, and n is an integer 1. uses this special value to forward X11 connections over the secure channel. The user should normally not set DISPLAY explicitly, as that will render the X11 connection insecure (and will require the user to manually copy any required authorization cookies). HOME Set to the path of the user's home directory. LOGNAME Synonym for USER; set for compatibility with systems that use this variable. MAIL Set to the path of the user's mailbox. PATH Set to the default PATH, as specified when compiling . SSH_ASKPASS If needs a passphrase, it will read the passphrase from the current terminal if it was run from a terminal. If does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS and open an X11 window to read the passphrase. This is particularly useful when calling from a .xsession or related script. (Note that on some machines it may be necessary to redirect the input from /dev/null to make this work.) SSH_ASKPASS_REQUIRE Allows further control over the use of an askpass program. If this variable is set to never then will never attempt to use one. If it is set to prefer, then will prefer to use the askpass program instead of the TTY when requesting passwords. Finally, if the variable is set to force, then the askpass program will be used for all passphrase input regardless of whether DISPLAY is set. SSH_AUTH_SOCK Identifies the path of a Unix-domain socket used to communicate with the agent. SSH_CONNECTION Identifies the client and server ends of the connection. The variable contains four space-separated values: client IP address, client port number, server IP address, and server port number. SSH_ORIGINAL_COMMAND This variable contains the original command line if a forced command is executed. It can be used to extract the original arguments. SSH_TTY This is set to the name of the tty (path to the device) associated with the current shell or command. If the current session has no tty, this variable is not set. SSH_TUNNEL Optionally set by sshd(8) to contain the interface names assigned if tunnel forwarding was requested by the client. SSH_USER_AUTH Optionally set by sshd(8), this variable may contain a pathname to a file that lists the authentication methods successfully used when the session was established, including any public keys that were used. TZ This variable is set to indicate the present time zone if it was set when the daemon was started (i.e. the daemon passes the value on to new connections). USER Set to the name of the user logging in. Additionally, reads ~/.ssh/environment, and adds lines of the format VARNAME=value to the environment if the file exists and users are allowed to change their environment. For more information, see the PermitUserEnvironment option in sshd_config(5). FILES top ~/.rhosts This file is used for host-based authentication (see above). On some machines this file may need to be world- readable if the user's home directory is on an NFS partition, because sshd(8) reads it as root. Additionally, this file must be owned by the user, and must not have write permissions for anyone else. The recommended permission for most machines is read/write for the user, and not accessible by others. ~/.shosts This file is used in exactly the same way as .rhosts, but allows host-based authentication without permitting login with rlogin/rsh. ~/.ssh/ This directory is the default location for all user- specific configuration and authentication information. There is no general requirement to keep the entire contents of this directory secret, but the recommended permissions are read/write/execute for the user, and not accessible by others. ~/.ssh/authorized_keys Lists the public keys (DSA, ECDSA, Ed25519, RSA) that can be used for logging in as this user. The format of this file is described in the sshd(8) manual page. This file is not highly sensitive, but the recommended permissions are read/write for the user, and not accessible by others. ~/.ssh/config This is the per-user configuration file. The file format and configuration options are described in ssh_config(5). Because of the potential for abuse, this file must have strict permissions: read/write for the user, and not writable by others. ~/.ssh/environment Contains additional definitions for environment variables; see ENVIRONMENT, above. ~/.ssh/id_dsa ~/.ssh/id_ecdsa ~/.ssh/id_ecdsa_sk ~/.ssh/id_ed25519 ~/.ssh/id_ed25519_sk ~/.ssh/id_rsa Contains the private key for authentication. These files contain sensitive data and should be readable by the user but not accessible by others (read/write/execute). will simply ignore a private key file if it is accessible by others. It is possible to specify a passphrase when generating the key which will be used to encrypt the sensitive part of this file using AES-128. ~/.ssh/id_dsa.pub ~/.ssh/id_ecdsa.pub ~/.ssh/id_ecdsa_sk.pub ~/.ssh/id_ed25519.pub ~/.ssh/id_ed25519_sk.pub ~/.ssh/id_rsa.pub Contains the public key for authentication. These files are not sensitive and can (but need not) be readable by anyone. ~/.ssh/known_hosts Contains a list of host keys for all hosts the user has logged into that are not already in the systemwide list of known host keys. See sshd(8) for further details of the format of this file. ~/.ssh/rc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. /etc/hosts.equiv This file is for host-based authentication (see above). It should only be writable by root. /etc/shosts.equiv This file is used in exactly the same way as hosts.equiv, but allows host-based authentication without permitting login with rlogin/rsh. /etc/ssh/ssh_config Systemwide configuration file. The file format and configuration options are described in ssh_config(5). /etc/ssh/ssh_host_key /etc/ssh/ssh_host_dsa_key /etc/ssh/ssh_host_ecdsa_key /etc/ssh/ssh_host_ed25519_key /etc/ssh/ssh_host_rsa_key These files contain the private parts of the host keys and are used for host-based authentication. /etc/ssh/ssh_known_hosts Systemwide list of known host keys. This file should be prepared by the system administrator to contain the public host keys of all machines in the organization. It should be world-readable. See sshd(8) for further details of the format of this file. /etc/ssh/sshrc Commands in this file are executed by when the user logs in, just before the user's shell (or command) is started. See the sshd(8) manual page for more information. EXIT STATUS top exits with the exit status of the remote command or with 255 if an error occurred. SEE ALSO top scp(1), sftp(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh-keyscan(1), tun(4), ssh_config(5), ssh-keysign(8), sshd(8) STANDARDS top S. Lehtinen and C. Lonvick, The Secure Shell (SSH) Protocol Assigned Numbers, RFC 4250, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Protocol Architecture, RFC 4251, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Authentication Protocol, RFC 4252, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Transport Layer Protocol, RFC 4253, January 2006. T. Ylonen and C. Lonvick, The Secure Shell (SSH) Connection Protocol, RFC 4254, January 2006. J. Schlyter and W. Griffin, Using DNS to Securely Publish Secure Shell (SSH) Key Fingerprints, RFC 4255, January 2006. F. Cusack and M. Forssen, Generic Message Exchange Authentication for the Secure Shell Protocol (SSH), RFC 4256, January 2006. J. Galbraith and P. Remaker, The Secure Shell (SSH) Session Channel Break Extension, RFC 4335, January 2006. M. Bellare, T. Kohno, and C. Namprempre, The Secure Shell (SSH) Transport Layer Encryption Modes, RFC 4344, January 2006. B. Harris, Improved Arcfour Modes for the Secure Shell (SSH) Transport Layer Protocol, RFC 4345, January 2006. M. Friedl, N. Provos, and W. Simpson, Diffie-Hellman Group Exchange for the Secure Shell (SSH) Transport Layer Protocol, RFC 4419, March 2006. J. Galbraith and R. Thayer, The Secure Shell (SSH) Public Key File Format, RFC 4716, November 2006. D. Stebila and J. Green, Elliptic Curve Algorithm Integration in the Secure Shell Transport Layer, RFC 5656, December 2009. A. Perrig and D. Song, Hash Visualization: a New Technique to improve Real-World Security, 1999, International Workshop on Cryptographic Techniques and E-Commerce (CrypTEC '99). AUTHORS top OpenSSH is a derivative of the original and free ssh 1.2.12 release by Tatu Ylonen. Aaron Campbell, Bob Beck, Markus Friedl, Niels Provos, Theo de Raadt and Dug Song removed many bugs, re- added newer features and created OpenSSH. Markus Friedl contributed the support for SSH protocol versions 1.5 and 2.0. COLOPHON top This page is part of the openssh (Portable OpenSSH) project. Information about the project can be found at http://www.openssh.com/portable.html. If you have a bug report for this manual page, see http://www.openssh.com/report.html. This page was obtained from the tarball openssh-9.6p1.tar.gz fetched from http://ftp.eu.openbsd.org/pub/OpenBSD/OpenSSH/portable/ 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 October 11, 2023 SSH(1) Pages that refer to this page: stap-jupyter(1), systemd-stdio-bridge(1), tar(1), sd_bus_default(3), environment.d(5), proc(5), user@.service(5), pty(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: ssh into localhost on port 4444 Bash Command:<START>ssh -p 4444 localhost<END>
start 2 sleep processes in the background
sleep 100 | sleep 200 &
['sleep']
Output a Bash command to accomplish the following task. Task: start 2 sleep processes in the background Bash Command:<START>sleep 100 | sleep 200 &<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # sleep\n\n> Delay for a specified amount of time.\n> More information: <https://www.gnu.org/software/coreutils/sleep>.\n\n- Delay in seconds:\n\n`sleep {{seconds}}`\n\n- Delay in [m]inutes. (Other units [d]ay, [h]our, [s]econd, [inf]inity can also be used):\n\n`sleep {{minutes}}m`\n\n- Delay for 1 [d]ay 3 [h]ours:\n\n`sleep 1d 3h`\n\n- Execute a specific command after 20 [m]inutes delay:\n\n`sleep 20m && {{command}}`\n Task: start 2 sleep processes in the background Bash Command:<START>sleep 100 | sleep 200 &<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: sleep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sleep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SLEEP(1) User Commands SLEEP(1) NAME top sleep - delay for a specified amount of time SYNOPSIS top sleep NUMBER[SUFFIX]... sleep OPTION DESCRIPTION top Pause for NUMBER seconds. SUFFIX may be 's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. NUMBER need not be an integer. Given two or more arguments, pause for the amount of time specified by the sum of their values. --help display this help and exit --version output version information and exit AUTHOR top Written by Jim Meyering 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 sleep(3) Full documentation <https://www.gnu.org/software/coreutils/sleep> or available locally via: info '(coreutils) sleep 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 SLEEP(1) Pages that refer to this page: dbpmda(1), pmsleep(1), ioctl_ns(2), sleep(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: start 2 sleep processes in the background Bash Command:<START>sleep 100 | sleep 200 &<END>
start from current directory, skip the directory src/emacs and all files and directories under it, and print the names of the other files found
find . -wholename './src/emacs' -prune -o -print
['find']
Output a Bash command to accomplish the following task. Task: start from current directory, skip the directory src/emacs and all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune -o -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: start from current directory, skip the directory src/emacs and all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune -o -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: start from current directory, skip the directory src/emacs and all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune -o -print<END>
start from current directory, skip the directory src/emacs and print it then skip all files and directories under it, and print the names of the other files found
find . -wholename './src/emacs' -prune , -print
['find']
Output a Bash command to accomplish the following task. Task: start from current directory, skip the directory src/emacs and print it then skip all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune , -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: start from current directory, skip the directory src/emacs and print it then skip all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune , -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: start from current directory, skip the directory src/emacs and print it then skip all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune , -print<END>
start from current directory, skip the directory src/emacs and print it then skip all files and directories under it, and print the names of the other files found
find . -wholename './src/emacs' -prune -print -o -print
['find']
Output a Bash command to accomplish the following task. Task: start from current directory, skip the directory src/emacs and print it then skip all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune -print -o -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: start from current directory, skip the directory src/emacs and print it then skip all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune -print -o -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: start from current directory, skip the directory src/emacs and print it then skip all files and directories under it, and print the names of the other files found Bash Command:<START>find . -wholename './src/emacs' -prune -print -o -print<END>
switch to user username
su username
['su']
Output a Bash command to accomplish the following task. Task: switch to user username Bash Command:<START>su username<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # su\n\n> Switch shell to another user.\n> More information: <https://manned.org/su>.\n\n- Switch to superuser (requires the root password):\n\n`su`\n\n- Switch to a given user (requires the user's password):\n\n`su {{username}}`\n\n- Switch to a given user and simulate a full login shell:\n\n`su - {{username}}`\n\n- Execute a command as another user:\n\n`su - {{username}} -c "{{command}}"`\n Task: switch to user username Bash Command:<START>su username<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: su(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training Another version of this page is provided by the shadow-utils project su(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | SIGNALS | CONFIG FILES | EXIT STATUS | FILES | NOTES | HISTORY | SEE ALSO | REPORTING BUGS | AVAILABILITY SU(1) User Commands SU(1) NAME top su - run a command with substitute user and group ID SYNOPSIS top su [options] [-] [user [argument...]] DESCRIPTION top su allows commands to be run with a substitute user and group ID. When called with no user specified, su defaults to running an interactive shell as root. When user is specified, additional arguments can be supplied, in which case they are passed to the shell. For backward compatibility, su defaults to not change the current directory and to only set the environment variables HOME and SHELL (plus USER and LOGNAME if the target user is not root). It is recommended to always use the --login option (instead of its shortcut -) to avoid side effects caused by mixing environments. This version of su uses PAM for authentication, account and session management. Some configuration options found in other su implementations, such as support for a wheel group, have to be configured via PAM. su is mostly designed for unprivileged users, the recommended solution for privileged users (e.g., scripts executed by root) is to use non-set-user-ID command runuser(1) that does not require authentication and provides separate PAM configuration. If the PAM session is not required at all then the recommended solution is to use command setpriv(1). Note that su in all cases uses PAM (pam_getenvlist(3)) to do the final environment modification. Command-line options such as --login and --preserve-environment affect the environment before it is modified by PAM. Since version 2.38 su resets process resource limits RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_FSIZE, RLIMIT_AS and RLIMIT_NOFILE. OPTIONS top -c, --command=command Pass command to the shell with the -c option. -f, --fast Pass -f to the shell, which may or may not be useful, depending on the shell. -g, --group=group Specify the primary group. This option is available to the root user only. -G, --supp-group=group Specify a supplementary group. This option is available to the root user only. The first specified supplementary group is also used as a primary group if the option --group is not specified. -, -l, --login Start the shell as a login shell with an environment similar to a real login: clears all the environment variables except TERM and variables specified by --whitelist-environment initializes the environment variables HOME, SHELL, USER, LOGNAME, and PATH changes to the target users home directory sets argv[0] of the shell to '-' in order to make the shell a login shell -m, -p, --preserve-environment Preserve the entire environment, i.e., do not set HOME, SHELL, USER or LOGNAME. This option is ignored if the option --login is specified. -P, --pty Create a pseudo-terminal for the session. The independent terminal provides better security as the user does not share a terminal with the original session. This can be used to avoid TIOCSTI ioctl terminal injection and other security attacks against terminal file descriptors. The entire session can also be moved to the background (e.g., su --pty - username -c application &). If the pseudo-terminal is enabled, then su works as a proxy between the sessions (sync stdin and stdout). This feature is mostly designed for interactive sessions. If the standard input is not a terminal, but for example a pipe (e.g., echo "date" | su --pty), then the ECHO flag for the pseudo-terminal is disabled to avoid messy output. -s, --shell=shell Run the specified shell instead of the default. The shell to run is selected according to the following rules, in order: the shell specified with --shell the shell specified in the environment variable SHELL, if the --preserve-environment option is used the shell listed in the passwd entry of the target user /bin/sh If the target user has a restricted shell (i.e., not listed in /etc/shells), the --shell option and the SHELL environment variables are ignored unless the calling user is root. --session-command=command Same as -c, but do not create a new session. (Discouraged.) -w, --whitelist-environment=list Dont reset the environment variables specified in the comma-separated list when clearing the environment for --login. The whitelist is ignored for the environment variables HOME, SHELL, USER, LOGNAME, and PATH. -h, --help Display help text and exit. -V, --version Print version and exit. SIGNALS top Upon receiving either SIGINT, SIGQUIT or SIGTERM, su terminates its child and afterwards terminates itself with the received signal. The child is terminated by SIGTERM, after unsuccessful attempt and 2 seconds of delay the child is killed by SIGKILL. CONFIG FILES top su reads the /etc/default/su and /etc/login.defs configuration files. The following configuration items are relevant for su: FAIL_DELAY (number) Delay in seconds in case of an authentication failure. The number must be a non-negative integer. ENV_PATH (string) Defines the PATH environment variable for a regular user. The default value is /usr/local/bin:/bin:/usr/bin. ENV_ROOTPATH (string), ENV_SUPATH (string) Defines the PATH environment variable for root. ENV_SUPATH takes precedence. The default value is /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin. ALWAYS_SET_PATH (boolean) If set to yes and --login and --preserve-environment were not specified su initializes PATH. The environment variable PATH may be different on systems where /bin and /sbin are merged into /usr; this variable is also affected by the --login command-line option and the PAM system setting (e.g., pam_env(8)). EXIT STATUS top su normally returns the exit status of the command it executed. If the command was killed by a signal, su returns the number of the signal plus 128. Exit status generated by su itself: 1 Generic error before executing the requested command 126 The requested command could not be executed 127 The requested command was not found FILES top /etc/pam.d/su default PAM configuration file /etc/pam.d/su-l PAM configuration file if --login is specified /etc/default/su command specific logindef config file /etc/login.defs global logindef config file NOTES top For security reasons, su always logs failed log-in attempts to the btmp file, but it does not write to the lastlog file at all. This solution can be used to control su behavior by PAM configuration. If you want to use the pam_lastlog(8) module to print warning message about failed log-in attempts then pam_lastlog(8) has to be configured to update the lastlog file as well. For example by: session required pam_lastlog.so nowtmp HISTORY top This su command was derived from coreutils' su, which was based on an implementation by David MacKenzie. The util-linux version has been refactored by Karel Zak. SEE ALSO top setpriv(1), login.defs(5), shells(5), pam(8), runuser(1) REPORTING BUGS top For bug reports, use the issue tracker at https://github.com/util-linux/util-linux/issues. AVAILABILITY top The su 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 SU(1) Pages that refer to this page: flock(1), homectl(1), login(1), login(1@@shadow-utils), machinectl(1), newgrp(1), runuser(1), setpriv(1), sg(1), updatedb(1), pam(3), pts(4), crontab(5), login.defs(5), passwd(5), passwd(5@@shadow-utils), shadow(5), suauth(5), credentials(7), environ(7), PAM(8), pam_rootok(8), pam_xauth(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: switch to user username Bash Command:<START>su username<END>
tar all files in the current folder and ask for user confirmation before creating the tar ball
find . -ok tar rvf backup {} \;
['find', 'tar']
Output a Bash command to accomplish the following task. Task: tar all files in the current folder and ask for user confirmation before creating the tar ball Bash Command:<START>find . -ok tar rvf backup {} \;<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 # tar\n\n> Archiving utility.\n> Often combined with a compression method, such as `gzip` or `bzip2`.\n> More information: <https://www.gnu.org/software/tar>.\n\n- [c]reate an archive and write it to a [f]ile:\n\n`tar cf {{path/to/target.tar}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive and write it to a [f]ile:\n\n`tar czf {{path/to/target.tar.gz}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive from a directory using relative paths:\n\n`tar czf {{path/to/target.tar.gz}} --directory={{path/to/directory}} .`\n\n- E[x]tract a (compressed) archive [f]ile into the current directory [v]erbosely:\n\n`tar xvf {{path/to/source.tar[.gz|.bz2|.xz]}}`\n\n- E[x]tract a (compressed) archive [f]ile into the target directory:\n\n`tar xf {{path/to/source.tar[.gz|.bz2|.xz]}} --directory={{path/to/directory}}`\n\n- [c]reate a compressed archive and write it to a [f]ile, using the file extension to [a]utomatically determine the compression program:\n\n`tar caf {{path/to/target.tar.xz}} {{path/to/file1 path/to/file2 ...}}`\n\n- Lis[t] the contents of a tar [f]ile [v]erbosely:\n\n`tar tvf {{path/to/source.tar}}`\n\n- E[x]tract files matching a pattern from an archive [f]ile:\n\n`tar xf {{path/to/source.tar}} --wildcards "{{*.html}}"`\n Task: tar all files in the current folder and ask for user confirmation before creating the tar ball Bash Command:<START>find . -ok tar rvf backup {} \;<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. tar(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tar(1) Linux manual page NAME | SYNOPSIS | NOTE | DESCRIPTION | OPTIONS | RETURN VALUE | SEE ALSO | BUG REPORTS | COPYRIGHT | COLOPHON TAR(1) GNU TAR Manual TAR(1) NAME top tar - an archiving utility SYNOPSIS top Traditional usage tar {A|c|d|r|t|u|x}[GnSkUWOmpsMBiajJzZhPlRvwo] [ARG...] UNIX-style usage tar -A [OPTIONS] -f ARCHIVE ARCHIVE... tar -c [-f ARCHIVE] [OPTIONS] [FILE...] tar -d [-f ARCHIVE] [OPTIONS] [FILE...] tar -r [-f ARCHIVE] [OPTIONS] [FILE...] tar -t [-f ARCHIVE] [OPTIONS] [MEMBER...] tar -u [-f ARCHIVE] [OPTIONS] [FILE...] tar -x [-f ARCHIVE] [OPTIONS] [MEMBER...] GNU-style usage tar {--catenate|--concatenate} [OPTIONS] --file ARCHIVE ARCHIVE... tar --create [--file ARCHIVE] [OPTIONS] [FILE...] tar {--diff|--compare} [--file ARCHIVE] [OPTIONS] [FILE...] tar --delete [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --append [--file ARCHIVE] [OPTIONS] [FILE...] tar --list [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --test-label [--file ARCHIVE] [OPTIONS] [LABEL...] tar --update [--file ARCHIVE] [OPTIONS] [FILE...] tar {--extract|--get} [--file ARCHIVE] [OPTIONS] [MEMBER...] NOTE top This manpage is a short description of GNU tar. For a detailed discussion, including examples and usage recommendations, refer to the GNU Tar Manual available in texinfo format. If the info reader and the tar documentation are properly installed on your system, the command info tar should give you access to the complete manual. You can also view the manual using the info mode in emacs(1), or find it in various formats online at https://www.gnu.org/software/tar/manual If any discrepancies occur between this manpage and the GNU Tar Manual, the later shall be considered the authoritative source. DESCRIPTION top GNU tar is an archiving program designed to store multiple files in a single file (an archive), and to manipulate such archives. The archive can be either a regular file or a device (e.g. a tape drive, hence the name of the program, which stands for tape archiver), which can be located either on the local or on a remote machine. Option styles Options to GNU tar can be given in three different styles. In traditional style, the first argument is a cluster of option letters and all subsequent arguments supply arguments to those options that require them. The arguments are read in the same order as the option letters. Any command line words that remain after all options have been processed are treated as non-option arguments: file or archive member names. For example, the c option requires creating the archive, the v option requests the verbose operation, and the f option takes an argument that sets the name of the archive to operate upon. The following command, written in the traditional style, instructs tar to store all files from the directory /etc into the archive file etc.tar, verbosely listing the files being archived: tar cfv etc.tar /etc In UNIX or short-option style, each option letter is prefixed with a single dash, as in other command line utilities. If an option takes an argument, the argument follows it, either as a separate command line word, or immediately following the option. However, if the option takes an optional argument, the argument must follow the option letter without any intervening whitespace, as in -g/tmp/snar.db. Any number of options not taking arguments can be clustered together after a single dash, e.g. -vkp. An option that takes an argument (whether mandatory or optional) can appear at the end of such a cluster, e.g. -vkpf a.tar. The example command above written in the short-option style could look like: tar -cvf etc.tar /etc or tar -c -v -f etc.tar /etc In GNU or long-option style, each option begins with two dashes and has a meaningful name, consisting of lower-case letters and dashes. When used, the long option can be abbreviated to its initial letters, provided that this does not create ambiguity. Arguments to long options are supplied either as a separate command line word, immediately following the option, or separated from the option by an equals sign with no intervening whitespace. Optional arguments must always use the latter method. Here are several ways of writing the example command in this style: tar --create --file etc.tar --verbose /etc or (abbreviating some options): tar --cre --file=etc.tar --verb /etc The options in all three styles can be intermixed, although doing so with old options is not encouraged. Operation mode The options listed in the table below tell GNU tar what operation it is to perform. Exactly one of them must be given. The meaning of non-option arguments depends on the operation mode requested. -A, --catenate, --concatenate Append archives to the end of another archive. The arguments are treated as the names of archives to append. All archives must be of the same format as the archive they are appended to, otherwise the resulting archive might be unusable with non-GNU implementations of tar. Notice also that when more than one archive is given, the members from archives other than the first one will be accessible in the resulting archive only when using the -i (--ignore-zeros) option. Compressed archives cannot be concatenated. -c, --create Create a new archive. Arguments supply the names of the files to be archived. Directories are archived recursively, unless the --no-recursion option is given. -d, --diff, --compare Find differences between archive and file system. The arguments are optional and specify archive members to compare. If not given, the current working directory is assumed. --delete Delete from the archive. The arguments supply names of the archive members to be removed. At least one argument must be given. This option does not operate on compressed archives. There is no short option equivalent. -r, --append Append files to the end of an archive. Arguments have the same meaning as for -c (--create). -t, --list List the contents of an archive. Arguments are optional. When given, they specify the names of the members to list. --test-label Test the archive volume label and exit. When used without arguments, it prints the volume label (if any) and exits with status 0. When one or more command line arguments are given. tar compares the volume label with each argument. It exits with code 0 if a match is found, and with code 1 otherwise. No output is displayed, unless used together with the -v (--verbose) option. There is no short option equivalent for this option. -u, --update Append files which are newer than the corresponding copy in the archive. Arguments have the same meaning as with the -c and -r options. Notice, that newer files don't replace their old archive copies, but instead are appended to the end of archive. The resulting archive can thus contain several members of the same name, corresponding to various versions of the same file. -x, --extract, --get Extract files from an archive. Arguments are optional. When given, they specify names of the archive members to be extracted. --show-defaults Show built-in defaults for various tar options and exit. -?, --help Display a short option summary and exit. --usage Display a list of available options and exit. --version Print program version and copyright information and exit. OPTIONS top Operation modifiers --check-device Check device numbers when creating incremental archives (default). -g, --listed-incremental=FILE Handle new GNU-format incremental backups. FILE is the name of a snapshot file, where tar stores additional information which is used to decide which files changed since the previous incremental dump and, consequently, must be dumped again. If FILE does not exist when creating an archive, it will be created and all files will be added to the resulting archive (the level 0 dump). To create incremental archives of non-zero level N, you need a copy of the snapshot file created for level N-1, and use it as FILE. When listing or extracting, the actual content of FILE is not inspected, it is needed only due to syntactical requirements. It is therefore common practice to use /dev/null in its place. --hole-detection=METHOD Use METHOD to detect holes in sparse files. This option implies --sparse. Valid values for METHOD are seek and raw. Default is seek with fallback to raw when not applicable. -G, --incremental Handle old GNU-format incremental backups. --ignore-failed-read Do not exit with nonzero on unreadable files. --level=NUMBER Set dump level for a created listed-incremental archive. Currently only --level=0 is meaningful: it instructs tar to truncate the snapshot file before dumping, thereby forcing a level 0 dump. -n, --seek Assume the archive is seekable. Normally tar determines automatically whether the archive can be seeked or not. This option is intended for use in cases when such recognition fails. It takes effect only if the archive is open for reading (e.g. with --list or --extract options). --no-check-device Do not check device numbers when creating incremental archives. --no-seek Assume the archive is not seekable. --occurrence[=N] Process only the Nth occurrence of each file in the archive. This option is valid only when used with one of the following subcommands: --delete, --diff, --extract or --list and when a list of files is given either on the command line or via the -T option. The default N is 1. --restrict Disable the use of some potentially harmful options. --sparse-version=MAJOR[.MINOR] Set which version of the sparse format to use. This option implies --sparse. Valid argument values are 0.0, 0.1, and 1.0. For a detailed discussion of sparse formats, refer to the GNU Tar Manual, appendix D, "Sparse Formats". Using the info reader, it can be accessed running the following command: info tar 'Sparse Formats'. -S, --sparse Handle sparse files efficiently. Some files in the file system may have segments which were actually never written (quite often these are database files created by such systems as DBM). When given this option, tar attempts to determine if the file is sparse prior to archiving it, and if so, to reduce the resulting archive size by not dumping empty parts of the file. Overwrite control These options control tar actions when extracting a file over an existing copy on disk. -k, --keep-old-files Don't replace existing files when extracting. --keep-newer-files Don't replace existing files that are newer than their archive copies. --keep-directory-symlink Don't replace existing symlinks to directories when extracting. --no-overwrite-dir Preserve metadata of existing directories. --one-top-level[=DIR] Extract all files into DIR, or, if used without argument, into a subdirectory named by the base name of the archive (minus standard compression suffixes recognizable by --auto-compress). --overwrite Overwrite existing files when extracting. --overwrite-dir Overwrite metadata of existing directories when extracting (default). --recursive-unlink Recursively remove all files in the directory prior to extracting it. --remove-files Remove files from disk after adding them to the archive. --skip-old-files Don't replace existing files when extracting, silently skip over them. -U, --unlink-first Remove each file prior to extracting over it. -W, --verify Verify the archive after writing it. Output stream selection --ignore-command-error Ignore subprocess exit codes. --no-ignore-command-error Treat non-zero exit codes of children as error (default). -O, --to-stdout Extract files to standard output. --to-command=COMMAND Pipe extracted files to COMMAND. The argument is the pathname of an external program, optionally with command line arguments. The program will be invoked and the contents of the file being extracted supplied to it on its standard input. Additional data will be supplied via the following environment variables: TAR_FILETYPE Type of the file. It is a single letter with the following meaning: f Regular file d Directory l Symbolic link h Hard link b Block device c Character device Currently only regular files are supported. TAR_MODE File mode, an octal number. TAR_FILENAME The name of the file. TAR_REALNAME Name of the file as stored in the archive. TAR_UNAME Name of the file owner. TAR_GNAME Name of the file owner group. TAR_ATIME Time of last access. It is a decimal number, representing seconds since the Epoch. If the archive provides times with nanosecond precision, the nanoseconds are appended to the timestamp after a decimal point. TAR_MTIME Time of last modification. TAR_CTIME Time of last status change. TAR_SIZE Size of the file. TAR_UID UID of the file owner. TAR_GID GID of the file owner. Additionally, the following variables contain information about tar operation mode and the archive being processed: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. Handling of file attributes --atime-preserve[=METHOD] Preserve access times on dumped files, either by restoring the times after reading (METHOD=replace, this is the default) or by not setting the times in the first place (METHOD=system). --delay-directory-restore Delay setting modification times and permissions of extracted directories until the end of extraction. Use this option when extracting from an archive which has unusual member ordering. --group=NAME[:GID] Force NAME as group for added files. If GID is not supplied, NAME can be either a user name or numeric GID. In this case the missing part (GID or name) will be inferred from the current host's group database. When used with --group-map=FILE, affects only those files whose owner group is not listed in FILE. --group-map=FILE Read group translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single group. It must consist of two fields, delimited by any amount of whitespace: OLDGRP NEWGRP[:NEWGID] OLDGRP is either a valid group name or a GID prefixed with +. Unless NEWGID is supplied, NEWGRP must also be either a valid group name or a +GID. Otherwise, both NEWGRP and NEWGID need not be listed in the system group database. As a result, each input file with owner group OLDGRP will be stored in archive with owner group NEWGRP and GID NEWGID. --mode=CHANGES Force symbolic mode CHANGES for added files. --mtime=DATE-OR-FILE Set mtime for added files. DATE-OR-FILE is either a date/time in almost arbitrary format, or the name of an existing file. In the latter case the mtime of that file will be used. -m, --touch Don't extract file modified time. --no-delay-directory-restore Cancel the effect of the prior --delay-directory-restore option. --no-same-owner Extract files as yourself (default for ordinary users). --no-same-permissions Apply the user's umask when extracting permissions from the archive (default for ordinary users). --numeric-owner Always use numbers for user/group names. --owner=NAME[:UID] Force NAME as owner for added files. If UID is not supplied, NAME can be either a user name or numeric UID. In this case the missing part (UID or name) will be inferred from the current host's user database. When used with --owner-map=FILE, affects only those files whose owner is not listed in FILE. --owner-map=FILE Read owner translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single UID. It must consist of two fields, delimited by any amount of whitespace: OLDUSR NEWUSR[:NEWUID] OLDUSR is either a valid user name or a UID prefixed with +. Unless NEWUID is supplied, NEWUSR must also be either a valid user name or a +UID. Otherwise, both NEWUSR and NEWUID need not be listed in the system user database. As a result, each input file owned by OLDUSR will be stored in archive with owner name NEWUSR and UID NEWUID. -p, --preserve-permissions, --same-permissions Set permissions of extracted files to those recorded in the archive (default for superuser). --same-owner Try extracting files with the same ownership as exists in the archive (default for superuser). -s, --preserve-order, --same-order Tell tar that the list of file names to process is sorted in the same order as the files in the archive. --sort=ORDER When creating an archive, sort directory entries according to ORDER, which is one of none, name, or inode. The default is --sort=none, which stores archive members in the same order as returned by the operating system. Using --sort=name ensures the member ordering in the created archive is uniform and reproducible. Using --sort=inode reduces the number of disk seeks made when creating the archive and thus can considerably speed up archivation. This sorting order is supported only if the underlying system provides the necessary information. Extended file attributes --acls Enable POSIX ACLs support. --no-acls Disable POSIX ACLs support. --selinux Enable SELinux context support. --no-selinux Disable SELinux context support. --xattrs Enable extended attributes support. --no-xattrs Disable extended attributes support. --xattrs-exclude=PATTERN Specify the exclude pattern for xattr keys. PATTERN is a globbing pattern, e.g. --xattrs-exclude='user.*' to include only attributes from the user namespace. --xattrs-include=PATTERN Specify the include pattern for xattr keys. PATTERN is a globbing pattern. Device selection and switching -f, --file=ARCHIVE Use archive file or device ARCHIVE. If this option is not given, tar will first examine the environment variable `TAPE'. If it is set, its value will be used as the archive name. Otherwise, tar will assume the compiled-in default. The default value can be inspected either using the --show-defaults option, or at the end of the tar --help output. An archive name that has a colon in it specifies a file or device on a remote machine. The part before the colon is taken as the machine name or IP address, and the part after it as the file or device pathname, e.g.: --file=remotehost:/dev/sr0 An optional username can be prefixed to the hostname, placing a @ sign between them. By default, the remote host is accessed via the rsh(1) command. Nowadays it is common to use ssh(1) instead. You can do so by giving the following command line option: --rsh-command=/usr/bin/ssh The remote machine should have the rmt(8) command installed. If its pathname does not match tar's default, you can inform tar about the correct pathname using the --rmt-command option. --force-local Archive file is local even if it has a colon. -F, --info-script=COMMAND, --new-volume-script=COMMAND Run COMMAND at the end of each tape (implies -M). The command can include arguments. When started, it will inherit tar's environment plus the following variables: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. TAR_FD File descriptor which can be used to communicate the new volume name to tar. If the info script fails, tar exits; otherwise, it begins writing the next volume. -L, --tape-length=N Change tape after writing Nx1024 bytes. If N is followed by a size suffix (see the subsection Size suffixes below), the suffix specifies the multiplicative factor to be used instead of 1024. This option implies -M. -M, --multi-volume Create/list/extract multi-volume archive. --rmt-command=COMMAND Use COMMAND instead of rmt when accessing remote archives. See the description of the -f option, above. --rsh-command=COMMAND Use COMMAND instead of rsh when accessing remote archives. See the description of the -f option, above. --volno-file=FILE When this option is used in conjunction with --multi-volume, tar will keep track of which volume of a multi-volume archive it is working in FILE. Device blocking -b, --blocking-factor=BLOCKS Set record size to BLOCKSx512 bytes. -B, --read-full-records When listing or extracting, accept incomplete input records after end-of-file marker. -i, --ignore-zeros Ignore zeroed blocks in archive. Normally two consecutive 512-blocks filled with zeroes mean EOF and tar stops reading after encountering them. This option instructs it to read further and is useful when reading archives created with the -A option. --record-size=NUMBER Set record size. NUMBER is the number of bytes per record. It must be multiple of 512. It can can be suffixed with a size suffix, e.g. --record-size=10K, for 10 Kilobytes. See the subsection Size suffixes, for a list of valid suffixes. Archive format selection -H, --format=FORMAT Create archive of the given format. Valid formats are: gnu GNU tar 1.13.x format oldgnu GNU format as per tar <= 1.12. pax, posix POSIX 1003.1-2001 (pax) format. ustar POSIX 1003.1-1988 (ustar) format. v7 Old V7 tar format. --old-archive, --portability Same as --format=v7. --pax-option=keyword[[:]=value][,keyword[[:]=value]]... Control pax keywords when creating PAX archives (-H pax). This option is equivalent to the -o option of the pax(1) utility. --posix Same as --format=posix. -V, --label=TEXT Create archive with volume name TEXT. If listing or extracting, use TEXT as a globbing pattern for volume name. Compression options -a, --auto-compress Use archive suffix to determine the compression program. -I, --use-compress-program=COMMAND Filter data through COMMAND. It must accept the -d option, for decompression. The argument can contain command line options. -j, --bzip2 Filter the archive through bzip2(1). -J, --xz Filter the archive through xz(1). --lzip Filter the archive through lzip(1). --lzma Filter the archive through lzma(1). --lzop Filter the archive through lzop(1). --no-auto-compress Do not use archive suffix to determine the compression program. -z, --gzip, --gunzip, --ungzip Filter the archive through gzip(1). -Z, --compress, --uncompress Filter the archive through compress(1). --zstd Filter the archive through zstd(1). Local file selection --add-file=FILE Add FILE to the archive (useful if its name starts with a dash). --backup[=CONTROL] Backup before removal. The CONTROL argument, if supplied, controls the backup policy. Its valid values are: none, off Never make backups. t, numbered Make numbered backups. nil, existing Make numbered backups if numbered backups exist, simple backups otherwise. never, simple Always make simple backups If CONTROL is not given, the value is taken from the VERSION_CONTROL environment variable. If it is not set, existing is assumed. -C, --directory=DIR Change to DIR before performing any operations. This option is order-sensitive, i.e. it affects all options that follow. --exclude=PATTERN Exclude files matching PATTERN, a glob(3)-style wildcard pattern. --exclude-backups Exclude backup and lock files. --exclude-caches Exclude contents of directories containing file CACHEDIR.TAG, except for the tag file itself. --exclude-caches-all Exclude directories containing file CACHEDIR.TAG and the file itself. --exclude-caches-under Exclude everything under directories containing CACHEDIR.TAG --exclude-ignore=FILE Before dumping a directory, see if it contains FILE. If so, read exclusion patterns from this file. The patterns affect only the directory itself. --exclude-ignore-recursive=FILE Same as --exclude-ignore, except that patterns from FILE affect both the directory and all its subdirectories. --exclude-tag=FILE Exclude contents of directories containing FILE, except for FILE itself. --exclude-tag-all=FILE Exclude directories containing FILE. --exclude-tag-under=FILE Exclude everything under directories containing FILE. --exclude-vcs Exclude version control system directories. --exclude-vcs-ignores Exclude files that match patterns read from VCS-specific ignore files. Supported files are: .cvsignore, .gitignore, .bzrignore, and .hgignore. -h, --dereference Follow symlinks; archive and dump the files they point to. --hard-dereference Follow hard links; archive and dump the files they refer to. -K, --starting-file=MEMBER Begin at the given member in the archive. --newer-mtime=DATE Work on files whose data changed after the DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --no-null Disable the effect of the previous --null option. --no-recursion Avoid descending automatically in directories. --no-unquote Do not unquote input file or member names. --no-verbatim-files-from Treat each line read from a file list as if it were supplied in the command line. I.e., leading and trailing whitespace is removed and, if the resulting string begins with a dash, it is treated as tar command line option. This is the default behavior. The --no-verbatim-files-from option is provided as a way to restore it after --verbatim-files-from option. This option is positional: it affects all --files-from options that occur after it in, until --verbatim-files-from option or end of line, whichever occurs first. It is implied by the --no-null option. --null Instruct subsequent -T options to read null-terminated names verbatim (disables special handling of names that start with a dash). See also --verbatim-files-from. -N, --newer=DATE, --after-date=DATE Only store files newer than DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --one-file-system Stay in local file system when creating archive. -P, --absolute-names Don't strip leading slashes from file names when creating archives. --recursion Recurse into directories (default). --suffix=STRING Backup before removal, override usual suffix. Default suffix is ~, unless overridden by environment variable SIMPLE_BACKUP_SUFFIX. -T, --files-from=FILE Get names to extract or create from FILE. Unless specified otherwise, the FILE must contain a list of names separated by ASCII LF (i.e. one name per line). The names read are handled the same way as command line arguments. They undergo quote removal and word splitting, and any string that starts with a - is handled as tar command line option. If this behavior is undesirable, it can be turned off using the --verbatim-files-from option. The --null option instructs tar that the names in FILE are separated by ASCII NUL character, instead of LF. It is useful if the list is generated by find(1) -print0 predicate. --unquote Unquote file or member names (default). --verbatim-files-from Treat each line obtained from a file list as a file name, even if it starts with a dash. File lists are supplied with the --files-from (-T) option. The default behavior is to handle names supplied in file lists as if they were typed in the command line, i.e. any names starting with a dash are treated as tar options. The --verbatim-files-from option disables this behavior. This option affects all --files-from options that occur after it in the command line. Its effect is reverted by the --no-verbatim-files-from option. This option is implied by the --null option. See also --add-file. -X, --exclude-from=FILE Exclude files matching patterns listed in FILE. File name transformations --strip-components=NUMBER Strip NUMBER leading components from file names on extraction. --transform=EXPRESSION, --xform=EXPRESSION Use sed replace EXPRESSION to transform file names. File name matching options These options affect both exclude and include patterns. --anchored Patterns match file name start. --ignore-case Ignore case. --no-anchored Patterns match after any / (default for exclusion). --no-ignore-case Case sensitive matching (default). --no-wildcards Verbatim string matching. --no-wildcards-match-slash Wildcards do not match /. --wildcards Use wildcards (default for exclusion). --wildcards-match-slash Wildcards match / (default for exclusion). Informative output --checkpoint[=N] Display progress messages every Nth record (default 10). --checkpoint-action=ACTION Run ACTION on each checkpoint. --clamp-mtime Only set time when the file is more recent than what was given with --mtime. --full-time Print file time to its full resolution. --index-file=FILE Send verbose output to FILE. -l, --check-links Print a message if not all links are dumped. --no-quote-chars=STRING Disable quoting for characters from STRING. --quote-chars=STRING Additionally quote characters from STRING. --quoting-style=STYLE Set quoting style for file and member names. Valid values for STYLE are literal, shell, shell-always, c, c-maybe, escape, locale, clocale. -R, --block-number Show block number within archive with each message. --show-omitted-dirs When listing or extracting, list each directory that does not match search criteria. --show-transformed-names, --show-stored-names Show file or archive names after transformation by --strip and --transform options. --totals[=SIGNAL] Print total bytes after processing the archive. If SIGNAL is given, print total bytes when this signal is delivered. Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1, and SIGUSR2. The SIG prefix can be omitted. --utc Print file modification times in UTC. -v, --verbose Verbosely list files processed. Each instance of this option on the command line increases the verbosity level by one. The maximum verbosity level is 3. For a detailed discussion of how various verbosity levels affect tar's output, please refer to GNU Tar Manual, subsection 2.5.2 "The '--verbose' Option". --warning=KEYWORD Enable or disable warning messages identified by KEYWORD. The messages are suppressed if KEYWORD is prefixed with no- and enabled otherwise. Multiple --warning options accumulate. Keywords controlling general tar operation: all Enable all warning messages. This is the default. none Disable all warning messages. filename-with-nuls "%s: file name read contains nul character" alone-zero-block "A lone zero block at %s" Keywords applicable for tar --create: cachedir "%s: contains a cache directory tag %s; %s" file-shrank "%s: File shrank by %s bytes; padding with zeros" xdev "%s: file is on a different filesystem; not dumped" file-ignored "%s: Unknown file type; file ignored" "%s: socket ignored" "%s: door ignored" file-unchanged "%s: file is unchanged; not dumped" ignore-archive "%s: archive cannot contain itself; not dumped" file-removed "%s: File removed before we read it" file-changed "%s: file changed as we read it" failed-read Suppresses warnings about unreadable files or directories. This keyword applies only if used together with the --ignore-failed-read option. Keywords applicable for tar --extract: existing-file "%s: skipping existing file" timestamp "%s: implausibly old time stamp %s" "%s: time stamp %s is %s s in the future" contiguous-cast "Extracting contiguous files as regular files" symlink-cast "Attempting extraction of symbolic links as hard links" unknown-cast "%s: Unknown file type '%c', extracted as normal file" ignore-newer "Current %s is newer or same age" unknown-keyword "Ignoring unknown extended header keyword '%s'" decompress-program Controls verbose description of failures occurring when trying to run alternative decompressor programs. This warning is disabled by default (unless --verbose is used). A common example of what you can get when using this warning is: $ tar --warning=decompress-program -x -f archive.Z tar (child): cannot run compress: No such file or directory tar (child): trying gzip This means that tar first tried to decompress archive.Z using compress, and, when that failed, switched to gzip. record-size "Record size = %lu blocks" Keywords controlling incremental extraction: rename-directory "%s: Directory has been renamed from %s" "%s: Directory has been renamed" new-directory "%s: Directory is new" xdev "%s: directory is on a different device: not purging" bad-dumpdir "Malformed dumpdir: 'X' never used" -w, --interactive, --confirmation Ask for confirmation for every action. Compatibility options -o When creating, same as --old-archive. When extracting, same as --no-same-owner. Size suffixes Suffix Units Byte Equivalent b Blocks SIZE x 512 B Kilobytes SIZE x 1024 c Bytes SIZE G Gigabytes SIZE x 1024^3 K Kilobytes SIZE x 1024 k Kilobytes SIZE x 1024 M Megabytes SIZE x 1024^2 P Petabytes SIZE x 1024^5 T Terabytes SIZE x 1024^4 w Words SIZE x 2 RETURN VALUE top Tar's exit code indicates whether it was able to successfully perform the requested operation, and if not, what kind of error occurred. 0 Successful termination. 1 Some files differ. If tar was invoked with the --compare (--diff, -d) command line option, this means that some files in the archive differ from their disk counterparts. If tar was given one of the --create, --append or --update options, this exit code means that some files were changed while being archived and so the resulting archive does not contain the exact copy of the file set. 2 Fatal error. This means that some fatal, unrecoverable error occurred. If a subprocess that had been invoked by tar exited with a nonzero exit code, tar itself exits with that code as well. This can happen, for example, if a compression option (e.g. -z) was used and the external compressor program failed. Another example is rmt failure during backup to a remote device. SEE ALSO top bzip2(1), compress(1), gzip(1), lzma(1), lzop(1), rmt(8), symlink(7), xz(1), zstd(1). Complete tar manual: run info tar or use emacs(1) info mode to read it. Online copies of GNU tar documentation in various formats can be found at: https://www.gnu.org/software/tar/manual BUG REPORTS top Report bugs to <bug-tar@gnu.org>. COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://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. COLOPHON top This page is part of the tar (an archiver program) project. Information about the project can be found at http://savannah.gnu.org/projects/tar/. If you have a bug report for this manual page, see http://savannah.gnu.org/bugs/?group=tar. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/tar.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-12.) 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 TAR July 11, 2022 TAR(1) Pages that refer to this page: attr(1), dpkg-deb(1), dpkg-source(1), machinectl(1), rsync(1), st(4), suffixes(7), symlink(7), cupsd-helper(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: tar all files in the current folder and ask for user confirmation before creating the tar ball Bash Command:<START>find . -ok tar rvf backup {} \;<END>
tar all the regular java files to myfile.tar
find . -type f -name "*.java" | xargs tar cvf myfile.tar
['find', 'tar', 'xargs']
Output a Bash command to accomplish the following task. Task: tar all the regular java files to myfile.tar Bash Command:<START>find . -type f -name "*.java" | xargs tar cvf myfile.tar<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 # tar\n\n> Archiving utility.\n> Often combined with a compression method, such as `gzip` or `bzip2`.\n> More information: <https://www.gnu.org/software/tar>.\n\n- [c]reate an archive and write it to a [f]ile:\n\n`tar cf {{path/to/target.tar}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive and write it to a [f]ile:\n\n`tar czf {{path/to/target.tar.gz}} {{path/to/file1 path/to/file2 ...}}`\n\n- [c]reate a g[z]ipped archive from a directory using relative paths:\n\n`tar czf {{path/to/target.tar.gz}} --directory={{path/to/directory}} .`\n\n- E[x]tract a (compressed) archive [f]ile into the current directory [v]erbosely:\n\n`tar xvf {{path/to/source.tar[.gz|.bz2|.xz]}}`\n\n- E[x]tract a (compressed) archive [f]ile into the target directory:\n\n`tar xf {{path/to/source.tar[.gz|.bz2|.xz]}} --directory={{path/to/directory}}`\n\n- [c]reate a compressed archive and write it to a [f]ile, using the file extension to [a]utomatically determine the compression program:\n\n`tar caf {{path/to/target.tar.xz}} {{path/to/file1 path/to/file2 ...}}`\n\n- Lis[t] the contents of a tar [f]ile [v]erbosely:\n\n`tar tvf {{path/to/source.tar}}`\n\n- E[x]tract files matching a pattern from an archive [f]ile:\n\n`tar xf {{path/to/source.tar}} --wildcards "{{*.html}}"`\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 Task: tar all the regular java files to myfile.tar Bash Command:<START>find . -type f -name "*.java" | xargs tar cvf myfile.tar<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. tar(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tar(1) Linux manual page NAME | SYNOPSIS | NOTE | DESCRIPTION | OPTIONS | RETURN VALUE | SEE ALSO | BUG REPORTS | COPYRIGHT | COLOPHON TAR(1) GNU TAR Manual TAR(1) NAME top tar - an archiving utility SYNOPSIS top Traditional usage tar {A|c|d|r|t|u|x}[GnSkUWOmpsMBiajJzZhPlRvwo] [ARG...] UNIX-style usage tar -A [OPTIONS] -f ARCHIVE ARCHIVE... tar -c [-f ARCHIVE] [OPTIONS] [FILE...] tar -d [-f ARCHIVE] [OPTIONS] [FILE...] tar -r [-f ARCHIVE] [OPTIONS] [FILE...] tar -t [-f ARCHIVE] [OPTIONS] [MEMBER...] tar -u [-f ARCHIVE] [OPTIONS] [FILE...] tar -x [-f ARCHIVE] [OPTIONS] [MEMBER...] GNU-style usage tar {--catenate|--concatenate} [OPTIONS] --file ARCHIVE ARCHIVE... tar --create [--file ARCHIVE] [OPTIONS] [FILE...] tar {--diff|--compare} [--file ARCHIVE] [OPTIONS] [FILE...] tar --delete [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --append [--file ARCHIVE] [OPTIONS] [FILE...] tar --list [--file ARCHIVE] [OPTIONS] [MEMBER...] tar --test-label [--file ARCHIVE] [OPTIONS] [LABEL...] tar --update [--file ARCHIVE] [OPTIONS] [FILE...] tar {--extract|--get} [--file ARCHIVE] [OPTIONS] [MEMBER...] NOTE top This manpage is a short description of GNU tar. For a detailed discussion, including examples and usage recommendations, refer to the GNU Tar Manual available in texinfo format. If the info reader and the tar documentation are properly installed on your system, the command info tar should give you access to the complete manual. You can also view the manual using the info mode in emacs(1), or find it in various formats online at https://www.gnu.org/software/tar/manual If any discrepancies occur between this manpage and the GNU Tar Manual, the later shall be considered the authoritative source. DESCRIPTION top GNU tar is an archiving program designed to store multiple files in a single file (an archive), and to manipulate such archives. The archive can be either a regular file or a device (e.g. a tape drive, hence the name of the program, which stands for tape archiver), which can be located either on the local or on a remote machine. Option styles Options to GNU tar can be given in three different styles. In traditional style, the first argument is a cluster of option letters and all subsequent arguments supply arguments to those options that require them. The arguments are read in the same order as the option letters. Any command line words that remain after all options have been processed are treated as non-option arguments: file or archive member names. For example, the c option requires creating the archive, the v option requests the verbose operation, and the f option takes an argument that sets the name of the archive to operate upon. The following command, written in the traditional style, instructs tar to store all files from the directory /etc into the archive file etc.tar, verbosely listing the files being archived: tar cfv etc.tar /etc In UNIX or short-option style, each option letter is prefixed with a single dash, as in other command line utilities. If an option takes an argument, the argument follows it, either as a separate command line word, or immediately following the option. However, if the option takes an optional argument, the argument must follow the option letter without any intervening whitespace, as in -g/tmp/snar.db. Any number of options not taking arguments can be clustered together after a single dash, e.g. -vkp. An option that takes an argument (whether mandatory or optional) can appear at the end of such a cluster, e.g. -vkpf a.tar. The example command above written in the short-option style could look like: tar -cvf etc.tar /etc or tar -c -v -f etc.tar /etc In GNU or long-option style, each option begins with two dashes and has a meaningful name, consisting of lower-case letters and dashes. When used, the long option can be abbreviated to its initial letters, provided that this does not create ambiguity. Arguments to long options are supplied either as a separate command line word, immediately following the option, or separated from the option by an equals sign with no intervening whitespace. Optional arguments must always use the latter method. Here are several ways of writing the example command in this style: tar --create --file etc.tar --verbose /etc or (abbreviating some options): tar --cre --file=etc.tar --verb /etc The options in all three styles can be intermixed, although doing so with old options is not encouraged. Operation mode The options listed in the table below tell GNU tar what operation it is to perform. Exactly one of them must be given. The meaning of non-option arguments depends on the operation mode requested. -A, --catenate, --concatenate Append archives to the end of another archive. The arguments are treated as the names of archives to append. All archives must be of the same format as the archive they are appended to, otherwise the resulting archive might be unusable with non-GNU implementations of tar. Notice also that when more than one archive is given, the members from archives other than the first one will be accessible in the resulting archive only when using the -i (--ignore-zeros) option. Compressed archives cannot be concatenated. -c, --create Create a new archive. Arguments supply the names of the files to be archived. Directories are archived recursively, unless the --no-recursion option is given. -d, --diff, --compare Find differences between archive and file system. The arguments are optional and specify archive members to compare. If not given, the current working directory is assumed. --delete Delete from the archive. The arguments supply names of the archive members to be removed. At least one argument must be given. This option does not operate on compressed archives. There is no short option equivalent. -r, --append Append files to the end of an archive. Arguments have the same meaning as for -c (--create). -t, --list List the contents of an archive. Arguments are optional. When given, they specify the names of the members to list. --test-label Test the archive volume label and exit. When used without arguments, it prints the volume label (if any) and exits with status 0. When one or more command line arguments are given. tar compares the volume label with each argument. It exits with code 0 if a match is found, and with code 1 otherwise. No output is displayed, unless used together with the -v (--verbose) option. There is no short option equivalent for this option. -u, --update Append files which are newer than the corresponding copy in the archive. Arguments have the same meaning as with the -c and -r options. Notice, that newer files don't replace their old archive copies, but instead are appended to the end of archive. The resulting archive can thus contain several members of the same name, corresponding to various versions of the same file. -x, --extract, --get Extract files from an archive. Arguments are optional. When given, they specify names of the archive members to be extracted. --show-defaults Show built-in defaults for various tar options and exit. -?, --help Display a short option summary and exit. --usage Display a list of available options and exit. --version Print program version and copyright information and exit. OPTIONS top Operation modifiers --check-device Check device numbers when creating incremental archives (default). -g, --listed-incremental=FILE Handle new GNU-format incremental backups. FILE is the name of a snapshot file, where tar stores additional information which is used to decide which files changed since the previous incremental dump and, consequently, must be dumped again. If FILE does not exist when creating an archive, it will be created and all files will be added to the resulting archive (the level 0 dump). To create incremental archives of non-zero level N, you need a copy of the snapshot file created for level N-1, and use it as FILE. When listing or extracting, the actual content of FILE is not inspected, it is needed only due to syntactical requirements. It is therefore common practice to use /dev/null in its place. --hole-detection=METHOD Use METHOD to detect holes in sparse files. This option implies --sparse. Valid values for METHOD are seek and raw. Default is seek with fallback to raw when not applicable. -G, --incremental Handle old GNU-format incremental backups. --ignore-failed-read Do not exit with nonzero on unreadable files. --level=NUMBER Set dump level for a created listed-incremental archive. Currently only --level=0 is meaningful: it instructs tar to truncate the snapshot file before dumping, thereby forcing a level 0 dump. -n, --seek Assume the archive is seekable. Normally tar determines automatically whether the archive can be seeked or not. This option is intended for use in cases when such recognition fails. It takes effect only if the archive is open for reading (e.g. with --list or --extract options). --no-check-device Do not check device numbers when creating incremental archives. --no-seek Assume the archive is not seekable. --occurrence[=N] Process only the Nth occurrence of each file in the archive. This option is valid only when used with one of the following subcommands: --delete, --diff, --extract or --list and when a list of files is given either on the command line or via the -T option. The default N is 1. --restrict Disable the use of some potentially harmful options. --sparse-version=MAJOR[.MINOR] Set which version of the sparse format to use. This option implies --sparse. Valid argument values are 0.0, 0.1, and 1.0. For a detailed discussion of sparse formats, refer to the GNU Tar Manual, appendix D, "Sparse Formats". Using the info reader, it can be accessed running the following command: info tar 'Sparse Formats'. -S, --sparse Handle sparse files efficiently. Some files in the file system may have segments which were actually never written (quite often these are database files created by such systems as DBM). When given this option, tar attempts to determine if the file is sparse prior to archiving it, and if so, to reduce the resulting archive size by not dumping empty parts of the file. Overwrite control These options control tar actions when extracting a file over an existing copy on disk. -k, --keep-old-files Don't replace existing files when extracting. --keep-newer-files Don't replace existing files that are newer than their archive copies. --keep-directory-symlink Don't replace existing symlinks to directories when extracting. --no-overwrite-dir Preserve metadata of existing directories. --one-top-level[=DIR] Extract all files into DIR, or, if used without argument, into a subdirectory named by the base name of the archive (minus standard compression suffixes recognizable by --auto-compress). --overwrite Overwrite existing files when extracting. --overwrite-dir Overwrite metadata of existing directories when extracting (default). --recursive-unlink Recursively remove all files in the directory prior to extracting it. --remove-files Remove files from disk after adding them to the archive. --skip-old-files Don't replace existing files when extracting, silently skip over them. -U, --unlink-first Remove each file prior to extracting over it. -W, --verify Verify the archive after writing it. Output stream selection --ignore-command-error Ignore subprocess exit codes. --no-ignore-command-error Treat non-zero exit codes of children as error (default). -O, --to-stdout Extract files to standard output. --to-command=COMMAND Pipe extracted files to COMMAND. The argument is the pathname of an external program, optionally with command line arguments. The program will be invoked and the contents of the file being extracted supplied to it on its standard input. Additional data will be supplied via the following environment variables: TAR_FILETYPE Type of the file. It is a single letter with the following meaning: f Regular file d Directory l Symbolic link h Hard link b Block device c Character device Currently only regular files are supported. TAR_MODE File mode, an octal number. TAR_FILENAME The name of the file. TAR_REALNAME Name of the file as stored in the archive. TAR_UNAME Name of the file owner. TAR_GNAME Name of the file owner group. TAR_ATIME Time of last access. It is a decimal number, representing seconds since the Epoch. If the archive provides times with nanosecond precision, the nanoseconds are appended to the timestamp after a decimal point. TAR_MTIME Time of last modification. TAR_CTIME Time of last status change. TAR_SIZE Size of the file. TAR_UID UID of the file owner. TAR_GID GID of the file owner. Additionally, the following variables contain information about tar operation mode and the archive being processed: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. Handling of file attributes --atime-preserve[=METHOD] Preserve access times on dumped files, either by restoring the times after reading (METHOD=replace, this is the default) or by not setting the times in the first place (METHOD=system). --delay-directory-restore Delay setting modification times and permissions of extracted directories until the end of extraction. Use this option when extracting from an archive which has unusual member ordering. --group=NAME[:GID] Force NAME as group for added files. If GID is not supplied, NAME can be either a user name or numeric GID. In this case the missing part (GID or name) will be inferred from the current host's group database. When used with --group-map=FILE, affects only those files whose owner group is not listed in FILE. --group-map=FILE Read group translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single group. It must consist of two fields, delimited by any amount of whitespace: OLDGRP NEWGRP[:NEWGID] OLDGRP is either a valid group name or a GID prefixed with +. Unless NEWGID is supplied, NEWGRP must also be either a valid group name or a +GID. Otherwise, both NEWGRP and NEWGID need not be listed in the system group database. As a result, each input file with owner group OLDGRP will be stored in archive with owner group NEWGRP and GID NEWGID. --mode=CHANGES Force symbolic mode CHANGES for added files. --mtime=DATE-OR-FILE Set mtime for added files. DATE-OR-FILE is either a date/time in almost arbitrary format, or the name of an existing file. In the latter case the mtime of that file will be used. -m, --touch Don't extract file modified time. --no-delay-directory-restore Cancel the effect of the prior --delay-directory-restore option. --no-same-owner Extract files as yourself (default for ordinary users). --no-same-permissions Apply the user's umask when extracting permissions from the archive (default for ordinary users). --numeric-owner Always use numbers for user/group names. --owner=NAME[:UID] Force NAME as owner for added files. If UID is not supplied, NAME can be either a user name or numeric UID. In this case the missing part (UID or name) will be inferred from the current host's user database. When used with --owner-map=FILE, affects only those files whose owner is not listed in FILE. --owner-map=FILE Read owner translation map from FILE. Empty lines are ignored. Comments are introduced with # sign and extend to the end of line. Each non-empty line in FILE defines translation for a single UID. It must consist of two fields, delimited by any amount of whitespace: OLDUSR NEWUSR[:NEWUID] OLDUSR is either a valid user name or a UID prefixed with +. Unless NEWUID is supplied, NEWUSR must also be either a valid user name or a +UID. Otherwise, both NEWUSR and NEWUID need not be listed in the system user database. As a result, each input file owned by OLDUSR will be stored in archive with owner name NEWUSR and UID NEWUID. -p, --preserve-permissions, --same-permissions Set permissions of extracted files to those recorded in the archive (default for superuser). --same-owner Try extracting files with the same ownership as exists in the archive (default for superuser). -s, --preserve-order, --same-order Tell tar that the list of file names to process is sorted in the same order as the files in the archive. --sort=ORDER When creating an archive, sort directory entries according to ORDER, which is one of none, name, or inode. The default is --sort=none, which stores archive members in the same order as returned by the operating system. Using --sort=name ensures the member ordering in the created archive is uniform and reproducible. Using --sort=inode reduces the number of disk seeks made when creating the archive and thus can considerably speed up archivation. This sorting order is supported only if the underlying system provides the necessary information. Extended file attributes --acls Enable POSIX ACLs support. --no-acls Disable POSIX ACLs support. --selinux Enable SELinux context support. --no-selinux Disable SELinux context support. --xattrs Enable extended attributes support. --no-xattrs Disable extended attributes support. --xattrs-exclude=PATTERN Specify the exclude pattern for xattr keys. PATTERN is a globbing pattern, e.g. --xattrs-exclude='user.*' to include only attributes from the user namespace. --xattrs-include=PATTERN Specify the include pattern for xattr keys. PATTERN is a globbing pattern. Device selection and switching -f, --file=ARCHIVE Use archive file or device ARCHIVE. If this option is not given, tar will first examine the environment variable `TAPE'. If it is set, its value will be used as the archive name. Otherwise, tar will assume the compiled-in default. The default value can be inspected either using the --show-defaults option, or at the end of the tar --help output. An archive name that has a colon in it specifies a file or device on a remote machine. The part before the colon is taken as the machine name or IP address, and the part after it as the file or device pathname, e.g.: --file=remotehost:/dev/sr0 An optional username can be prefixed to the hostname, placing a @ sign between them. By default, the remote host is accessed via the rsh(1) command. Nowadays it is common to use ssh(1) instead. You can do so by giving the following command line option: --rsh-command=/usr/bin/ssh The remote machine should have the rmt(8) command installed. If its pathname does not match tar's default, you can inform tar about the correct pathname using the --rmt-command option. --force-local Archive file is local even if it has a colon. -F, --info-script=COMMAND, --new-volume-script=COMMAND Run COMMAND at the end of each tape (implies -M). The command can include arguments. When started, it will inherit tar's environment plus the following variables: TAR_VERSION GNU tar version number. TAR_ARCHIVE The name of the archive tar is processing. TAR_BLOCKING_FACTOR Current blocking factor, i.e. number of 512-byte blocks in a record. TAR_VOLUME Ordinal number of the volume tar is processing (set if reading a multi-volume archive). TAR_FORMAT Format of the archive being processed. One of: gnu, oldgnu, posix, ustar, v7. TAR_SUBCOMMAND A short option (with a leading dash) describing the operation tar is executing. TAR_FD File descriptor which can be used to communicate the new volume name to tar. If the info script fails, tar exits; otherwise, it begins writing the next volume. -L, --tape-length=N Change tape after writing Nx1024 bytes. If N is followed by a size suffix (see the subsection Size suffixes below), the suffix specifies the multiplicative factor to be used instead of 1024. This option implies -M. -M, --multi-volume Create/list/extract multi-volume archive. --rmt-command=COMMAND Use COMMAND instead of rmt when accessing remote archives. See the description of the -f option, above. --rsh-command=COMMAND Use COMMAND instead of rsh when accessing remote archives. See the description of the -f option, above. --volno-file=FILE When this option is used in conjunction with --multi-volume, tar will keep track of which volume of a multi-volume archive it is working in FILE. Device blocking -b, --blocking-factor=BLOCKS Set record size to BLOCKSx512 bytes. -B, --read-full-records When listing or extracting, accept incomplete input records after end-of-file marker. -i, --ignore-zeros Ignore zeroed blocks in archive. Normally two consecutive 512-blocks filled with zeroes mean EOF and tar stops reading after encountering them. This option instructs it to read further and is useful when reading archives created with the -A option. --record-size=NUMBER Set record size. NUMBER is the number of bytes per record. It must be multiple of 512. It can can be suffixed with a size suffix, e.g. --record-size=10K, for 10 Kilobytes. See the subsection Size suffixes, for a list of valid suffixes. Archive format selection -H, --format=FORMAT Create archive of the given format. Valid formats are: gnu GNU tar 1.13.x format oldgnu GNU format as per tar <= 1.12. pax, posix POSIX 1003.1-2001 (pax) format. ustar POSIX 1003.1-1988 (ustar) format. v7 Old V7 tar format. --old-archive, --portability Same as --format=v7. --pax-option=keyword[[:]=value][,keyword[[:]=value]]... Control pax keywords when creating PAX archives (-H pax). This option is equivalent to the -o option of the pax(1) utility. --posix Same as --format=posix. -V, --label=TEXT Create archive with volume name TEXT. If listing or extracting, use TEXT as a globbing pattern for volume name. Compression options -a, --auto-compress Use archive suffix to determine the compression program. -I, --use-compress-program=COMMAND Filter data through COMMAND. It must accept the -d option, for decompression. The argument can contain command line options. -j, --bzip2 Filter the archive through bzip2(1). -J, --xz Filter the archive through xz(1). --lzip Filter the archive through lzip(1). --lzma Filter the archive through lzma(1). --lzop Filter the archive through lzop(1). --no-auto-compress Do not use archive suffix to determine the compression program. -z, --gzip, --gunzip, --ungzip Filter the archive through gzip(1). -Z, --compress, --uncompress Filter the archive through compress(1). --zstd Filter the archive through zstd(1). Local file selection --add-file=FILE Add FILE to the archive (useful if its name starts with a dash). --backup[=CONTROL] Backup before removal. The CONTROL argument, if supplied, controls the backup policy. Its valid values are: none, off Never make backups. t, numbered Make numbered backups. nil, existing Make numbered backups if numbered backups exist, simple backups otherwise. never, simple Always make simple backups If CONTROL is not given, the value is taken from the VERSION_CONTROL environment variable. If it is not set, existing is assumed. -C, --directory=DIR Change to DIR before performing any operations. This option is order-sensitive, i.e. it affects all options that follow. --exclude=PATTERN Exclude files matching PATTERN, a glob(3)-style wildcard pattern. --exclude-backups Exclude backup and lock files. --exclude-caches Exclude contents of directories containing file CACHEDIR.TAG, except for the tag file itself. --exclude-caches-all Exclude directories containing file CACHEDIR.TAG and the file itself. --exclude-caches-under Exclude everything under directories containing CACHEDIR.TAG --exclude-ignore=FILE Before dumping a directory, see if it contains FILE. If so, read exclusion patterns from this file. The patterns affect only the directory itself. --exclude-ignore-recursive=FILE Same as --exclude-ignore, except that patterns from FILE affect both the directory and all its subdirectories. --exclude-tag=FILE Exclude contents of directories containing FILE, except for FILE itself. --exclude-tag-all=FILE Exclude directories containing FILE. --exclude-tag-under=FILE Exclude everything under directories containing FILE. --exclude-vcs Exclude version control system directories. --exclude-vcs-ignores Exclude files that match patterns read from VCS-specific ignore files. Supported files are: .cvsignore, .gitignore, .bzrignore, and .hgignore. -h, --dereference Follow symlinks; archive and dump the files they point to. --hard-dereference Follow hard links; archive and dump the files they refer to. -K, --starting-file=MEMBER Begin at the given member in the archive. --newer-mtime=DATE Work on files whose data changed after the DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --no-null Disable the effect of the previous --null option. --no-recursion Avoid descending automatically in directories. --no-unquote Do not unquote input file or member names. --no-verbatim-files-from Treat each line read from a file list as if it were supplied in the command line. I.e., leading and trailing whitespace is removed and, if the resulting string begins with a dash, it is treated as tar command line option. This is the default behavior. The --no-verbatim-files-from option is provided as a way to restore it after --verbatim-files-from option. This option is positional: it affects all --files-from options that occur after it in, until --verbatim-files-from option or end of line, whichever occurs first. It is implied by the --no-null option. --null Instruct subsequent -T options to read null-terminated names verbatim (disables special handling of names that start with a dash). See also --verbatim-files-from. -N, --newer=DATE, --after-date=DATE Only store files newer than DATE. If DATE starts with / or . it is taken to be a file name; the mtime of that file is used as the date. --one-file-system Stay in local file system when creating archive. -P, --absolute-names Don't strip leading slashes from file names when creating archives. --recursion Recurse into directories (default). --suffix=STRING Backup before removal, override usual suffix. Default suffix is ~, unless overridden by environment variable SIMPLE_BACKUP_SUFFIX. -T, --files-from=FILE Get names to extract or create from FILE. Unless specified otherwise, the FILE must contain a list of names separated by ASCII LF (i.e. one name per line). The names read are handled the same way as command line arguments. They undergo quote removal and word splitting, and any string that starts with a - is handled as tar command line option. If this behavior is undesirable, it can be turned off using the --verbatim-files-from option. The --null option instructs tar that the names in FILE are separated by ASCII NUL character, instead of LF. It is useful if the list is generated by find(1) -print0 predicate. --unquote Unquote file or member names (default). --verbatim-files-from Treat each line obtained from a file list as a file name, even if it starts with a dash. File lists are supplied with the --files-from (-T) option. The default behavior is to handle names supplied in file lists as if they were typed in the command line, i.e. any names starting with a dash are treated as tar options. The --verbatim-files-from option disables this behavior. This option affects all --files-from options that occur after it in the command line. Its effect is reverted by the --no-verbatim-files-from option. This option is implied by the --null option. See also --add-file. -X, --exclude-from=FILE Exclude files matching patterns listed in FILE. File name transformations --strip-components=NUMBER Strip NUMBER leading components from file names on extraction. --transform=EXPRESSION, --xform=EXPRESSION Use sed replace EXPRESSION to transform file names. File name matching options These options affect both exclude and include patterns. --anchored Patterns match file name start. --ignore-case Ignore case. --no-anchored Patterns match after any / (default for exclusion). --no-ignore-case Case sensitive matching (default). --no-wildcards Verbatim string matching. --no-wildcards-match-slash Wildcards do not match /. --wildcards Use wildcards (default for exclusion). --wildcards-match-slash Wildcards match / (default for exclusion). Informative output --checkpoint[=N] Display progress messages every Nth record (default 10). --checkpoint-action=ACTION Run ACTION on each checkpoint. --clamp-mtime Only set time when the file is more recent than what was given with --mtime. --full-time Print file time to its full resolution. --index-file=FILE Send verbose output to FILE. -l, --check-links Print a message if not all links are dumped. --no-quote-chars=STRING Disable quoting for characters from STRING. --quote-chars=STRING Additionally quote characters from STRING. --quoting-style=STYLE Set quoting style for file and member names. Valid values for STYLE are literal, shell, shell-always, c, c-maybe, escape, locale, clocale. -R, --block-number Show block number within archive with each message. --show-omitted-dirs When listing or extracting, list each directory that does not match search criteria. --show-transformed-names, --show-stored-names Show file or archive names after transformation by --strip and --transform options. --totals[=SIGNAL] Print total bytes after processing the archive. If SIGNAL is given, print total bytes when this signal is delivered. Allowed signals are: SIGHUP, SIGQUIT, SIGINT, SIGUSR1, and SIGUSR2. The SIG prefix can be omitted. --utc Print file modification times in UTC. -v, --verbose Verbosely list files processed. Each instance of this option on the command line increases the verbosity level by one. The maximum verbosity level is 3. For a detailed discussion of how various verbosity levels affect tar's output, please refer to GNU Tar Manual, subsection 2.5.2 "The '--verbose' Option". --warning=KEYWORD Enable or disable warning messages identified by KEYWORD. The messages are suppressed if KEYWORD is prefixed with no- and enabled otherwise. Multiple --warning options accumulate. Keywords controlling general tar operation: all Enable all warning messages. This is the default. none Disable all warning messages. filename-with-nuls "%s: file name read contains nul character" alone-zero-block "A lone zero block at %s" Keywords applicable for tar --create: cachedir "%s: contains a cache directory tag %s; %s" file-shrank "%s: File shrank by %s bytes; padding with zeros" xdev "%s: file is on a different filesystem; not dumped" file-ignored "%s: Unknown file type; file ignored" "%s: socket ignored" "%s: door ignored" file-unchanged "%s: file is unchanged; not dumped" ignore-archive "%s: archive cannot contain itself; not dumped" file-removed "%s: File removed before we read it" file-changed "%s: file changed as we read it" failed-read Suppresses warnings about unreadable files or directories. This keyword applies only if used together with the --ignore-failed-read option. Keywords applicable for tar --extract: existing-file "%s: skipping existing file" timestamp "%s: implausibly old time stamp %s" "%s: time stamp %s is %s s in the future" contiguous-cast "Extracting contiguous files as regular files" symlink-cast "Attempting extraction of symbolic links as hard links" unknown-cast "%s: Unknown file type '%c', extracted as normal file" ignore-newer "Current %s is newer or same age" unknown-keyword "Ignoring unknown extended header keyword '%s'" decompress-program Controls verbose description of failures occurring when trying to run alternative decompressor programs. This warning is disabled by default (unless --verbose is used). A common example of what you can get when using this warning is: $ tar --warning=decompress-program -x -f archive.Z tar (child): cannot run compress: No such file or directory tar (child): trying gzip This means that tar first tried to decompress archive.Z using compress, and, when that failed, switched to gzip. record-size "Record size = %lu blocks" Keywords controlling incremental extraction: rename-directory "%s: Directory has been renamed from %s" "%s: Directory has been renamed" new-directory "%s: Directory is new" xdev "%s: directory is on a different device: not purging" bad-dumpdir "Malformed dumpdir: 'X' never used" -w, --interactive, --confirmation Ask for confirmation for every action. Compatibility options -o When creating, same as --old-archive. When extracting, same as --no-same-owner. Size suffixes Suffix Units Byte Equivalent b Blocks SIZE x 512 B Kilobytes SIZE x 1024 c Bytes SIZE G Gigabytes SIZE x 1024^3 K Kilobytes SIZE x 1024 k Kilobytes SIZE x 1024 M Megabytes SIZE x 1024^2 P Petabytes SIZE x 1024^5 T Terabytes SIZE x 1024^4 w Words SIZE x 2 RETURN VALUE top Tar's exit code indicates whether it was able to successfully perform the requested operation, and if not, what kind of error occurred. 0 Successful termination. 1 Some files differ. If tar was invoked with the --compare (--diff, -d) command line option, this means that some files in the archive differ from their disk counterparts. If tar was given one of the --create, --append or --update options, this exit code means that some files were changed while being archived and so the resulting archive does not contain the exact copy of the file set. 2 Fatal error. This means that some fatal, unrecoverable error occurred. If a subprocess that had been invoked by tar exited with a nonzero exit code, tar itself exits with that code as well. This can happen, for example, if a compression option (e.g. -z) was used and the external compressor program failed. Another example is rmt failure during backup to a remote device. SEE ALSO top bzip2(1), compress(1), gzip(1), lzma(1), lzop(1), rmt(8), symlink(7), xz(1), zstd(1). Complete tar manual: run info tar or use emacs(1) info mode to read it. Online copies of GNU tar documentation in various formats can be found at: https://www.gnu.org/software/tar/manual BUG REPORTS top Report bugs to <bug-tar@gnu.org>. COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://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. COLOPHON top This page is part of the tar (an archiver program) project. Information about the project can be found at http://savannah.gnu.org/projects/tar/. If you have a bug report for this manual page, see http://savannah.gnu.org/bugs/?group=tar. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/tar.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-12.) 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 TAR July 11, 2022 TAR(1) Pages that refer to this page: attr(1), dpkg-deb(1), dpkg-source(1), machinectl(1), rsync(1), st(4), suffixes(7), symlink(7), cupsd-helper(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. 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. Task: tar all the regular java files to myfile.tar Bash Command:<START>find . -type f -name "*.java" | xargs tar cvf myfile.tar<END>
test if the 2nd column in file A is in the reverse order of the second column of file B
diff --brief <(awk '{print $2}' A) <(tac B | awk '{print $2}')
['awk', 'tac', 'diff']
Output a Bash command to accomplish the following task. Task: test if the 2nd column in file A is in the reverse order of the second column of file B Bash Command:<START>diff --brief <(awk '{print $2}' A) <(tac B | awk '{print $2}')<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # awk\n\n> A versatile programming language for working on files.\n> More information: <https://github.com/onetrueawk/awk>.\n\n- Print the fifth column (a.k.a. field) in a space-separated file:\n\n`awk '{print $5}' {{path/to/file}}`\n\n- Print the second column of the lines containing "foo" in a space-separated file:\n\n`awk '/{{foo}}/ {print $2}' {{path/to/file}}`\n\n- Print the last column of each line in a file, using a comma (instead of space) as a field separator:\n\n`awk -F ',' '{print $NF}' {{path/to/file}}`\n\n- Sum the values in the first column of a file and print the total:\n\n`awk '{s+=$1} END {print s}' {{path/to/file}}`\n\n- Print every third line starting from the first line:\n\n`awk 'NR%3==1' {{path/to/file}}`\n\n- Print different values based on conditions:\n\n`awk '{if ($1 == "foo") print "Exact match foo"; else if ($1 ~ "bar") print "Partial match bar"; else print "Baz"}' {{path/to/file}}`\n\n- Print all lines where the 10th column value equals the specified value:\n\n`awk '($10 == {{value}})'`\n\n- Print all the lines which the 10th column value is between a min and a max:\n\n`awk '($10 >= {{min_value}} && $10 <= {{max_value}})'`\n # tac\n\n> Display and concatenate files with lines in reversed order.\n> See also: `cat`.\n> More information: <https://www.gnu.org/software/coreutils/tac>.\n\n- Concatenate specific files in reversed order:\n\n`tac {{path/to/file1 path/to/file2 ...}}`\n\n- Display `stdin` in reversed order:\n\n`{{cat path/to/file}} | tac`\n\n- Use a specific separator:\n\n`tac --separator {{,}} {{path/to/file1 path/to/file2 ...}}`\n\n- Use a specific regex as a separator:\n\n`tac --regex --separator {{[,;]}} {{path/to/file1 path/to/file2 ...}}`\n\n- Use a separator before each file:\n\n`tac --before {{path/to/file1 path/to/file2 ...}}`\n # diff\n\n> Compare files and directories.\n> More information: <https://man7.org/linux/man-pages/man1/diff.1.html>.\n\n- Compare files (lists changes to turn `old_file` into `new_file`):\n\n`diff {{old_file}} {{new_file}}`\n\n- Compare files, ignoring [w]hite spaces:\n\n`diff {{-w|--ignore-all-space}} {{old_file}} {{new_file}}`\n\n- Compare files, showing the differences side by side:\n\n`diff {{-y|--side-by-side}} {{old_file}} {{new_file}}`\n\n- Compare files, showing the differences in [u]nified format (as used by `git diff`):\n\n`diff {{-u|--unified}} {{old_file}} {{new_file}}`\n\n- Compare directories [r]ecursively (shows names for differing files/directories as well as changes made to files):\n\n`diff {{-r|--recursive}} {{old_directory}} {{new_directory}}`\n\n- Compare directories, only showing the names of files that differ:\n\n`diff {{-r|--recursive}} {{-q|--brief}} {{old_directory}} {{new_directory}}`\n\n- Create a patch file for Git from the differences of two text files, treating nonexistent files as empty:\n\n`diff {{-a|--text}} {{-u|--unified}} {{-N|--new-file}} {{old_file}} {{new_file}} > {{diff.patch}}`\n\n- Compare files, showing output in color and try hard to find smaller set of changes:\n\n`diff {{-d|--minimal}} --color=always {{old_file}} {{new_file}}`\n Task: test if the 2nd column in file A is in the reverse order of the second column of file B Bash Command:<START>diff --brief <(awk '{print $2}' A) <(tac B | awk '{print $2}')<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: awk(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training awk(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 AWK(1P) POSIX Programmer's Manual AWK(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 awk pattern scanning and processing language SYNOPSIS top awk [-F sepstring] [-v assignment]... program [argument...] awk [-F sepstring] -f progfile [-f progfile]... [-v assignment]... [argument...] DESCRIPTION top The awk utility shall execute programs written in the awk programming language, which is specialized for textual data manipulation. An awk program is a sequence of patterns and corresponding actions. When input is read that matches a pattern, the action associated with that pattern is carried out. Input shall be interpreted as a sequence of records. By default, a record is a line, less its terminating <newline>, but this can be changed by using the RS built-in variable. Each record of input shall be matched in turn against each pattern in the program. For each pattern matched, the associated action shall be executed. The awk utility shall interpret each input record as a sequence of fields where, by default, a field is a string of non-<blank> non-<newline> characters. This default <blank> and <newline> field delimiter can be changed by using the FS built-in variable or the -F sepstring option. The awk utility shall denote the first field in a record $1, the second $2, and so on. The symbol $0 shall refer to the entire record; setting any other field causes the re-evaluation of $0. Assigning to $0 shall reset the values of all other fields and the NF built-in variable. OPTIONS top The awk utility shall conform to the Base Definitions volume of POSIX.12017, Section 12.2, Utility Syntax Guidelines. The following options shall be supported: -F sepstring Define the input field separator. This option shall be equivalent to: -v FS=sepstring except that if -F sepstring and -v FS=sepstring are both used, it is unspecified whether the FS assignment resulting from -F sepstring is processed in command line order or is processed after the last -v FS=sepstring. See the description of the FS built-in variable, and how it is used, in the EXTENDED DESCRIPTION section. -f progfile Specify the pathname of the file progfile containing an awk program. A pathname of '-' shall denote the standard input. If multiple instances of this option are specified, the concatenation of the files specified as progfile in the order specified shall be the awk program. The awk program can alternatively be specified in the command line as a single argument. -v assignment The application shall ensure that the assignment argument is in the same form as an assignment operand. The specified variable assignment shall occur prior to executing the awk program, including the actions associated with BEGIN patterns (if any). Multiple occurrences of this option can be specified. OPERANDS top The following operands shall be supported: program If no -f option is specified, the first operand to awk shall be the text of the awk program. The application shall supply the program operand as a single argument to awk. If the text does not end in a <newline>, awk shall interpret the text as if it did. argument Either of the following two types of argument can be intermixed: file A pathname of a file that contains the input to be read, which is matched against the set of patterns in the program. If no file operands are specified, or if a file operand is '-', the standard input shall be used. assignment An operand that begins with an <underscore> or alphabetic character from the portable character set (see the table in the Base Definitions volume of POSIX.12017, Section 6.1, Portable Character Set), followed by a sequence of underscores, digits, and alphabetics from the portable character set, followed by the '=' character, shall specify a variable assignment rather than a pathname. The characters before the '=' represent the name of an awk variable; if that name is an awk reserved word (see Grammar) the behavior is undefined. The characters following the <equals-sign> shall be interpreted as if they appeared in the awk program preceded and followed by a double-quote ('"') character, as a STRING token (see Grammar), except that if the last character is an unescaped <backslash>, it shall be interpreted as a literal <backslash> rather than as the first character of the sequence "\"". The variable shall be assigned the value of that STRING token and, if appropriate, shall be considered a numeric string (see Expressions in awk), the variable shall also be assigned its numeric value. Each such variable assignment shall occur just prior to the processing of the following file, if any. Thus, an assignment before the first file argument shall be executed after the BEGIN actions (if any), while an assignment after the last file argument shall occur before the END actions (if any). If there are no file arguments, assignments shall be executed before processing the standard input. STDIN top The standard input shall be used only if no file operands are specified, or if a file operand is '-', or if a progfile option- argument is '-'; see the INPUT FILES section. If the awk program contains no actions and no patterns, but is otherwise a valid awk program, standard input and any file operands shall not be read and awk shall exit with a return status of zero. INPUT FILES top Input files to the awk program from any of the following sources shall be text files: * Any file operands or their equivalents, achieved by modifying the awk variables ARGV and ARGC * Standard input in the absence of any file operands * Arguments to the getline function Whether the variable RS is set to a value other than a <newline> or not, for these files, implementations shall support records terminated with the specified separator up to {LINE_MAX} bytes and may support longer records. If -f progfile is specified, the application shall ensure that the files named by each of the progfile option-arguments are text files and their concatenation, in the same order as they appear in the arguments, is an awk program. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of awk: 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_COLLATE Determine the locale for the behavior of ranges, equivalence classes, and multi-character collating elements within regular expressions and in comparisons of string values. 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 and input files), the behavior of character classes within regular expressions, the identification of characters as letters, and the mapping of uppercase and lowercase characters for the toupper and tolower functions. LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. LC_NUMERIC Determine the radix character used when interpreting numeric input, performing conversions between numeric and string values, and formatting numeric output. Regardless of locale, the <period> character (the decimal-point character of the POSIX locale) is the decimal-point character recognized in processing awk programs (including assignments in command line arguments). NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. PATH Determine the search path when looking for commands executed by system(expr), or input and output pipes; see the Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables. In addition, all environment variables shall be visible via the awk variable ENVIRON. ASYNCHRONOUS EVENTS top Default. STDOUT top The nature of the output files depends on the awk program. STDERR top The standard error shall be used only for diagnostic messages. OUTPUT FILES top The nature of the output files depends on the awk program. EXTENDED DESCRIPTION top Overall Program Structure An awk program is composed of pairs of the form: pattern { action } Either the pattern or the action (including the enclosing brace characters) can be omitted. A missing pattern shall match any record of input, and a missing action shall be equivalent to: { print } Execution of the awk program shall start by first executing the actions associated with all BEGIN patterns in the order they occur in the program. Then each file operand (or standard input if no files were specified) shall be processed in turn by reading data from the file until a record separator is seen (<newline> by default). Before the first reference to a field in the record is evaluated, the record shall be split into fields, according to the rules in Regular Expressions, using the value of FS that was current at the time the record was read. Each pattern in the program then shall be evaluated in the order of occurrence, and the action associated with each pattern that matches the current record executed. The action for a matching pattern shall be executed before evaluating subsequent patterns. Finally, the actions associated with all END patterns shall be executed in the order they occur in the program. Expressions in awk Expressions describe computations used in patterns and actions. In the following table, valid expression operations are given in groups from highest precedence first to lowest precedence last, with equal-precedence operators grouped between horizontal lines. In expression evaluation, where the grammar is formally ambiguous, higher precedence operators shall be evaluated before lower precedence operators. In this table expr, expr1, expr2, and expr3 represent any expression, while lvalue represents any entity that can be assigned to (that is, on the left side of an assignment operator). The precise syntax of expressions is given in Grammar. Table 4-1: Expressions in Decreasing Precedence in awk Syntax Name Type of Result Associativity ( expr ) Grouping Type of expr N/A $expr Field reference String N/A lvalue ++ Post-increment Numeric N/A lvalue -- Post-decrement Numeric N/A ++ lvalue Pre-increment Numeric N/A -- lvalue Pre-decrement Numeric N/A expr ^ expr Exponentiation Numeric Right ! expr Logical not Numeric N/A + expr Unary plus Numeric N/A - expr Unary minus Numeric N/A expr * expr Multiplication Numeric Left expr / expr Division Numeric Left expr % expr Modulus Numeric Left expr + expr Addition Numeric Left expr - expr Subtraction Numeric Left expr expr String concatenation String Left expr < expr Less than Numeric None expr <= expr Less than or equal to Numeric None expr != expr Not equal to Numeric None expr == expr Equal to Numeric None expr > expr Greater than Numeric None expr >= expr Greater than or equal to Numeric None expr ~ expr ERE match Numeric None expr !~ expr ERE non-match Numeric None expr in array Array membership Numeric Left ( index ) in array Multi-dimension array Numeric Left membership expr && expr Logical AND Numeric Left expr || expr Logical OR Numeric Left expr1 ? expr2 : expr3Conditional expression Type of selectedRight expr2 or expr3 lvalue ^= expr Exponentiation assignmentNumeric Right lvalue %= expr Modulus assignment Numeric Right lvalue *= expr Multiplication assignmentNumeric Right lvalue /= expr Division assignment Numeric Right lvalue += expr Addition assignment Numeric Right lvalue -= expr Subtraction assignment Numeric Right lvalue = expr Assignment Type of expr Right Each expression shall have either a string value, a numeric value, or both. Except as stated for specific contexts, the value of an expression shall be implicitly converted to the type needed for the context in which it is used. A string value shall be converted to a numeric value either by the equivalent of the following calls to functions defined by the ISO C standard: setlocale(LC_NUMERIC, ""); numeric_value = atof(string_value); or by converting the initial portion of the string to type double representation as follows: The input string is decomposed into two parts: an initial, possibly empty, sequence of white-space characters (as specified by isspace()) and a subject sequence interpreted as a floating-point constant. The expected form of the subject sequence is an optional '+' or '-' sign, then a non-empty sequence of digits optionally containing a <period>, then an optional exponent part. An exponent part consists of 'e' or 'E', followed by an optional sign, followed by one or more decimal digits. The sequence starting with the first digit or the <period> (whichever occurs first) is interpreted as a floating constant of the C language, and if neither an exponent part nor a <period> appears, a <period> is assumed to follow the last digit in the string. If the subject sequence begins with a <hyphen-minus>, the value resulting from the conversion is negated. A numeric value that is exactly equal to the value of an integer (see Section 1.1.2, Concepts Derived from the ISO C Standard) shall be converted to a string by the equivalent of a call to the sprintf function (see String Functions) with the string "%d" as the fmt argument and the numeric value being converted as the first and only expr argument. Any other numeric value shall be converted to a string by the equivalent of a call to the sprintf function with the value of the variable CONVFMT as the fmt argument and the numeric value being converted as the first and only expr argument. The result of the conversion is unspecified if the value of CONVFMT is not a floating-point format specification. This volume of POSIX.12017 specifies no explicit conversions between numbers and strings. An application can force an expression to be treated as a number by adding zero to it, or can force it to be treated as a string by concatenating the null string ("") to it. A string value shall be considered a numeric string if it comes from one of the following: 1. Field variables 2. Input from the getline() function 3. FILENAME 4. ARGV array elements 5. ENVIRON array elements 6. Array elements created by the split() function 7. A command line variable assignment 8. Variable assignment from another numeric string variable and an implementation-dependent condition corresponding to either case (a) or (b) below is met. a. After the equivalent of the following calls to functions defined by the ISO C standard, string_value_end would differ from string_value, and any characters before the terminating null character in string_value_end would be <blank> characters: char *string_value_end; setlocale(LC_NUMERIC, ""); numeric_value = strtod (string_value, &string_value_end); b. After all the following conversions have been applied, the resulting string would lexically be recognized as a NUMBER token as described by the lexical conventions in Grammar: -- All leading and trailing <blank> characters are discarded. -- If the first non-<blank> is '+' or '-', it is discarded. -- Each occurrence of the decimal point character from the current locale is changed to a <period>. In case (a) the numeric value of the numeric string shall be the value that would be returned by the strtod() call. In case (b) if the first non-<blank> is '-', the numeric value of the numeric string shall be the negation of the numeric value of the recognized NUMBER token; otherwise, the numeric value of the numeric string shall be the numeric value of the recognized NUMBER token. Whether or not a string is a numeric string shall be relevant only in contexts where that term is used in this section. When an expression is used in a Boolean context, if it has a numeric value, a value of zero shall be treated as false and any other value shall be treated as true. Otherwise, a string value of the null string shall be treated as false and any other value shall be treated as true. A Boolean context shall be one of the following: * The first subexpression of a conditional expression * An expression operated on by logical NOT, logical AND, or logical OR * The second expression of a for statement * The expression of an if statement * The expression of the while clause in either a while or do...while statement * An expression used as a pattern (as in Overall Program Structure) All arithmetic shall follow the semantics of floating-point arithmetic as specified by the ISO C standard (see Section 1.1.2, Concepts Derived from the ISO C Standard). The value of the expression: expr1 ^ expr2 shall be equivalent to the value returned by the ISO C standard function call: pow(expr1, expr2) The expression: lvalue ^= expr shall be equivalent to the ISO C standard expression: lvalue = pow(lvalue, expr) except that lvalue shall be evaluated only once. The value of the expression: expr1 % expr2 shall be equivalent to the value returned by the ISO C standard function call: fmod(expr1, expr2) The expression: lvalue %= expr shall be equivalent to the ISO C standard expression: lvalue = fmod(lvalue, expr) except that lvalue shall be evaluated only once. Variables and fields shall be set by the assignment statement: lvalue = expression and the type of expression shall determine the resulting variable type. The assignment includes the arithmetic assignments ("+=", "-=", "*=", "/=", "%=", "^=", "++", "--") all of which shall produce a numeric result. The left-hand side of an assignment and the target of increment and decrement operators can be one of a variable, an array with index, or a field selector. The awk language supplies arrays that are used for storing numbers or strings. Arrays need not be declared. They shall initially be empty, and their sizes shall change dynamically. The subscripts, or element identifiers, are strings, providing a type of associative array capability. An array name followed by a subscript within square brackets can be used as an lvalue and thus as an expression, as described in the grammar; see Grammar. Unsubscripted array names can be used in only the following contexts: * A parameter in a function definition or function call * The NAME token following any use of the keyword in as specified in the grammar (see Grammar); if the name used in this context is not an array name, the behavior is undefined A valid array index shall consist of one or more <comma>-separated expressions, similar to the way in which multi- dimensional arrays are indexed in some programming languages. Because awk arrays are really one-dimensional, such a <comma>-separated list shall be converted to a single string by concatenating the string values of the separate expressions, each separated from the other by the value of the SUBSEP variable. Thus, the following two index operations shall be equivalent: var[expr1, expr2, ... exprn] var[expr1 SUBSEP expr2 SUBSEP ... SUBSEP exprn] The application shall ensure that a multi-dimensioned index used with the in operator is parenthesized. The in operator, which tests for the existence of a particular array element, shall not cause that element to exist. Any other reference to a nonexistent array element shall automatically create it. Comparisons (with the '<', "<=", "!=", "==", '>', and ">=" operators) shall be made numerically if both operands are numeric, if one is numeric and the other has a string value that is a numeric string, or if one is numeric and the other has the uninitialized value. Otherwise, operands shall be converted to strings as required and a string comparison shall be made as follows: * For the "!=" and "==" operators, the strings should be compared to check if they are identical but may be compared using the locale-specific collation sequence to check if they collate equally. * For the other operators, the strings shall be compared using the locale-specific collation sequence. The value of the comparison expression shall be 1 if the relation is true, or 0 if the relation is false. Variables and Special Variables Variables can be used in an awk program by referencing them. With the exception of function parameters (see User-Defined Functions), they are not explicitly declared. Function parameter names shall be local to the function; all other variable names shall be global. The same name shall not be used as both a function parameter name and as the name of a function or a special awk variable. The same name shall not be used both as a variable name with global scope and as the name of a function. The same name shall not be used within the same scope both as a scalar variable and as an array. Uninitialized variables, including scalar variables, array elements, and field variables, shall have an uninitialized value. An uninitialized value shall have both a numeric value of zero and a string value of the empty string. Evaluation of variables with an uninitialized value, to either string or numeric, shall be determined by the context in which they are used. Field variables shall be designated by a '$' followed by a number or numerical expression. The effect of the field number expression evaluating to anything other than a non-negative integer is unspecified; uninitialized variables or string values need not be converted to numeric values in this context. New field variables can be created by assigning a value to them. References to nonexistent fields (that is, fields after $NF), shall evaluate to the uninitialized value. Such references shall not create new fields. However, assigning to a nonexistent field (for example, $(NF+2)=5) shall increase the value of NF; create any intervening fields with the uninitialized value; and cause the value of $0 to be recomputed, with the fields being separated by the value of OFS. Each field variable shall have a string value or an uninitialized value when created. Field variables shall have the uninitialized value when created from $0 using FS and the variable does not contain any characters. If appropriate, the field variable shall be considered a numeric string (see Expressions in awk). Implementations shall support the following other special variables that are set by awk: ARGC The number of elements in the ARGV array. ARGV An array of command line arguments, excluding options and the program argument, numbered from zero to ARGC-1. The arguments in ARGV can be modified or added to; ARGC can be altered. As each input file ends, awk shall treat the next non-null element of ARGV, up to the current value of ARGC-1, inclusive, as the name of the next input file. Thus, setting an element of ARGV to null means that it shall not be treated as an input file. The name '-' indicates the standard input. If an argument matches the format of an assignment operand, this argument shall be treated as an assignment rather than a file argument. CONVFMT The printf format for converting numbers to strings (except for output statements, where OFMT is used); "%.6g" by default. ENVIRON An array representing the value of the environment, as described in the exec functions defined in the System Interfaces volume of POSIX.12017. The indices of the array shall be strings consisting of the names of the environment variables, and the value of each array element shall be a string consisting of the value of that variable. If appropriate, the environment variable shall be considered a numeric string (see Expressions in awk); the array element shall also have its numeric value. In all cases where the behavior of awk is affected by environment variables (including the environment of any commands that awk executes via the system function or via pipeline redirections with the print statement, the printf statement, or the getline function), the environment used shall be the environment at the time awk began executing; it is implementation-defined whether any modification of ENVIRON affects this environment. FILENAME A pathname of the current input file. Inside a BEGIN action the value is undefined. Inside an END action the value shall be the name of the last input file processed. FNR The ordinal number of the current record in the current file. Inside a BEGIN action the value shall be zero. Inside an END action the value shall be the number of the last record processed in the last file processed. FS Input field separator regular expression; a <space> by default. NF The number of fields in the current record. Inside a BEGIN action, the use of NF is undefined unless a getline function without a var argument is executed previously. Inside an END action, NF shall retain the value it had for the last record read, unless a subsequent, redirected, getline function without a var argument is performed prior to entering the END action. NR The ordinal number of the current record from the start of input. Inside a BEGIN action the value shall be zero. Inside an END action the value shall be the number of the last record processed. OFMT The printf format for converting numbers to strings in output statements (see Output Statements); "%.6g" by default. The result of the conversion is unspecified if the value of OFMT is not a floating-point format specification. OFS The print statement output field separator; <space> by default. ORS The print statement output record separator; a <newline> by default. RLENGTH The length of the string matched by the match function. RS The first character of the string value of RS shall be the input record separator; a <newline> by default. If RS contains more than one character, the results are unspecified. If RS is null, then records are separated by sequences consisting of a <newline> plus one or more blank lines, leading or trailing blank lines shall not result in empty records at the beginning or end of the input, and a <newline> shall always be a field separator, no matter what the value of FS is. RSTART The starting position of the string matched by the match function, numbering from 1. This shall always be equivalent to the return value of the match function. SUBSEP The subscript separator string for multi-dimensional arrays; the default value is implementation-defined. Regular Expressions The awk utility shall make use of the extended regular expression notation (see the Base Definitions volume of POSIX.12017, Section 9.4, Extended Regular Expressions) except that it shall allow the use of C-language conventions for escaping special characters within the EREs, as specified in the table in the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v') and the following table; these escape sequences shall be recognized both inside and outside bracket expressions. Note that records need not be separated by <newline> characters and string constants can contain <newline> characters, so even the "\n" sequence is valid in awk EREs. Using a <slash> character within an ERE requires the escaping shown in the following table. Table 4-2: Escape Sequences in awk Escape Sequence Description Meaning \" <backslash> <quotation-mark> <quotation-mark> character \/ <backslash> <slash> <slash> character \ddd A <backslash> character followed The character whose encoding is by the longest sequence of one, represented by the one, two, or two, or three octal-digit three-digit octal integer. Multi- characters (01234567). If all of byte characters require multiple, the digits are 0 (that is, concatenated escape sequences of representation of the NUL this type, including the leading character), the behavior is <backslash> for each byte. undefined. \c A <backslash> character followed Undefined by any character not described in this table or in the table in the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v'). A regular expression can be matched against a specific field or string by using one of the two regular expression matching operators, '~' and "!~". These operators shall interpret their right-hand operand as a regular expression and their left-hand operand as a string. If the regular expression matches the string, the '~' expression shall evaluate to a value of 1, and the "!~" expression shall evaluate to a value of 0. (The regular expression matching operation is as defined by the term matched in the Base Definitions volume of POSIX.12017, Section 9.1, Regular Expression Definitions, where a match occurs on any part of the string unless the regular expression is limited with the <circumflex> or <dollar-sign> special characters.) If the regular expression does not match the string, the '~' expression shall evaluate to a value of 0, and the "!~" expression shall evaluate to a value of 1. If the right-hand operand is any expression other than the lexical token ERE, the string value of the expression shall be interpreted as an extended regular expression, including the escape conventions described above. Note that these same escape conventions shall also be applied in determining the value of a string literal (the lexical token STRING), and thus shall be applied a second time when a string literal is used in this context. When an ERE token appears as an expression in any context other than as the right-hand of the '~' or "!~" operator or as one of the built-in function arguments described below, the value of the resulting expression shall be the equivalent of: $0 ~ /ere/ The ere argument to the gsub, match, sub functions, and the fs argument to the split function (see String Functions) shall be interpreted as extended regular expressions. These can be either ERE tokens or arbitrary expressions, and shall be interpreted in the same manner as the right-hand side of the '~' or "!~" operator. An extended regular expression can be used to separate fields by assigning a string containing the expression to the built-in variable FS, either directly or as a consequence of using the -F sepstring option. The default value of the FS variable shall be a single <space>. The following describes FS behavior: 1. If FS is a null string, the behavior is unspecified. 2. If FS is a single character: a. If FS is <space>, skip leading and trailing <blank> and <newline> characters; fields shall be delimited by sets of one or more <blank> or <newline> characters. b. Otherwise, if FS is any other character c, fields shall be delimited by each single occurrence of c. 3. Otherwise, the string value of FS shall be considered to be an extended regular expression. Each occurrence of a sequence matching the extended regular expression shall delimit fields. Except for the '~' and "!~" operators, and in the gsub, match, split, and sub built-in functions, ERE matching shall be based on input records; that is, record separator characters (the first character of the value of the variable RS, <newline> by default) cannot be embedded in the expression, and no expression shall match the record separator character. If the record separator is not <newline>, <newline> characters embedded in the expression can be matched. For the '~' and "!~" operators, and in those four built-in functions, ERE matching shall be based on text strings; that is, any character (including <newline> and the record separator) can be embedded in the pattern, and an appropriate pattern shall match any character. However, in all awk ERE matching, the use of one or more NUL characters in the pattern, input record, or text string produces undefined results. Patterns A pattern is any valid expression, a range specified by two expressions separated by a comma, or one of the two special patterns BEGIN or END. Special Patterns The awk utility shall recognize two special patterns, BEGIN and END. Each BEGIN pattern shall be matched once and its associated action executed before the first record of input is readexcept possibly by use of the getline function (see Input/Output and General Functions) in a prior BEGIN actionand before command line assignment is done. Each END pattern shall be matched once and its associated action executed after the last record of input has been read. These two patterns shall have associated actions. BEGIN and END shall not combine with other patterns. Multiple BEGIN and END patterns shall be allowed. The actions associated with the BEGIN patterns shall be executed in the order specified in the program, as are the END actions. An END pattern can precede a BEGIN pattern in a program. If an awk program consists of only actions with the pattern BEGIN, and the BEGIN action contains no getline function, awk shall exit without reading its input when the last statement in the last BEGIN action is executed. If an awk program consists of only actions with the pattern END or only actions with the patterns BEGIN and END, the input shall be read before the statements in the END actions are executed. Expression Patterns An expression pattern shall be evaluated as if it were an expression in a Boolean context. If the result is true, the pattern shall be considered to match, and the associated action (if any) shall be executed. If the result is false, the action shall not be executed. Pattern Ranges A pattern range consists of two expressions separated by a comma; in this case, the action shall be performed for all records between a match of the first expression and the following match of the second expression, inclusive. At this point, the pattern range can be repeated starting at input records subsequent to the end of the matched range. Actions An action is a sequence of statements as shown in the grammar in Grammar. Any single statement can be replaced by a statement list enclosed in curly braces. The application shall ensure that statements in a statement list are separated by <newline> or <semicolon> characters. Statements in a statement list shall be executed sequentially in the order that they appear. The expression acting as the conditional in an if statement shall be evaluated and if it is non-zero or non-null, the following statement shall be executed; otherwise, if else is present, the statement following the else shall be executed. The if, while, do...while, for, break, and continue statements are based on the ISO C standard (see Section 1.1.2, Concepts Derived from the ISO C Standard), except that the Boolean expressions shall be treated as described in Expressions in awk, and except in the case of: for (variable in array) which shall iterate, assigning each index of array to variable in an unspecified order. The results of adding new elements to array within such a for loop are undefined. If a break or continue statement occurs outside of a loop, the behavior is undefined. The delete statement shall remove an individual array element. Thus, the following code deletes an entire array: for (index in array) delete array[index] The next statement shall cause all further processing of the current input record to be abandoned. The behavior is undefined if a next statement appears or is invoked in a BEGIN or END action. The exit statement shall invoke all END actions in the order in which they occur in the program source and then terminate the program without reading further input. An exit statement inside an END action shall terminate the program without further execution of END actions. If an expression is specified in an exit statement, its numeric value shall be the exit status of awk, unless subsequent errors are encountered or a subsequent exit statement with an expression is executed. Output Statements Both print and printf statements shall write to standard output by default. The output shall be written to the location specified by output_redirection if one is supplied, as follows: > expression >> expression | expression In all cases, the expression shall be evaluated to produce a string that is used as a pathname into which to write (for '>' or ">>") or as a command to be executed (for '|'). Using the first two forms, if the file of that name is not currently open, it shall be opened, creating it if necessary and using the first form, truncating the file. The output then shall be appended to the file. As long as the file remains open, subsequent calls in which expression evaluates to the same string value shall simply append output to the file. The file remains open until the close function (see Input/Output and General Functions) is called with an expression that evaluates to the same string value. The third form shall write output onto a stream piped to the input of a command. The stream shall be created if no stream is currently open with the value of expression as its command name. The stream created shall be equivalent to one created by a call to the popen() function defined in the System Interfaces volume of POSIX.12017 with the value of expression as the command argument and a value of w as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall write output to the existing stream. The stream shall remain open until the close function (see Input/Output and General Functions) is called with an expression that evaluates to the same string value. At that time, the stream shall be closed as if by a call to the pclose() function defined in the System Interfaces volume of POSIX.12017. As described in detail by the grammar in Grammar, these output statements shall take a <comma>-separated list of expressions referred to in the grammar by the non-terminal symbols expr_list, print_expr_list, or print_expr_list_opt. This list is referred to here as the expression list, and each member is referred to as an expression argument. The print statement shall write the value of each expression argument onto the indicated output stream separated by the current output field separator (see variable OFS above), and terminated by the output record separator (see variable ORS above). All expression arguments shall be taken as strings, being converted if necessary; this conversion shall be as described in Expressions in awk, with the exception that the printf format in OFMT shall be used instead of the value in CONVFMT. An empty expression list shall stand for the whole input record ($0). The printf statement shall produce output based on a notation similar to the File Format Notation used to describe file formats in this volume of POSIX.12017 (see the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation). Output shall be produced as specified with the first expression argument as the string format and subsequent expression arguments as the strings arg1 to argn, inclusive, with the following exceptions: 1. The format shall be an actual character string rather than a graphical representation. Therefore, it cannot contain empty character positions. The <space> in the format string, in any context other than a flag of a conversion specification, shall be treated as an ordinary character that is copied to the output. 2. If the character set contains a '' character and that character appears in the format string, it shall be treated as an ordinary character that is copied to the output. 3. The escape sequences beginning with a <backslash> character shall be treated as sequences of ordinary characters that are copied to the output. Note that these same sequences shall be interpreted lexically by awk when they appear in literal strings, but they shall not be treated specially by the printf statement. 4. A field width or precision can be specified as the '*' character instead of a digit string. In this case the next argument from the expression list shall be fetched and its numeric value taken as the field width or precision. 5. The implementation shall not precede or follow output from the d or u conversion specifier characters with <blank> characters not specified by the format string. 6. The implementation shall not precede output from the o conversion specifier character with leading zeros not specified by the format string. 7. For the c conversion specifier character: if the argument has a numeric value, the character whose encoding is that value shall be output. If the value is zero or is not the encoding of any character in the character set, the behavior is undefined. If the argument does not have a numeric value, the first character of the string value shall be output; if the string does not contain any characters, the behavior is undefined. 8. For each conversion specification that consumes an argument, the next expression argument shall be evaluated. With the exception of the c conversion specifier character, the value shall be converted (according to the rules specified in Expressions in awk) to the appropriate type for the conversion specification. 9. If there are insufficient expression arguments to satisfy all the conversion specifications in the format string, the behavior is undefined. 10. If any character sequence in the format string begins with a '%' character, but does not form a valid conversion specification, the behavior is unspecified. Both print and printf can output at least {LINE_MAX} bytes. Functions The awk language has a variety of built-in functions: arithmetic, string, input/output, and general. Arithmetic Functions The arithmetic functions, except for int, shall be based on the ISO C standard (see Section 1.1.2, Concepts Derived from the ISO C Standard). The behavior is undefined in cases where the ISO C standard specifies that an error be returned or that the behavior is undefined. Although the grammar (see Grammar) permits built-in functions to appear with no arguments or parentheses, unless the argument or parentheses are indicated as optional in the following list (by displaying them within the "[]" brackets), such use is undefined. atan2(y,x) Return arctangent of y/x in radians in the range [-,]. cos(x) Return cosine of x, where x is in radians. sin(x) Return sine of x, where x is in radians. exp(x) Return the exponential function of x. log(x) Return the natural logarithm of x. sqrt(x) Return the square root of x. int(x) Return the argument truncated to an integer. Truncation shall be toward 0 when x>0. rand() Return a random number n, such that 0n<1. srand([expr]) Set the seed value for rand to expr or use the time of day if expr is omitted. The previous seed value shall be returned. String Functions The string functions in the following list shall be supported. Although the grammar (see Grammar) permits built-in functions to appear with no arguments or parentheses, unless the argument or parentheses are indicated as optional in the following list (by displaying them within the "[]" brackets), such use is undefined. gsub(ere, repl[, in]) Behave like sub (see below), except that it shall replace all occurrences of the regular expression (like the ed utility global substitute) in $0 or in the in argument, when specified. index(s, t) Return the position, in characters, numbering from 1, in string s where string t first occurs, or zero if it does not occur at all. length[([s])] Return the length, in characters, of its argument taken as a string, or of the whole record, $0, if there is no argument. match(s, ere) Return the position, in characters, numbering from 1, in string s where the extended regular expression ere occurs, or zero if it does not occur at all. RSTART shall be set to the starting position (which is the same as the returned value), zero if no match is found; RLENGTH shall be set to the length of the matched string, -1 if no match is found. split(s, a[, fs ]) Split the string s into array elements a[1], a[2], ..., a[n], and return n. All elements of the array shall be deleted before the split is performed. The separation shall be done with the ERE fs or with the field separator FS if fs is not given. Each array element shall have a string value when created and, if appropriate, the array element shall be considered a numeric string (see Expressions in awk). The effect of a null string as the value of fs is unspecified. sprintf(fmt, expr, expr, ...) Format the expressions according to the printf format given by fmt and return the resulting string. sub(ere, repl[, in ]) Substitute the string repl in place of the first instance of the extended regular expression ERE in string in and return the number of substitutions. An <ampersand> ('&') appearing in the string repl shall be replaced by the string from in that matches the ERE. An <ampersand> preceded with a <backslash> shall be interpreted as the literal <ampersand> character. An occurrence of two consecutive <backslash> characters shall be interpreted as just a single literal <backslash> character. Any other occurrence of a <backslash> (for example, preceding any other character) shall be treated as a literal <backslash> character. Note that if repl is a string literal (the lexical token STRING; see Grammar), the handling of the <ampersand> character occurs after any lexical processing, including any lexical <backslash>-escape sequence processing. If in is specified and it is not an lvalue (see Expressions in awk), the behavior is undefined. If in is omitted, awk shall use the current record ($0) in its place. substr(s, m[, n ]) Return the at most n-character substring of s that begins at position m, numbering from 1. If n is omitted, or if n specifies more characters than are left in the string, the length of the substring shall be limited by the length of the string s. tolower(s) Return a string based on the string s. Each character in s that is an uppercase letter specified to have a tolower mapping by the LC_CTYPE category of the current locale shall be replaced in the returned string by the lowercase letter specified by the mapping. Other characters in s shall be unchanged in the returned string. toupper(s) Return a string based on the string s. Each character in s that is a lowercase letter specified to have a toupper mapping by the LC_CTYPE category of the current locale is replaced in the returned string by the uppercase letter specified by the mapping. Other characters in s are unchanged in the returned string. All of the preceding functions that take ERE as a parameter expect a pattern or a string valued expression that is a regular expression as defined in Regular Expressions. Input/Output and General Functions The input/output and general functions are: close(expression) Close the file or pipe opened by a print or printf statement or a call to getline with the same string- valued expression. The limit on the number of open expression arguments is implementation-defined. If the close was successful, the function shall return zero; otherwise, it shall return non-zero. expression | getline [var] Read a record of input from a stream piped from the output of a command. The stream shall be created if no stream is currently open with the value of expression as its command name. The stream created shall be equivalent to one created by a call to the popen() function with the value of expression as the command argument and a value of r as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall read subsequent records from the stream. The stream shall remain open until the close function is called with an expression that evaluates to the same string value. At that time, the stream shall be closed as if by a call to the pclose() function. If var is omitted, $0 and NF shall be set; otherwise, var shall be set and, if appropriate, it shall be considered a numeric string (see Expressions in awk). The getline operator can form ambiguous constructs when there are unparenthesized operators (including concatenate) to the left of the '|' (to the beginning of the expression containing getline). In the context of the '$' operator, '|' shall behave as if it had a lower precedence than '$'. The result of evaluating other operators is unspecified, and conforming applications shall parenthesize properly all such usages. getline Set $0 to the next input record from the current input file. This form of getline shall set the NF, NR, and FNR variables. getline var Set variable var to the next input record from the current input file and, if appropriate, var shall be considered a numeric string (see Expressions in awk). This form of getline shall set the FNR and NR variables. getline [var] < expression Read the next record of input from a named file. The expression shall be evaluated to produce a string that is used as a pathname. If the file of that name is not currently open, it shall be opened. As long as the stream remains open, subsequent calls in which expression evaluates to the same string value shall read subsequent records from the file. The file shall remain open until the close function is called with an expression that evaluates to the same string value. If var is omitted, $0 and NF shall be set; otherwise, var shall be set and, if appropriate, it shall be considered a numeric string (see Expressions in awk). The getline operator can form ambiguous constructs when there are unparenthesized binary operators (including concatenate) to the right of the '<' (up to the end of the expression containing the getline). The result of evaluating such a construct is unspecified, and conforming applications shall parenthesize properly all such usages. system(expression) Execute the command given by expression in a manner equivalent to the system() function defined in the System Interfaces volume of POSIX.12017 and return the exit status of the command. All forms of getline shall return 1 for successful input, zero for end-of-file, and -1 for an error. Where strings are used as the name of a file or pipeline, the application shall ensure that the strings are textually identical. The terminology ``same string value'' implies that ``equivalent strings'', even those that differ only by <space> characters, represent different files. User-Defined Functions The awk language also provides user-defined functions. Such functions can be defined as: function name([parameter, ...]) { statements } A function can be referred to anywhere in an awk program; in particular, its use can precede its definition. The scope of a function is global. Function parameters, if present, can be either scalars or arrays; the behavior is undefined if an array name is passed as a parameter that the function uses as a scalar, or if a scalar expression is passed as a parameter that the function uses as an array. Function parameters shall be passed by value if scalar and by reference if array name. The number of parameters in the function definition need not match the number of parameters in the function call. Excess formal parameters can be used as local variables. If fewer arguments are supplied in a function call than are in the function definition, the extra parameters that are used in the function body as scalars shall evaluate to the uninitialized value until they are otherwise initialized, and the extra parameters that are used in the function body as arrays shall be treated as uninitialized arrays where each element evaluates to the uninitialized value until otherwise initialized. When invoking a function, no white space can be placed between the function name and the opening parenthesis. Function calls can be nested and recursive calls can be made upon functions. Upon return from any nested or recursive function call, the values of all of the calling function's parameters shall be unchanged, except for array parameters passed by reference. The return statement can be used to return a value. If a return statement appears outside of a function definition, the behavior is undefined. In the function definition, <newline> characters shall be optional before the opening brace and after the closing brace. Function definitions can appear anywhere in the program where a pattern-action pair is allowed. Grammar The grammar in this section and the lexical conventions in the following section shall together describe the syntax for awk programs. The general conventions for this style of grammar are described in Section 1.3, Grammar Conventions. A valid program can be represented as the non-terminal symbol program in the grammar. This formal syntax shall take precedence over the preceding text syntax description. %token NAME NUMBER STRING ERE %token FUNC_NAME /* Name followed by '(' without white space. */ /* Keywords */ %token Begin End /* 'BEGIN' 'END' */ %token Break Continue Delete Do Else /* 'break' 'continue' 'delete' 'do' 'else' */ %token Exit For Function If In /* 'exit' 'for' 'function' 'if' 'in' */ %token Next Print Printf Return While /* 'next' 'print' 'printf' 'return' 'while' */ /* Reserved function names */ %token BUILTIN_FUNC_NAME /* One token for the following: * atan2 cos sin exp log sqrt int rand srand * gsub index length match split sprintf sub * substr tolower toupper close system */ %token GETLINE /* Syntactically different from other built-ins. */ /* Two-character tokens. */ %token ADD_ASSIGN SUB_ASSIGN MUL_ASSIGN DIV_ASSIGN MOD_ASSIGN POW_ASSIGN /* '+=' '-=' '*=' '/=' '%=' '^=' */ %token OR AND NO_MATCH EQ LE GE NE INCR DECR APPEND /* '||' '&&' '!~' '==' '<=' '>=' '!=' '++' '--' '>>' */ /* One-character tokens. */ %token '{' '}' '(' ')' '[' ']' ',' ';' NEWLINE %token '+' '-' '*' '%' '^' '!' '>' '<' '|' '?' ':' '~' '$' '=' %start program %% program : item_list | item_list item ; item_list : /* empty */ | item_list item terminator ; item : action | pattern action | normal_pattern | Function NAME '(' param_list_opt ')' newline_opt action | Function FUNC_NAME '(' param_list_opt ')' newline_opt action ; param_list_opt : /* empty */ | param_list ; param_list : NAME | param_list ',' NAME ; pattern : normal_pattern | special_pattern ; normal_pattern : expr | expr ',' newline_opt expr ; special_pattern : Begin | End ; action : '{' newline_opt '}' | '{' newline_opt terminated_statement_list '}' | '{' newline_opt unterminated_statement_list '}' ; terminator : terminator NEWLINE | ';' | NEWLINE ; terminated_statement_list : terminated_statement | terminated_statement_list terminated_statement ; unterminated_statement_list : unterminated_statement | terminated_statement_list unterminated_statement ; terminated_statement : action newline_opt | If '(' expr ')' newline_opt terminated_statement | If '(' expr ')' newline_opt terminated_statement Else newline_opt terminated_statement | While '(' expr ')' newline_opt terminated_statement | For '(' simple_statement_opt ';' expr_opt ';' simple_statement_opt ')' newline_opt terminated_statement | For '(' NAME In NAME ')' newline_opt terminated_statement | ';' newline_opt | terminatable_statement NEWLINE newline_opt | terminatable_statement ';' newline_opt ; unterminated_statement : terminatable_statement | If '(' expr ')' newline_opt unterminated_statement | If '(' expr ')' newline_opt terminated_statement Else newline_opt unterminated_statement | While '(' expr ')' newline_opt unterminated_statement | For '(' simple_statement_opt ';' expr_opt ';' simple_statement_opt ')' newline_opt unterminated_statement | For '(' NAME In NAME ')' newline_opt unterminated_statement ; terminatable_statement : simple_statement | Break | Continue | Next | Exit expr_opt | Return expr_opt | Do newline_opt terminated_statement While '(' expr ')' ; simple_statement_opt : /* empty */ | simple_statement ; simple_statement : Delete NAME '[' expr_list ']' | expr | print_statement ; print_statement : simple_print_statement | simple_print_statement output_redirection ; simple_print_statement : Print print_expr_list_opt | Print '(' multiple_expr_list ')' | Printf print_expr_list | Printf '(' multiple_expr_list ')' ; output_redirection : '>' expr | APPEND expr | '|' expr ; expr_list_opt : /* empty */ | expr_list ; expr_list : expr | multiple_expr_list ; multiple_expr_list : expr ',' newline_opt expr | multiple_expr_list ',' newline_opt expr ; expr_opt : /* empty */ | expr ; expr : unary_expr | non_unary_expr ; unary_expr : '+' expr | '-' expr | unary_expr '^' expr | unary_expr '*' expr | unary_expr '/' expr | unary_expr '%' expr | unary_expr '+' expr | unary_expr '-' expr | unary_expr non_unary_expr | unary_expr '<' expr | unary_expr LE expr | unary_expr NE expr | unary_expr EQ expr | unary_expr '>' expr | unary_expr GE expr | unary_expr '~' expr | unary_expr NO_MATCH expr | unary_expr In NAME | unary_expr AND newline_opt expr | unary_expr OR newline_opt expr | unary_expr '?' expr ':' expr | unary_input_function ; non_unary_expr : '(' expr ')' | '!' expr | non_unary_expr '^' expr | non_unary_expr '*' expr | non_unary_expr '/' expr | non_unary_expr '%' expr | non_unary_expr '+' expr | non_unary_expr '-' expr | non_unary_expr non_unary_expr | non_unary_expr '<' expr | non_unary_expr LE expr | non_unary_expr NE expr | non_unary_expr EQ expr | non_unary_expr '>' expr | non_unary_expr GE expr | non_unary_expr '~' expr | non_unary_expr NO_MATCH expr | non_unary_expr In NAME | '(' multiple_expr_list ')' In NAME | non_unary_expr AND newline_opt expr | non_unary_expr OR newline_opt expr | non_unary_expr '?' expr ':' expr | NUMBER | STRING | lvalue | ERE | lvalue INCR | lvalue DECR | INCR lvalue | DECR lvalue | lvalue POW_ASSIGN expr | lvalue MOD_ASSIGN expr | lvalue MUL_ASSIGN expr | lvalue DIV_ASSIGN expr | lvalue ADD_ASSIGN expr | lvalue SUB_ASSIGN expr | lvalue '=' expr | FUNC_NAME '(' expr_list_opt ')' /* no white space allowed before '(' */ | BUILTIN_FUNC_NAME '(' expr_list_opt ')' | BUILTIN_FUNC_NAME | non_unary_input_function ; print_expr_list_opt : /* empty */ | print_expr_list ; print_expr_list : print_expr | print_expr_list ',' newline_opt print_expr ; print_expr : unary_print_expr | non_unary_print_expr ; unary_print_expr : '+' print_expr | '-' print_expr | unary_print_expr '^' print_expr | unary_print_expr '*' print_expr | unary_print_expr '/' print_expr | unary_print_expr '%' print_expr | unary_print_expr '+' print_expr | unary_print_expr '-' print_expr | unary_print_expr non_unary_print_expr | unary_print_expr '~' print_expr | unary_print_expr NO_MATCH print_expr | unary_print_expr In NAME | unary_print_expr AND newline_opt print_expr | unary_print_expr OR newline_opt print_expr | unary_print_expr '?' print_expr ':' print_expr ; non_unary_print_expr : '(' expr ')' | '!' print_expr | non_unary_print_expr '^' print_expr | non_unary_print_expr '*' print_expr | non_unary_print_expr '/' print_expr | non_unary_print_expr '%' print_expr | non_unary_print_expr '+' print_expr | non_unary_print_expr '-' print_expr | non_unary_print_expr non_unary_print_expr | non_unary_print_expr '~' print_expr | non_unary_print_expr NO_MATCH print_expr | non_unary_print_expr In NAME | '(' multiple_expr_list ')' In NAME | non_unary_print_expr AND newline_opt print_expr | non_unary_print_expr OR newline_opt print_expr | non_unary_print_expr '?' print_expr ':' print_expr | NUMBER | STRING | lvalue | ERE | lvalue INCR | lvalue DECR | INCR lvalue | DECR lvalue | lvalue POW_ASSIGN print_expr | lvalue MOD_ASSIGN print_expr | lvalue MUL_ASSIGN print_expr | lvalue DIV_ASSIGN print_expr | lvalue ADD_ASSIGN print_expr | lvalue SUB_ASSIGN print_expr | lvalue '=' print_expr | FUNC_NAME '(' expr_list_opt ')' /* no white space allowed before '(' */ | BUILTIN_FUNC_NAME '(' expr_list_opt ')' | BUILTIN_FUNC_NAME ; lvalue : NAME | NAME '[' expr_list ']' | '$' expr ; non_unary_input_function : simple_get | simple_get '<' expr | non_unary_expr '|' simple_get ; unary_input_function : unary_expr '|' simple_get ; simple_get : GETLINE | GETLINE lvalue ; newline_opt : /* empty */ | newline_opt NEWLINE ; This grammar has several ambiguities that shall be resolved as follows: * Operator precedence and associativity shall be as described in Table 4-1, Expressions in Decreasing Precedence in awk. * In case of ambiguity, an else shall be associated with the most immediately preceding if that would satisfy the grammar. * In some contexts, a <slash> ('/') that is used to surround an ERE could also be the division operator. This shall be resolved in such a way that wherever the division operator could appear, a <slash> is assumed to be the division operator. (There is no unary division operator.) Each expression in an awk program shall conform to the precedence and associativity rules, even when this is not needed to resolve an ambiguity. For example, because '$' has higher precedence than '++', the string "$x++--" is not a valid awk expression, even though it is unambiguously parsed by the grammar as "$(x++)--". One convention that might not be obvious from the formal grammar is where <newline> characters are acceptable. There are several obvious placements such as terminating a statement, and a <backslash> can be used to escape <newline> characters between any lexical tokens. In addition, <newline> characters without <backslash> characters can follow a comma, an open brace, logical AND operator ("&&"), logical OR operator ("||"), the do keyword, the else keyword, and the closing parenthesis of an if, for, or while statement. For example: { print $1, $2 } Lexical Conventions The lexical conventions for awk programs, with respect to the preceding grammar, shall be as follows: 1. Except as noted, awk shall recognize the longest possible token or delimiter beginning at a given point. 2. A comment shall consist of any characters beginning with the <number-sign> character and terminated by, but excluding the next occurrence of, a <newline>. Comments shall have no effect, except to delimit lexical tokens. 3. The <newline> shall be recognized as the token NEWLINE. 4. A <backslash> character immediately followed by a <newline> shall have no effect. 5. The token STRING shall represent a string constant. A string constant shall begin with the character '"'. Within a string constant, a <backslash> character shall be considered to begin an escape sequence as specified in the table in the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v'). In addition, the escape sequences in Table 4-2, Escape Sequences in awk shall be recognized. A <newline> shall not occur within a string constant. A string constant shall be terminated by the first unescaped occurrence of the character '"' after the one that begins the string constant. The value of the string shall be the sequence of all unescaped characters and values of escape sequences between, but not including, the two delimiting '"' characters. 6. The token ERE represents an extended regular expression constant. An ERE constant shall begin with the <slash> character. Within an ERE constant, a <backslash> character shall be considered to begin an escape sequence as specified in the table in the Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation. In addition, the escape sequences in Table 4-2, Escape Sequences in awk shall be recognized. The application shall ensure that a <newline> does not occur within an ERE constant. An ERE constant shall be terminated by the first unescaped occurrence of the <slash> character after the one that begins the ERE constant. The extended regular expression represented by the ERE constant shall be the sequence of all unescaped characters and values of escape sequences between, but not including, the two delimiting <slash> characters. 7. A <blank> shall have no effect, except to delimit lexical tokens or within STRING or ERE tokens. 8. The token NUMBER shall represent a numeric constant. Its form and numeric value shall either be equivalent to the decimal- floating-constant token as specified by the ISO C standard, or it shall be a sequence of decimal digits and shall be evaluated as an integer constant in decimal. In addition, implementations may accept numeric constants with the form and numeric value equivalent to the hexadecimal-constant and hexadecimal-floating-constant tokens as specified by the ISO C standard. If the value is too large or too small to be representable (see Section 1.1.2, Concepts Derived from the ISO C Standard), the behavior is undefined. 9. A sequence of underscores, digits, and alphabetics from the portable character set (see the Base Definitions volume of POSIX.12017, Section 6.1, Portable Character Set), beginning with an <underscore> or alphabetic character, shall be considered a word. 10. The following words are keywords that shall be recognized as individual tokens; the name of the token is the same as the keyword: BEGIN delete END function in printf break do exit getline next return continue else for if print while 11. The following words are names of built-in functions and shall be recognized as the token BUILTIN_FUNC_NAME: atan2 gsub log split sub toupper close index match sprintf substr cos int rand sqrt system exp length sin srand tolower The above-listed keywords and names of built-in functions are considered reserved words. 12. The token NAME shall consist of a word that is not a keyword or a name of a built-in function and is not followed immediately (without any delimiters) by the '(' character. 13. The token FUNC_NAME shall consist of a word that is not a keyword or a name of a built-in function, followed immediately (without any delimiters) by the '(' character. The '(' character shall not be included as part of the token. 14. The following two-character sequences shall be recognized as the named tokens: Token Name Sequence Token Name Sequence ADD_ASSIGN += NO_MATCH !~ SUB_ASSIGN -= EQ == MUL_ASSIGN *= LE <= DIV_ASSIGN /= GE >= MOD_ASSIGN %= NE != POW_ASSIGN ^= INCR ++ OR || DECR -- AND && APPEND >> 15. The following single characters shall be recognized as tokens whose names are the character: <newline> { } ( ) [ ] , ; + - * % ^ ! > < | ? : ~ $ = There is a lexical ambiguity between the token ERE and the tokens '/' and DIV_ASSIGN. When an input sequence begins with a <slash> character in any syntactic context where the token '/' or DIV_ASSIGN could appear as the next token in a valid program, the longer of those two tokens that can be recognized shall be recognized. In any other syntactic context where the token ERE could appear as the next token in a valid program, the token ERE shall be recognized. EXIT STATUS top The following exit values shall be returned: 0 All input files were processed successfully. >0 An error occurred. The exit status can be altered within the program by using an exit expression. CONSEQUENCES OF ERRORS top If any file operand is specified and the named file cannot be accessed, awk shall write a diagnostic message to standard error and terminate without any further action. If the program specified by either the program operand or a progfile operand is not a valid awk program (as specified in the EXTENDED DESCRIPTION section), the behavior is undefined. The following sections are informative. APPLICATION USAGE top The index, length, match, and substr functions should not be confused with similar functions in the ISO C standard; the awk versions deal with characters, while the ISO C standard deals with bytes. Because the concatenation operation is represented by adjacent expressions rather than an explicit operator, it is often necessary to use parentheses to enforce the proper evaluation precedence. When using awk to process pathnames, it is recommended that LC_ALL, or at least LC_CTYPE and LC_COLLATE, are set to POSIX or C in the environment, since pathnames can contain byte sequences that do not form valid characters in some locales, in which case the utility's behavior would be undefined. In the POSIX locale each byte is a valid single-byte character, and therefore this problem is avoided. On implementations where the "==" operator checks if strings collate equally, applications needing to check whether strings are identical can use: length(a) == length(b) && index(a,b) == 1 On implementations where the "==" operator checks if strings are identical, applications needing to check whether strings collate equally can use: a <= b && a >= b EXAMPLES top The awk program specified in the command line is most easily specified within single-quotes (for example, 'program') for applications using sh, because awk programs commonly contain characters that are special to the shell, including double- quotes. In the cases where an awk program contains single-quote characters, it is usually easiest to specify most of the program as strings within single-quotes concatenated by the shell with quoted single-quote characters. For example: awk '/'\''/ { print "quote:", $0 }' prints all lines from the standard input containing a single- quote character, prefixed with quote:. The following are examples of simple awk programs: 1. Write to the standard output all input lines for which field 3 is greater than 5: $3 > 5 2. Write every tenth line: (NR % 10) == 0 3. Write any line with a substring matching the regular expression: /(G|D)(2[0-9][[:alpha:]]*)/ 4. Print any line with a substring containing a 'G' or 'D', followed by a sequence of digits and characters. This example uses character classes digit and alpha to match language- independent digit and alphabetic characters respectively: /(G|D)([[:digit:][:alpha:]]*)/ 5. Write any line in which the second field matches the regular expression and the fourth field does not: $2 ~ /xyz/ && $4 !~ /xyz/ 6. Write any line in which the second field contains a <backslash>: $2 ~ /\\/ 7. Write any line in which the second field contains a <backslash>. Note that <backslash>-escapes are interpreted twice; once in lexical processing of the string and once in processing the regular expression: $2 ~ "\\\\" 8. Write the second to the last and the last field in each line. Separate the fields by a <colon>: {OFS=":";print $(NF-1), $NF} 9. Write the line number and number of fields in each line. The three strings representing the line number, the <colon>, and the number of fields are concatenated and that string is written to standard output: {print NR ":" NF} 10. Write lines longer than 72 characters: length($0) > 72 11. Write the first two fields in opposite order separated by OFS: { print $2, $1 } 12. Same, with input fields separated by a <comma> or <space> and <tab> characters, or both: BEGIN { FS = ",[ \t]*|[ \t]+" } { print $2, $1 } 13. Add up the first column, print sum, and average: {s += $1 } END {print "sum is ", s, " average is", s/NR} 14. Write fields in reverse order, one per line (many lines out for each line in): { for (i = NF; i > 0; --i) print $i } 15. Write all lines between occurrences of the strings start and stop: /start/, /stop/ 16. Write all lines whose first field is different from the previous one: $1 != prev { print; prev = $1 } 17. Simulate echo: BEGIN { for (i = 1; i < ARGC; ++i) printf("%s%s", ARGV[i], i==ARGC-1?"\n":" ") } 18. Write the path prefixes contained in the PATH environment variable, one per line: BEGIN { n = split (ENVIRON["PATH"], path, ":") for (i = 1; i <= n; ++i) print path[i] } 19. If there is a file named input containing page headers of the form: Page # and a file named program that contains: /Page/ { $2 = n++; } { print } then the command line: awk -f program n=5 input prints the file input, filling in page numbers starting at 5. RATIONALE top This description is based on the new awk, ``nawk'', (see the referenced The AWK Programming Language), which introduced a number of new features to the historical awk: 1. New keywords: delete, do, function, return 2. New built-in functions: atan2, close, cos, gsub, match, rand, sin, srand, sub, system 3. New predefined variables: FNR, ARGC, ARGV, RSTART, RLENGTH, SUBSEP 4. New expression operators: ?, :, ,, ^ 5. The FS variable and the third argument to split, now treated as extended regular expressions. 6. The operator precedence, changed to more closely match the C language. Two examples of code that operate differently are: while ( n /= 10 > 1) ... if (!"wk" ~ /bwk/) ... Several features have been added based on newer implementations of awk: * Multiple instances of -f progfile are permitted. * The new option -v assignment. * The new predefined variable ENVIRON. * New built-in functions toupper and tolower. * More formatting capabilities are added to printf to match the ISO C standard. Earlier versions of this standard required implementations to support multiple adjacent <semicolon>s, lines with one or more <semicolon> before a rule (pattern-action pairs), and lines with only <semicolon>(s). These are not required by this standard and are considered poor programming practice, but can be accepted by an implementation of awk as an extension. The overall awk syntax has always been based on the C language, with a few features from the shell command language and other sources. Because of this, it is not completely compatible with any other language, which has caused confusion for some users. It is not the intent of the standard developers to address such issues. A few relatively minor changes toward making the language more compatible with the ISO C standard were made; most of these changes are based on similar changes in recent implementations, as described above. There remain several C-language conventions that are not in awk. One of the notable ones is the <comma> operator, which is commonly used to specify multiple expressions in the C language for statement. Also, there are various places where awk is more restrictive than the C language regarding the type of expression that can be used in a given context. These limitations are due to the different features that the awk language does provide. Regular expressions in awk have been extended somewhat from historical implementations to make them a pure superset of extended regular expressions, as defined by POSIX.12008 (see the Base Definitions volume of POSIX.12017, Section 9.4, Extended Regular Expressions). The main extensions are internationalization features and interval expressions. Historical implementations of awk have long supported <backslash>-escape sequences as an extension to extended regular expressions, and this extension has been retained despite inconsistency with other utilities. The number of escape sequences recognized in both extended regular expressions and strings has varied (generally increasing with time) among implementations. The set specified by POSIX.12008 includes most sequences known to be supported by popular implementations and by the ISO C standard. One sequence that is not supported is hexadecimal value escapes beginning with '\x'. This would allow values expressed in more than 9 bits to be used within awk as in the ISO C standard. However, because this syntax has a non- deterministic length, it does not permit the subsequent character to be a hexadecimal digit. This limitation can be dealt with in the C language by the use of lexical string concatenation. In the awk language, concatenation could also be a solution for strings, but not for extended regular expressions (either lexical ERE tokens or strings used dynamically as regular expressions). Because of this limitation, the feature has not been added to POSIX.12008. When a string variable is used in a context where an extended regular expression normally appears (where the lexical token ERE is used in the grammar) the string does not contain the literal <slash> characters. Some versions of awk allow the form: func name(args, ... ) { statements } This has been deprecated by the authors of the language, who asked that it not be specified. Historical implementations of awk produce an error if a next statement is executed in a BEGIN action, and cause awk to terminate if a next statement is executed in an END action. This behavior has not been documented, and it was not believed that it was necessary to standardize it. The specification of conversions between string and numeric values is much more detailed than in the documentation of historical implementations or in the referenced The AWK Programming Language. Although most of the behavior is designed to be intuitive, the details are necessary to ensure compatible behavior from different implementations. This is especially important in relational expressions since the types of the operands determine whether a string or numeric comparison is performed. From the perspective of an application developer, it is usually sufficient to expect intuitive behavior and to force conversions (by adding zero or concatenating a null string) when the type of an expression does not obviously match what is needed. The intent has been to specify historical practice in almost all cases. The one exception is that, in historical implementations, variables and constants maintain both string and numeric values after their original value is converted by any use. This means that referencing a variable or constant can have unexpected side-effects. For example, with historical implementations the following program: { a = "+2" b = 2 if (NR % 2) c = a + b if (a == b) print "numeric comparison" else print "string comparison" } would perform a numeric comparison (and output numeric comparison) for each odd-numbered line, but perform a string comparison (and output string comparison) for each even-numbered line. POSIX.12008 ensures that comparisons will be numeric if necessary. With historical implementations, the following program: BEGIN { OFMT = "%e" print 3.14 OFMT = "%f" print 3.14 } would output "3.140000e+00" twice, because in the second print statement the constant "3.14" would have a string value from the previous conversion. POSIX.12008 requires that the output of the second print statement be "3.140000". The behavior of historical implementations was seen as too unintuitive and unpredictable. It was pointed out that with the rules contained in early drafts, the following script would print nothing: BEGIN { y[1.5] = 1 OFMT = "%e" print y[1.5] } Therefore, a new variable, CONVFMT, was introduced. The OFMT variable is now restricted to affecting output conversions of numbers to strings and CONVFMT is used for internal conversions, such as comparisons or array indexing. The default value is the same as that for OFMT, so unless a program changes CONVFMT (which no historical program would do), it will receive the historical behavior associated with internal string conversions. The POSIX awk lexical and syntactic conventions are specified more formally than in other sources. Again the intent has been to specify historical practice. One convention that may not be obvious from the formal grammar as in other verbal descriptions is where <newline> characters are acceptable. There are several obvious placements such as terminating a statement, and a <backslash> can be used to escape <newline> characters between any lexical tokens. In addition, <newline> characters without <backslash> characters can follow a comma, an open brace, a logical AND operator ("&&"), a logical OR operator ("||"), the do keyword, the else keyword, and the closing parenthesis of an if, for, or while statement. For example: { print $1, $2 } The requirement that awk add a trailing <newline> to the program argument text is to simplify the grammar, making it match a text file in form. There is no way for an application or test suite to determine whether a literal <newline> is added or whether awk simply acts as if it did. POSIX.12008 requires several changes from historical implementations in order to support internationalization. Probably the most subtle of these is the use of the decimal-point character, defined by the LC_NUMERIC category of the locale, in representations of floating-point numbers. This locale-specific character is used in recognizing numeric input, in converting between strings and numeric values, and in formatting output. However, regardless of locale, the <period> character (the decimal-point character of the POSIX locale) is the decimal-point character recognized in processing awk programs (including assignments in command line arguments). This is essentially the same convention as the one used in the ISO C standard. The difference is that the C language includes the setlocale() function, which permits an application to modify its locale. Because of this capability, a C application begins executing with its locale set to the C locale, and only executes in the environment-specified locale after an explicit call to setlocale(). However, adding such an elaborate new feature to the awk language was seen as inappropriate for POSIX.12008. It is possible to execute an awk program explicitly in any desired locale by setting the environment in the shell. The undefined behavior resulting from NULs in extended regular expressions allows future extensions for the GNU gawk program to process binary data. The behavior in the case of invalid awk programs (including lexical, syntactic, and semantic errors) is undefined because it was considered overly limiting on implementations to specify. In most cases such errors can be expected to produce a diagnostic and a non-zero exit status. However, some implementations may choose to extend the language in ways that make use of certain invalid constructs. Other invalid constructs might be deemed worthy of a warning, but otherwise cause some reasonable behavior. Still other constructs may be very difficult to detect in some implementations. Also, different implementations might detect a given error during an initial parsing of the program (before reading any input files) while others might detect it when executing the program after reading some input. Implementors should be aware that diagnosing errors as early as possible and producing useful diagnostics can ease debugging of applications, and thus make an implementation more usable. The unspecified behavior from using multi-character RS values is to allow possible future extensions based on extended regular expressions used for record separators. Historical implementations take the first character of the string and ignore the others. Unspecified behavior when split(string,array,<null>) is used is to allow a proposed future extension that would split up a string into an array of individual characters. In the context of the getline function, equally good arguments for different precedences of the | and < operators can be made. Historical practice has been that: getline < "a" "b" is parsed as: ( getline < "a" ) "b" although many would argue that the intent was that the file ab should be read. However: getline < "x" + 1 parses as: getline < ( "x" + 1 ) Similar problems occur with the | version of getline, particularly in combination with $. For example: $"echo hi" | getline (This situation is particularly problematic when used in a print statement, where the |getline part might be a redirection of the print.) Since in most cases such constructs are not (or at least should not) be used (because they have a natural ambiguity for which there is no conventional parsing), the meaning of these constructs has been made explicitly unspecified. (The effect is that a conforming application that runs into the problem must parenthesize to resolve the ambiguity.) There appeared to be few if any actual uses of such constructs. Grammars can be written that would cause an error under these circumstances. Where backwards-compatibility is not a large consideration, implementors may wish to use such grammars. Some historical implementations have allowed some built-in functions to be called without an argument list, the result being a default argument list chosen in some ``reasonable'' way. Use of length as a synonym for length($0) is the only one of these forms that is thought to be widely known or widely used; this particular form is documented in various places (for example, most historical awk reference pages, although not in the referenced The AWK Programming Language) as legitimate practice. With this exception, default argument lists have always been undocumented and vaguely defined, and it is not at all clear how (or if) they should be generalized to user-defined functions. They add no useful functionality and preclude possible future extensions that might need to name functions without calling them. Not standardizing them seems the simplest course. The standard developers considered that length merited special treatment, however, since it has been documented in the past and sees possibly substantial use in historical programs. Accordingly, this usage has been made legitimate, but Issue 5 removed the obsolescent marking for XSI-conforming implementations and many otherwise conforming applications depend on this feature. In sub and gsub, if repl is a string literal (the lexical token STRING), then two consecutive <backslash> characters should be used in the string to ensure a single <backslash> will precede the <ampersand> when the resultant string is passed to the function. (For example, to specify one literal <ampersand> in the replacement string, use gsub(ERE, "\\&").) Historically, the only special character in the repl argument of sub and gsub string functions was the <ampersand> ('&') character and preceding it with the <backslash> character was used to turn off its special meaning. The description in the ISO POSIX2:1993 standard introduced behavior such that the <backslash> character was another special character and it was unspecified whether there were any other special characters. This description introduced several portability problems, some of which are described below, and so it has been replaced with the more historical description. Some of the problems include: * Historically, to create the replacement string, a script could use gsub(ERE, "\\&"), but with the ISO POSIX2:1993 standard wording, it was necessary to use gsub(ERE, "\\\\&"). The <backslash> characters are doubled here because all string literals are subject to lexical analysis, which would reduce each pair of <backslash> characters to a single <backslash> before being passed to gsub. * Since it was unspecified what the special characters were, for portable scripts to guarantee that characters are printed literally, each character had to be preceded with a <backslash>. (For example, a portable script had to use gsub(ERE, "\\h\\i") to produce a replacement string of "hi".) The description for comparisons in the ISO POSIX2:1993 standard did not properly describe historical practice because of the way numeric strings are compared as numbers. The current rules cause the following code: if (0 == "000") print "strange, but true" else print "not true" to do a numeric comparison, causing the if to succeed. It should be intuitively obvious that this is incorrect behavior, and indeed, no historical implementation of awk actually behaves this way. To fix this problem, the definition of numeric string was enhanced to include only those values obtained from specific circumstances (mostly external sources) where it is not possible to determine unambiguously whether the value is intended to be a string or a numeric. Variables that are assigned to a numeric string shall also be treated as a numeric string. (For example, the notion of a numeric string can be propagated across assignments.) In comparisons, all variables having the uninitialized value are to be treated as a numeric operand evaluating to the numeric value zero. Uninitialized variables include all types of variables including scalars, array elements, and fields. The definition of an uninitialized value in Variables and Special Variables is necessary to describe the value placed on uninitialized variables and on fields that are valid (for example, < $NF) but have no characters in them and to describe how these variables are to be used in comparisons. A valid field, such as $1, that has no characters in it can be obtained from an input line of "\t\t" when FS='\t'. Historically, the comparison ($1<10) was done numerically after evaluating $1 to the value zero. The phrase ``... also shall have the numeric value of the numeric string'' was removed from several sections of the ISO POSIX2:1993 standard because is specifies an unnecessary implementation detail. It is not necessary for POSIX.12008 to specify that these objects be assigned two different values. It is only necessary to specify that these objects may evaluate to two different values depending on context. Historical implementations of awk did not parse hexadecimal integer or floating constants like "0xa" and "0xap0". Due to an oversight, the 2001 through 2004 editions of this standard required support for hexadecimal floating constants. This was due to the reference to atof(). This version of the standard allows but does not require implementations to use atof() and includes a description of how floating-point numbers are recognized as an alternative to match historic behavior. The intent of this change is to allow implementations to recognize floating-point constants according to either the ISO/IEC 9899:1990 standard or ISO/IEC 9899:1999 standard, and to allow (but not require) implementations to recognize hexadecimal integer constants. Historical implementations of awk did not support floating-point infinities and NaNs in numeric strings; e.g., "-INF" and "NaN". However, implementations that use the atof() or strtod() functions to do the conversion picked up support for these values if they used a ISO/IEC 9899:1999 standard version of the function instead of a ISO/IEC 9899:1990 standard version. Due to an oversight, the 2001 through 2004 editions of this standard did not allow support for infinities and NaNs, but in this revision support is allowed (but not required). This is a silent change to the behavior of awk programs; for example, in the POSIX locale the expression: ("-INF" + 0 < 0) formerly had the value 0 because "-INF" converted to 0, but now it may have the value 0 or 1. FUTURE DIRECTIONS top A future version of this standard may require the "!=" and "==" operators to perform string comparisons by checking if the strings are identical (and not by checking if they collate equally). SEE ALSO top Section 1.3, Grammar Conventions, grep(1p), lex(1p), sed(1p) The Base Definitions volume of POSIX.12017, Chapter 5, File Format Notation, Section 6.1, Portable Character Set, Chapter 8, Environment Variables, Chapter 9, Regular Expressions, Section 12.2, Utility Syntax Guidelines The System Interfaces volume of POSIX.12017, atof(3p), exec(1p), isspace(3p), popen(3p), setlocale(3p), strtod(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 AWK(1P) Pages that refer to this page: bc(1p), colrm(1), join(1p), printf(1p), sed(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. tac(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tac(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TAC(1) User Commands TAC(1) NAME top tac - concatenate and print files in reverse SYNOPSIS top tac [OPTION]... [FILE]... DESCRIPTION top Write each FILE to standard output, last line first. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -b, --before attach the separator before instead of after -r, --regex interpret the separator as a regular expression -s, --separator=STRING use STRING as the separator instead of newline --help display this help and exit --version output version information and exit AUTHOR top Written by Jay Lepreau 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 cat(1), rev(1) Full documentation <https://www.gnu.org/software/coreutils/tac> or available locally via: info '(coreutils) tac 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 TAC(1) Pages that refer to this page: cat(1), rev(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. diff(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training diff(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON DIFF(1) User Commands DIFF(1) NAME top diff - compare files line by line SYNOPSIS top diff [OPTION]... FILES DESCRIPTION top Compare FILES line by line. Mandatory arguments to long options are mandatory for short options too. --normal output a normal diff (the default) -q, --brief report only when files differ -s, --report-identical-files report when two files are the same -c, -C NUM, --context[=NUM] output NUM (default 3) lines of copied context -u, -U NUM, --unified[=NUM] output NUM (default 3) lines of unified context -e, --ed output an ed script -n, --rcs output an RCS format diff -y, --side-by-side output in two columns -W, --width=NUM output at most NUM (default 130) print columns --left-column output only the left column of common lines --suppress-common-lines do not output common lines -p, --show-c-function show which C function each change is in -F, --show-function-line=RE show the most recent line matching RE --label LABEL use LABEL instead of file name and timestamp (can be repeated) -t, --expand-tabs expand tabs to spaces in output -T, --initial-tab make tabs line up by prepending a tab --tabsize=NUM tab stops every NUM (default 8) print columns --suppress-blank-empty suppress space or tab before empty output lines -l, --paginate pass output through 'pr' to paginate it -r, --recursive recursively compare any subdirectories found --no-dereference don't follow symbolic links -N, --new-file treat absent files as empty --unidirectional-new-file treat absent first files as empty --ignore-file-name-case ignore case when comparing file names --no-ignore-file-name-case consider case when comparing file names -x, --exclude=PAT exclude files that match PAT -X, --exclude-from=FILE exclude files that match any pattern in FILE -S, --starting-file=FILE start with FILE when comparing directories --from-file=FILE1 compare FILE1 to all operands; FILE1 can be a directory --to-file=FILE2 compare all operands to FILE2; FILE2 can be a directory -i, --ignore-case ignore case differences in file contents -E, --ignore-tab-expansion ignore changes due to tab expansion -Z, --ignore-trailing-space ignore white space at line end -b, --ignore-space-change ignore changes in the amount of white space -w, --ignore-all-space ignore all white space -B, --ignore-blank-lines ignore changes where lines are all blank -I, --ignore-matching-lines=RE ignore changes where all lines match RE -a, --text treat all files as text --strip-trailing-cr strip trailing carriage return on input -D, --ifdef=NAME output merged file with '#ifdef NAME' diffs --GTYPE-group-format=GFMT format GTYPE input groups with GFMT --line-format=LFMT format all input lines with LFMT --LTYPE-line-format=LFMT format LTYPE input lines with LFMT These format options provide fine-grained control over the output of diff, generalizing -D/--ifdef. LTYPE is 'old', 'new', or 'unchanged'. GTYPE is LTYPE or 'changed'. GFMT (only) may contain: %< lines from FILE1 %> lines from FILE2 %= lines common to FILE1 and FILE2 %[-][WIDTH][.[PREC]]{doxX}LETTER printf-style spec for LETTER LETTERs are as follows for new group, lower case for old group: F first line number L last line number N number of lines = L-F+1 E F-1 M L+1 %(A=B?T:E) if A equals B then T else E LFMT (only) may contain: %L contents of line %l contents of line, excluding any trailing newline %[-][WIDTH][.[PREC]]{doxX}n printf-style spec for input line number Both GFMT and LFMT may contain: %% % %c'C' the single character C %c'\OOO' the character with octal code OOO C the character C (other characters represent themselves) -d, --minimal try hard to find a smaller set of changes --horizon-lines=NUM keep NUM lines of the common prefix and suffix --speed-large-files assume large files and many scattered small changes --color[=WHEN] color output; WHEN is 'never', 'always', or 'auto'; plain --color means --color='auto' --palette=PALETTE the colors to use when --color is active; PALETTE is a colon-separated list of terminfo capabilities --help display this help and exit -v, --version output version information and exit FILES are 'FILE1 FILE2' or 'DIR1 DIR2' or 'DIR FILE' or 'FILE DIR'. If --from-file or --to-file is given, there are no restrictions on FILE(s). If a FILE is '-', read standard input. Exit status is 0 if inputs are the same, 1 if different, 2 if trouble. AUTHOR top Written by Paul Eggert, Mike Haertel, David Hayes, Richard Stallman, and Len Tower. REPORTING BUGS top Report bugs to: bug-diffutils@gnu.org GNU diffutils home page: <https://www.gnu.org/software/diffutils/> General help using GNU software: <https://www.gnu.org/gethelp/> 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 wdiff(1), cmp(1), diff3(1), sdiff(1), patch(1) The full documentation for diff is maintained as a Texinfo manual. If the info and diff programs are properly installed at your site, the command info diff should give you access to the complete manual. COLOPHON top This page is part of the diffutils (GNU diff utilities) project. Information about the project can be found at http://savannah.gnu.org/projects/diffutils/. If you have a bug report for this manual page, send it to bug-diffutils@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/diffutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-20.) 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 diffutils 3.10.207-774b December 2023 DIFF(1) Pages that refer to this page: cmp(1), diff3(1), gendiff(1), grep(1), patch(1), quilt(1), sdiff(1), suffixes(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: test if the 2nd column in file A is in the reverse order of the second column of file B Bash Command:<START>diff --brief <(awk '{print $2}' A) <(tac B | awk '{print $2}')<END>
this find command Substitute space with underscore in the file name replaces space in all the *.mp3 files with _
find . -type f -iname '*.mp3' -exec rename '/ /_/' {} \;
['find', 'rename']
Output a Bash command to accomplish the following task. Task: this find command Substitute space with underscore in the file name replaces space in all the *.mp3 files with _ Bash Command:<START>find . -type f -iname '*.mp3' -exec rename '/ /_/' {} \;<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: this find command Substitute space with underscore in the file name replaces space in all the *.mp3 files with _ Bash Command:<START>find . -type f -iname '*.mp3' -exec rename '/ /_/' {} \;<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: this find command Substitute space with underscore in the file name replaces space in all the *.mp3 files with _ Bash Command:<START>find . -type f -iname '*.mp3' -exec rename '/ /_/' {} \;<END>