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
Compare each file in "repos1/" and "repos2/", treat absent files as empty, ignore differences in whitespace and tab expansions, and print 3 lines of unified context
diff -ENwbur repos1/ repos2/
['diff']
Output a Bash command to accomplish the following task. Task: Compare each file in "repos1/" and "repos2/", treat absent files as empty, ignore differences in whitespace and tab expansions, and print 3 lines of unified context Bash Command:<START>diff -ENwbur repos1/ repos2/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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: Compare each file in "repos1/" and "repos2/", treat absent files as empty, ignore differences in whitespace and tab expansions, and print 3 lines of unified context Bash Command:<START>diff -ENwbur repos1/ repos2/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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: Compare each file in "repos1/" and "repos2/", treat absent files as empty, ignore differences in whitespace and tab expansions, and print 3 lines of unified context Bash Command:<START>diff -ENwbur repos1/ repos2/<END>
Compare files "A1" and "A2" with 3 lines of unified context and print lines beginning with "+"
diff -u A1 A2 | grep -E "^\+"
['grep', 'diff']
Output a Bash command to accomplish the following task. Task: Compare files "A1" and "A2" with 3 lines of unified context and print lines beginning with "+" Bash Command:<START>diff -u A1 A2 | grep -E "^\+"<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 # 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: Compare files "A1" and "A2" with 3 lines of unified context and print lines beginning with "+" Bash Command:<START>diff -u A1 A2 | grep -E "^\+"<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. 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: Compare files "A1" and "A2" with 3 lines of unified context and print lines beginning with "+" Bash Command:<START>diff -u A1 A2 | grep -E "^\+"<END>
Compare files 'file1' and 'file2' and print in three columns strings unique for first file, second file, and common ones
comm abc def
['comm']
Output a Bash command to accomplish the following task. Task: Compare files 'file1' and 'file2' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm abc def<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # comm\n\n> Select or reject lines common to two files. Both files must be sorted.\n> More information: <https://www.gnu.org/software/coreutils/comm>.\n\n- Produce three tab-separated columns: lines only in first file, lines only in second file and common lines:\n\n`comm {{file1}} {{file2}}`\n\n- Print only lines common to both files:\n\n`comm -12 {{file1}} {{file2}}`\n\n- Print only lines common to both files, reading one file from `stdin`:\n\n`cat {{file1}} | comm -12 - {{file2}}`\n\n- Get lines only found in first file, saving the result to a third file:\n\n`comm -23 {{file1}} {{file2}} > {{file1_only}}`\n\n- Print lines only found in second file, when the files aren't sorted:\n\n`comm -13 <(sort {{file1}}) <(sort {{file2}})`\n Task: Compare files 'file1' and 'file2' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm abc def<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: comm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training comm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON COMM(1) User Commands COMM(1) NAME top comm - compare two sorted files line by line SYNOPSIS top comm [OPTION]... FILE1 FILE2 DESCRIPTION top Compare sorted files FILE1 and FILE2 line by line. When FILE1 or FILE2 (not both) is -, read standard input. With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files. -1 suppress column 1 (lines unique to FILE1) -2 suppress column 2 (lines unique to FILE2) -3 suppress column 3 (lines that appear in both files) --check-order check that the input is correctly sorted, even if all input lines are pairable --nocheck-order do not check that the input is correctly sorted --output-delimiter=STR separate columns with STR --total output a summary -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit Note, comparisons honor the rules specified by 'LC_COLLATE'. EXAMPLES top comm -12 file1 file2 Print only lines present in both file1 and file2. comm -3 file1 file2 Print lines in file1 not in file2, and vice versa. 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 join(1), uniq(1) Full documentation <https://www.gnu.org/software/coreutils/comm> or available locally via: info '(coreutils) comm 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 COMM(1) Pages that refer to this page: join(1), uniq(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: Compare files 'file1' and 'file2' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm abc def<END>
Compare files in "/tmp/dir1" and "/tmp/dir2", treat absent files as empty and all files as text, and print 3 lines of unified context
diff -Naur dir1/ dir2
['diff']
Output a Bash command to accomplish the following task. Task: Compare files in "/tmp/dir1" and "/tmp/dir2", treat absent files as empty and all files as text, and print 3 lines of unified context Bash Command:<START>diff -Naur dir1/ dir2<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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: Compare files in "/tmp/dir1" and "/tmp/dir2", treat absent files as empty and all files as text, and print 3 lines of unified context Bash Command:<START>diff -Naur dir1/ dir2<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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: Compare files in "/tmp/dir1" and "/tmp/dir2", treat absent files as empty and all files as text, and print 3 lines of unified context Bash Command:<START>diff -Naur dir1/ dir2<END>
Compare files in "/tmp/dir1" and "/tmp/dir2", treating absent files as empty and all files as text
diff -Nar /tmp/dir1 /tmp/dir2/
['diff']
Output a Bash command to accomplish the following task. Task: Compare files in "/tmp/dir1" and "/tmp/dir2", treating absent files as empty and all files as text Bash Command:<START>diff -Nar /tmp/dir1 /tmp/dir2/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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: Compare files in "/tmp/dir1" and "/tmp/dir2", treating absent files as empty and all files as text Bash Command:<START>diff -Nar /tmp/dir1 /tmp/dir2/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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: Compare files in "/tmp/dir1" and "/tmp/dir2", treating absent files as empty and all files as text Bash Command:<START>diff -Nar /tmp/dir1 /tmp/dir2/<END>
Compare sorted files 'f1.txt' and 'f2.txt' and print in three columns strings unique for first file, second file, and common ones
comm <(sort -n f1.txt) <(sort -n f2.txt)
['sort', 'comm']
Output a Bash command to accomplish the following task. Task: Compare sorted files 'f1.txt' and 'f2.txt' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm <(sort -n f1.txt) <(sort -n f2.txt)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # comm\n\n> Select or reject lines common to two files. Both files must be sorted.\n> More information: <https://www.gnu.org/software/coreutils/comm>.\n\n- Produce three tab-separated columns: lines only in first file, lines only in second file and common lines:\n\n`comm {{file1}} {{file2}}`\n\n- Print only lines common to both files:\n\n`comm -12 {{file1}} {{file2}}`\n\n- Print only lines common to both files, reading one file from `stdin`:\n\n`cat {{file1}} | comm -12 - {{file2}}`\n\n- Get lines only found in first file, saving the result to a third file:\n\n`comm -23 {{file1}} {{file2}} > {{file1_only}}`\n\n- Print lines only found in second file, when the files aren't sorted:\n\n`comm -13 <(sort {{file1}}) <(sort {{file2}})`\n Task: Compare sorted files 'f1.txt' and 'f2.txt' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm <(sort -n f1.txt) <(sort -n f2.txt)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. comm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training comm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON COMM(1) User Commands COMM(1) NAME top comm - compare two sorted files line by line SYNOPSIS top comm [OPTION]... FILE1 FILE2 DESCRIPTION top Compare sorted files FILE1 and FILE2 line by line. When FILE1 or FILE2 (not both) is -, read standard input. With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files. -1 suppress column 1 (lines unique to FILE1) -2 suppress column 2 (lines unique to FILE2) -3 suppress column 3 (lines that appear in both files) --check-order check that the input is correctly sorted, even if all input lines are pairable --nocheck-order do not check that the input is correctly sorted --output-delimiter=STR separate columns with STR --total output a summary -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit Note, comparisons honor the rules specified by 'LC_COLLATE'. EXAMPLES top comm -12 file1 file2 Print only lines present in both file1 and file2. comm -3 file1 file2 Print lines in file1 not in file2, and vice versa. 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 join(1), uniq(1) Full documentation <https://www.gnu.org/software/coreutils/comm> or available locally via: info '(coreutils) comm 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 COMM(1) Pages that refer to this page: join(1), uniq(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: Compare sorted files 'f1.txt' and 'f2.txt' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm <(sort -n f1.txt) <(sort -n f2.txt)<END>
Compare sorted files 'f1.txt' and 'f2.txt' and print in three columns strings unique for first file, second file, and common ones
comm <(sort f1.txt) <(sort f2.txt)
['sort', 'comm']
Output a Bash command to accomplish the following task. Task: Compare sorted files 'f1.txt' and 'f2.txt' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm <(sort f1.txt) <(sort f2.txt)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # comm\n\n> Select or reject lines common to two files. Both files must be sorted.\n> More information: <https://www.gnu.org/software/coreutils/comm>.\n\n- Produce three tab-separated columns: lines only in first file, lines only in second file and common lines:\n\n`comm {{file1}} {{file2}}`\n\n- Print only lines common to both files:\n\n`comm -12 {{file1}} {{file2}}`\n\n- Print only lines common to both files, reading one file from `stdin`:\n\n`cat {{file1}} | comm -12 - {{file2}}`\n\n- Get lines only found in first file, saving the result to a third file:\n\n`comm -23 {{file1}} {{file2}} > {{file1_only}}`\n\n- Print lines only found in second file, when the files aren't sorted:\n\n`comm -13 <(sort {{file1}}) <(sort {{file2}})`\n Task: Compare sorted files 'f1.txt' and 'f2.txt' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm <(sort f1.txt) <(sort f2.txt)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. comm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training comm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON COMM(1) User Commands COMM(1) NAME top comm - compare two sorted files line by line SYNOPSIS top comm [OPTION]... FILE1 FILE2 DESCRIPTION top Compare sorted files FILE1 and FILE2 line by line. When FILE1 or FILE2 (not both) is -, read standard input. With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files. -1 suppress column 1 (lines unique to FILE1) -2 suppress column 2 (lines unique to FILE2) -3 suppress column 3 (lines that appear in both files) --check-order check that the input is correctly sorted, even if all input lines are pairable --nocheck-order do not check that the input is correctly sorted --output-delimiter=STR separate columns with STR --total output a summary -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit Note, comparisons honor the rules specified by 'LC_COLLATE'. EXAMPLES top comm -12 file1 file2 Print only lines present in both file1 and file2. comm -3 file1 file2 Print lines in file1 not in file2, and vice versa. 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 join(1), uniq(1) Full documentation <https://www.gnu.org/software/coreutils/comm> or available locally via: info '(coreutils) comm 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 COMM(1) Pages that refer to this page: join(1), uniq(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: Compare sorted files 'f1.txt' and 'f2.txt' and print in three columns strings unique for first file, second file, and common ones Bash Command:<START>comm <(sort f1.txt) <(sort f2.txt)<END>
Compare text "hello" and "goodbye" line by line
diff <(echo hello) <(echo goodbye)
['diff', 'echo']
Output a Bash command to accomplish the following task. Task: Compare text "hello" and "goodbye" line by line Bash Command:<START>diff <(echo hello) <(echo goodbye)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # 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: Compare text "hello" and "goodbye" line by line Bash Command:<START>diff <(echo hello) <(echo goodbye)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. 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: Compare text "hello" and "goodbye" line by line Bash Command:<START>diff <(echo hello) <(echo goodbye)<END>
Compare the contents of gzip-ompressed files "file1" and "file2"
diff <(zcat file1.gz) <(zcat file2.gz)
['zcat', 'diff']
Output a Bash command to accomplish the following task. Task: Compare the contents of gzip-ompressed files "file1" and "file2" Bash Command:<START>diff <(zcat file1.gz) <(zcat file2.gz)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # zcat\n\n> Print data from `gzip` compressed files.\n> More information: <https://www.gnu.org/software/gzip/manual/gzip.html>.\n\n- Print the uncompressed contents of a `gzip` archive to `stdout`:\n\n`zcat {{file.txt.gz}}`\n\n- Print compression details of a `gzip` archive to `stdout`:\n\n`zcat -l {{file.txt.gz}}`\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: Compare the contents of gzip-ompressed files "file1" and "file2" Bash Command:<START>diff <(zcat file1.gz) <(zcat file2.gz)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: zcat(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training zcat(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 ZCAT(1P) POSIX Programmer's Manual ZCAT(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 zcat expand and concatenate data SYNOPSIS top zcat [file...] DESCRIPTION top The zcat utility shall write to standard output the uncompressed form of files that have been compressed using the compress utility. It is the equivalent of uncompress -c. Input files are not affected. OPTIONS top None. OPERANDS top The following operand shall be supported: file The pathname of a file previously processed by the compress utility. If file already has the .Z suffix specified, it is used as submitted. Otherwise, the .Z suffix is appended to the filename prior to processing. STDIN top The standard input shall be used only if no file operands are specified, or if a file operand is '-'. INPUT FILES top Input files shall be compressed files that are in the format produced by the compress utility. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of zcat: LANG Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.12017, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.) LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments). LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. ASYNCHRONOUS EVENTS top Default. STDOUT top The compressed files given as input shall be written on standard output in their uncompressed form. STDERR top The standard error shall be used only for diagnostic messages. OUTPUT FILES top None. EXTENDED DESCRIPTION top None. EXIT STATUS top The following exit values shall be returned: 0 Successful completion. >0 An error occurred. CONSEQUENCES OF ERRORS top Default. The following sections are informative. APPLICATION USAGE top None. EXAMPLES top None. RATIONALE top None. FUTURE DIRECTIONS top None. SEE ALSO top compress(1p), uncompress(1p) The Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables 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 ZCAT(1P) Pages that refer to this page: compress(1p), uncompress(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. 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: Compare the contents of gzip-ompressed files "file1" and "file2" Bash Command:<START>diff <(zcat file1.gz) <(zcat file2.gz)<END>
Compare the files in 'FOLDER1' and 'FOLDER2' and show which ones are indentical and which ones differ
find FOLDER1 -type f -print0 | xargs -0 -I % find FOLDER2 -type f -exec diff -qs --from-file="%" '{}' \+
['find', 'xargs', 'diff']
Output a Bash command to accomplish the following task. Task: Compare the files in 'FOLDER1' and 'FOLDER2' and show which ones are indentical and which ones differ Bash Command:<START>find FOLDER1 -type f -print0 | xargs -0 -I % find FOLDER2 -type f -exec diff -qs --from-file="%" '{}' \+<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # 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 # 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: Compare the files in 'FOLDER1' and 'FOLDER2' and show which ones are indentical and which ones differ Bash Command:<START>find FOLDER1 -type f -print0 | xargs -0 -I % find FOLDER2 -type f -exec diff -qs --from-file="%" '{}' \+<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. 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. 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: Compare the files in 'FOLDER1' and 'FOLDER2' and show which ones are indentical and which ones differ Bash Command:<START>find FOLDER1 -type f -print0 | xargs -0 -I % find FOLDER2 -type f -exec diff -qs --from-file="%" '{}' \+<END>
Compares two listings 'ls' and 'ls *Music*', showing only strings that unique for first listing.
comm -23 <(ls) <(ls *Music*)
['ls', 'comm']
Output a Bash command to accomplish the following task. Task: Compares two listings 'ls' and 'ls *Music*', showing only strings that unique for first listing. Bash Command:<START>comm -23 <(ls) <(ls *Music*)<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 # comm\n\n> Select or reject lines common to two files. Both files must be sorted.\n> More information: <https://www.gnu.org/software/coreutils/comm>.\n\n- Produce three tab-separated columns: lines only in first file, lines only in second file and common lines:\n\n`comm {{file1}} {{file2}}`\n\n- Print only lines common to both files:\n\n`comm -12 {{file1}} {{file2}}`\n\n- Print only lines common to both files, reading one file from `stdin`:\n\n`cat {{file1}} | comm -12 - {{file2}}`\n\n- Get lines only found in first file, saving the result to a third file:\n\n`comm -23 {{file1}} {{file2}} > {{file1_only}}`\n\n- Print lines only found in second file, when the files aren't sorted:\n\n`comm -13 <(sort {{file1}}) <(sort {{file2}})`\n Task: Compares two listings 'ls' and 'ls *Music*', showing only strings that unique for first listing. Bash Command:<START>comm -23 <(ls) <(ls *Music*)<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. comm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training comm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON COMM(1) User Commands COMM(1) NAME top comm - compare two sorted files line by line SYNOPSIS top comm [OPTION]... FILE1 FILE2 DESCRIPTION top Compare sorted files FILE1 and FILE2 line by line. When FILE1 or FILE2 (not both) is -, read standard input. With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files. -1 suppress column 1 (lines unique to FILE1) -2 suppress column 2 (lines unique to FILE2) -3 suppress column 3 (lines that appear in both files) --check-order check that the input is correctly sorted, even if all input lines are pairable --nocheck-order do not check that the input is correctly sorted --output-delimiter=STR separate columns with STR --total output a summary -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit Note, comparisons honor the rules specified by 'LC_COLLATE'. EXAMPLES top comm -12 file1 file2 Print only lines present in both file1 and file2. comm -3 file1 file2 Print lines in file1 not in file2, and vice versa. 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 join(1), uniq(1) Full documentation <https://www.gnu.org/software/coreutils/comm> or available locally via: info '(coreutils) comm 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 COMM(1) Pages that refer to this page: join(1), uniq(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: Compares two listings 'ls' and 'ls *Music*', showing only strings that unique for first listing. Bash Command:<START>comm -23 <(ls) <(ls *Music*)<END>
Compose filepath as folder path where file $SRC is located, and lowercase filename of $SRC file, and save it in 'DST' variable
DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'`
['dirname', 'basename', 'tr']
Output a Bash command to accomplish the following task. Task: Compose filepath as folder path where file $SRC is located, and lowercase filename of $SRC file, and save it in 'DST' variable Bash Command:<START>DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # dirname\n\n> Calculates the parent directory of a file or directory path.\n> More information: <https://www.gnu.org/software/coreutils/dirname>.\n\n- Calculate the parent directory of a given path:\n\n`dirname {{path/to/file_or_directory}}`\n\n- Calculate the parent directory of multiple paths:\n\n`dirname {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n\n- Delimit output with a NUL character instead of a newline (useful when combining with `xargs`):\n\n`dirname --zero {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n # basename\n\n> Remove leading directory portions from a path.\n> More information: <https://www.gnu.org/software/coreutils/basename>.\n\n- Show only the file name from a path:\n\n`basename {{path/to/file}}`\n\n- Show only the rightmost directory name from a path:\n\n`basename {{path/to/directory/}}`\n\n- Show only the file name from a path, with a suffix removed:\n\n`basename {{path/to/file}} {{suffix}}`\n # tr\n\n> Translate characters: run replacements based on single characters and character sets.\n> More information: <https://www.gnu.org/software/coreutils/tr>.\n\n- Replace all occurrences of a character in a file, and print the result:\n\n`tr {{find_character}} {{replace_character}} < {{path/to/file}}`\n\n- Replace all occurrences of a character from another command's output:\n\n`echo {{text}} | tr {{find_character}} {{replace_character}}`\n\n- Map each character of the first set to the corresponding character of the second set:\n\n`tr '{{abcd}}' '{{jkmn}}' < {{path/to/file}}`\n\n- Delete all occurrences of the specified set of characters from the input:\n\n`tr -d '{{input_characters}}' < {{path/to/file}}`\n\n- Compress a series of identical characters to a single character:\n\n`tr -s '{{input_characters}}' < {{path/to/file}}`\n\n- Translate the contents of a file to upper-case:\n\n`tr "[:lower:]" "[:upper:]" < {{path/to/file}}`\n\n- Strip out non-printable characters from a file:\n\n`tr -cd "[:print:]" < {{path/to/file}}`\n Task: Compose filepath as folder path where file $SRC is located, and lowercase filename of $SRC file, and save it in 'DST' variable Bash Command:<START>DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: dirname(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training dirname(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON DIRNAME(1) User Commands DIRNAME(1) NAME top dirname - strip last component from file name SYNOPSIS top dirname [OPTION] NAME... DESCRIPTION top Output each NAME with its last non-slash component and trailing slashes removed; if NAME contains no /'s, output '.' (meaning the current directory). -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit EXAMPLES top dirname /usr/bin/ -> "/usr" dirname dir1/str dir2/str -> "dir1" followed by "dir2" dirname stdio.h -> "." 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 basename(1), readlink(1) Full documentation <https://www.gnu.org/software/coreutils/dirname> or available locally via: info '(coreutils) dirname 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 DIRNAME(1) Pages that refer to this page: basename(1), basename(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. basename(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training basename(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON BASENAME(1) User Commands BASENAME(1) NAME top basename - strip directory and suffix from filenames SYNOPSIS top basename NAME [SUFFIX] basename OPTION... NAME... DESCRIPTION top Print NAME with any leading directory components removed. If specified, also remove a trailing SUFFIX. Mandatory arguments to long options are mandatory for short options too. -a, --multiple support multiple arguments and treat each as a NAME -s, --suffix=SUFFIX remove a trailing SUFFIX; implies -a -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit EXAMPLES top basename /usr/bin/sort -> "sort" basename include/stdio.h .h -> "stdio" basename -s .h include/stdio.h -> "stdio" basename -a any/str1 any/str2 -> "str1" followed by "str2" 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 dirname(1), readlink(1) Full documentation <https://www.gnu.org/software/coreutils/basename> or available locally via: info '(coreutils) basename 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 BASENAME(1) Pages that refer to this page: dirname(1), pmsignal(1), basename(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. tr(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tr(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | BUGS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TR(1) User Commands TR(1) NAME top tr - translate or delete characters SYNOPSIS top tr [OPTION]... STRING1 [STRING2] DESCRIPTION top Translate, squeeze, and/or delete characters from standard input, writing to standard output. STRING1 and STRING2 specify arrays of characters ARRAY1 and ARRAY2 that control the action. -c, -C, --complement use the complement of ARRAY1 -d, --delete delete characters in ARRAY1, do not translate -s, --squeeze-repeats replace each sequence of a repeated character that is listed in the last specified ARRAY, with a single occurrence of that character -t, --truncate-set1 first truncate ARRAY1 to length of ARRAY2 --help display this help and exit --version output version information and exit ARRAYs are specified as strings of characters. Most represent themselves. Interpreted sequences are: \NNN character with octal value NNN (1 to 3 octal digits) \\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab \v vertical tab CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in ARRAY2, copies of CHAR until length of ARRAY1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [:alnum:] all letters and digits [:alpha:] all letters [:blank:] all horizontal whitespace [:cntrl:] all control characters [:digit:] all digits [:graph:] all printable characters, not including space [:lower:] all lower case letters [:print:] all printable characters, including space [:punct:] all punctuation characters [:space:] all horizontal or vertical whitespace [:upper:] all upper case letters [:xdigit:] all hexadecimal digits [=CHAR=] all characters which are equivalent to CHAR Translation occurs if -d is not given and both STRING1 and STRING2 appear. -t is only significant when translating. ARRAY2 is extended to length of ARRAY1 by repeating its last character as necessary. Excess characters of ARRAY2 are ignored. Character classes expand in unspecified order; while translating, [:lower:] and [:upper:] may be used in pairs to specify case conversion. Squeezing occurs after translation or deletion. BUGS top Full support is available only for safe single-byte locales, in which every possible input byte represents a single character. The C locale is safe in GNU systems, so you can avoid this issue in the shell by running LC_ALL=C tr instead of plain tr. 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 Full documentation <https://www.gnu.org/software/coreutils/tr> or available locally via: info '(coreutils) tr 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 TR(1) Pages that refer to this page: sed(1), 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: Compose filepath as folder path where file $SRC is located, and lowercase filename of $SRC file, and save it in 'DST' variable Bash Command:<START>DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'`<END>
Compose filepath as folder path where file $f is located, and lowercase filename of $f file, and save it in 'g' variable
g=`dirname "$f"`/`basename "$f" | tr '[A-Z]' '[a-z]'`
['dirname', 'basename', 'tr']
Output a Bash command to accomplish the following task. Task: Compose filepath as folder path where file $f is located, and lowercase filename of $f file, and save it in 'g' variable Bash Command:<START>g=`dirname "$f"`/`basename "$f" | tr '[A-Z]' '[a-z]'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # dirname\n\n> Calculates the parent directory of a file or directory path.\n> More information: <https://www.gnu.org/software/coreutils/dirname>.\n\n- Calculate the parent directory of a given path:\n\n`dirname {{path/to/file_or_directory}}`\n\n- Calculate the parent directory of multiple paths:\n\n`dirname {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n\n- Delimit output with a NUL character instead of a newline (useful when combining with `xargs`):\n\n`dirname --zero {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n # basename\n\n> Remove leading directory portions from a path.\n> More information: <https://www.gnu.org/software/coreutils/basename>.\n\n- Show only the file name from a path:\n\n`basename {{path/to/file}}`\n\n- Show only the rightmost directory name from a path:\n\n`basename {{path/to/directory/}}`\n\n- Show only the file name from a path, with a suffix removed:\n\n`basename {{path/to/file}} {{suffix}}`\n # tr\n\n> Translate characters: run replacements based on single characters and character sets.\n> More information: <https://www.gnu.org/software/coreutils/tr>.\n\n- Replace all occurrences of a character in a file, and print the result:\n\n`tr {{find_character}} {{replace_character}} < {{path/to/file}}`\n\n- Replace all occurrences of a character from another command's output:\n\n`echo {{text}} | tr {{find_character}} {{replace_character}}`\n\n- Map each character of the first set to the corresponding character of the second set:\n\n`tr '{{abcd}}' '{{jkmn}}' < {{path/to/file}}`\n\n- Delete all occurrences of the specified set of characters from the input:\n\n`tr -d '{{input_characters}}' < {{path/to/file}}`\n\n- Compress a series of identical characters to a single character:\n\n`tr -s '{{input_characters}}' < {{path/to/file}}`\n\n- Translate the contents of a file to upper-case:\n\n`tr "[:lower:]" "[:upper:]" < {{path/to/file}}`\n\n- Strip out non-printable characters from a file:\n\n`tr -cd "[:print:]" < {{path/to/file}}`\n Task: Compose filepath as folder path where file $f is located, and lowercase filename of $f file, and save it in 'g' variable Bash Command:<START>g=`dirname "$f"`/`basename "$f" | tr '[A-Z]' '[a-z]'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: dirname(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training dirname(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON DIRNAME(1) User Commands DIRNAME(1) NAME top dirname - strip last component from file name SYNOPSIS top dirname [OPTION] NAME... DESCRIPTION top Output each NAME with its last non-slash component and trailing slashes removed; if NAME contains no /'s, output '.' (meaning the current directory). -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit EXAMPLES top dirname /usr/bin/ -> "/usr" dirname dir1/str dir2/str -> "dir1" followed by "dir2" dirname stdio.h -> "." 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 basename(1), readlink(1) Full documentation <https://www.gnu.org/software/coreutils/dirname> or available locally via: info '(coreutils) dirname 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 DIRNAME(1) Pages that refer to this page: basename(1), basename(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. basename(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training basename(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON BASENAME(1) User Commands BASENAME(1) NAME top basename - strip directory and suffix from filenames SYNOPSIS top basename NAME [SUFFIX] basename OPTION... NAME... DESCRIPTION top Print NAME with any leading directory components removed. If specified, also remove a trailing SUFFIX. Mandatory arguments to long options are mandatory for short options too. -a, --multiple support multiple arguments and treat each as a NAME -s, --suffix=SUFFIX remove a trailing SUFFIX; implies -a -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit EXAMPLES top basename /usr/bin/sort -> "sort" basename include/stdio.h .h -> "stdio" basename -s .h include/stdio.h -> "stdio" basename -a any/str1 any/str2 -> "str1" followed by "str2" 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 dirname(1), readlink(1) Full documentation <https://www.gnu.org/software/coreutils/basename> or available locally via: info '(coreutils) basename 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 BASENAME(1) Pages that refer to this page: dirname(1), pmsignal(1), basename(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. tr(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tr(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | BUGS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TR(1) User Commands TR(1) NAME top tr - translate or delete characters SYNOPSIS top tr [OPTION]... STRING1 [STRING2] DESCRIPTION top Translate, squeeze, and/or delete characters from standard input, writing to standard output. STRING1 and STRING2 specify arrays of characters ARRAY1 and ARRAY2 that control the action. -c, -C, --complement use the complement of ARRAY1 -d, --delete delete characters in ARRAY1, do not translate -s, --squeeze-repeats replace each sequence of a repeated character that is listed in the last specified ARRAY, with a single occurrence of that character -t, --truncate-set1 first truncate ARRAY1 to length of ARRAY2 --help display this help and exit --version output version information and exit ARRAYs are specified as strings of characters. Most represent themselves. Interpreted sequences are: \NNN character with octal value NNN (1 to 3 octal digits) \\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab \v vertical tab CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in ARRAY2, copies of CHAR until length of ARRAY1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [:alnum:] all letters and digits [:alpha:] all letters [:blank:] all horizontal whitespace [:cntrl:] all control characters [:digit:] all digits [:graph:] all printable characters, not including space [:lower:] all lower case letters [:print:] all printable characters, including space [:punct:] all punctuation characters [:space:] all horizontal or vertical whitespace [:upper:] all upper case letters [:xdigit:] all hexadecimal digits [=CHAR=] all characters which are equivalent to CHAR Translation occurs if -d is not given and both STRING1 and STRING2 appear. -t is only significant when translating. ARRAY2 is extended to length of ARRAY1 by repeating its last character as necessary. Excess characters of ARRAY2 are ignored. Character classes expand in unspecified order; while translating, [:lower:] and [:upper:] may be used in pairs to specify case conversion. Squeezing occurs after translation or deletion. BUGS top Full support is available only for safe single-byte locales, in which every possible input byte represents a single character. The C locale is safe in GNU systems, so you can avoid this issue in the shell by running LC_ALL=C tr instead of plain tr. 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 Full documentation <https://www.gnu.org/software/coreutils/tr> or available locally via: info '(coreutils) tr 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 TR(1) Pages that refer to this page: sed(1), 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: Compose filepath as folder path where file $f is located, and lowercase filename of $f file, and save it in 'g' variable Bash Command:<START>g=`dirname "$f"`/`basename "$f" | tr '[A-Z]' '[a-z]'`<END>
Composes full process tree with process id numbers, and prints only those strings that contain 'git'.
pstree -p | grep git
['grep', 'pstree', 'git']
Output a Bash command to accomplish the following task. Task: Composes full process tree with process id numbers, and prints only those strings that contain 'git'. Bash Command:<START>pstree -p | grep git<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 # pstree\n\n> A convenient tool to show running processes as a tree.\n> More information: <https://manned.org/pstree>.\n\n- Display a tree of processes:\n\n`pstree`\n\n- Display a tree of processes with PIDs:\n\n`pstree -p`\n\n- Display all process trees rooted at processes owned by specified user:\n\n`pstree {{user}}`\n # git\n\n> Distributed version control system.\n> Some subcommands such as `commit`, `add`, `branch`, `checkout`, `push`, etc. have their own usage documentation.\n> More information: <https://git-scm.com/>.\n\n- Execute a Git subcommand:\n\n`git {{subcommand}}`\n\n- Execute a Git subcommand on a custom repository root path:\n\n`git -C {{path/to/repo}} {{subcommand}}`\n\n- Execute a Git subcommand with a given configuration set:\n\n`git -c '{{config.key}}={{value}}' {{subcommand}}`\n\n- Display help:\n\n`git --help`\n\n- Display help for a specific subcommand (like `clone`, `add`, `push`, `log`, etc.):\n\n`git help {{subcommand}}`\n\n- Display version:\n\n`git --version`\n Task: Composes full process tree with process id numbers, and prints only those strings that contain 'git'. Bash Command:<START>pstree -p | grep git<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. pstree(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training pstree(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | FILES | BUGS | SEE ALSO | COLOPHON PSTREE(1) User Commands PSTREE(1) NAME top pstree - display a tree of processes SYNOPSIS top pstree [-a, --arguments] [-c, --compact-not] [-C, --color attr] [-g, --show-pgids] [-h, --highlight-all, -H pid, --highlight-pid pid] [-l, --long] [-n, --numeric-sort] [-N, --ns-sort ns] [-p, --show-pids] [-s, --show-parents] [-S, --ns-changes] [-t, --thread-names] [-T, --hide-threads] [-u, --uid-changes] [-Z, --security-context] [-A, --ascii, -G, --vt100, -U, --unicode] [pid, user] pstree -V, --version DESCRIPTION top pstree shows running processes as a tree. The tree is rooted at either pid or init if pid is omitted. If a user name is specified, all process trees rooted at processes owned by that user are shown. pstree visually merges identical branches by putting them in square brackets and prefixing them with the repetition count, e.g. init-+-getty |-getty |-getty `-getty becomes init---4*[getty] Child threads of a process are found under the parent process and are shown with the process name in curly braces, e.g. icecast2---13*[{icecast2}] If pstree is called as pstree.x11 then it will prompt the user at the end of the line to press return and will not return until that has happened. This is useful for when pstree is run in a xterminal. Certain kernel or mount parameters, such as the hidepid option for procfs, will hide information for some processes. In these situations pstree will attempt to build the tree without this information, showing process names as question marks. OPTIONS top -a Show command line arguments. If the command line of a process is swapped out, that process is shown in parentheses. -a implicitly disables compaction for processes but not threads. -A Use ASCII characters to draw the tree. -c Disable compaction of identical subtrees. By default, subtrees are compacted whenever possible. -C Color the process name by given attribute. Currently pstree only accepts the value age which colors by process age. Processes newer than 60 seconds are green, newer than an hour yellow and the remaining red. -g Show PGIDs. Process Group IDs are shown as decimal numbers in parentheses after each process name. If both PIDs and PGIDs are displayed then PIDs are shown first. -G Use VT100 line drawing characters. -h Highlight the current process and its ancestors. This is a no-op if the terminal doesn't support highlighting or if neither the current process nor any of its ancestors are in the subtree being shown. -H Like -h, but highlight the specified process instead. Unlike with -h, pstree fails when using -H if highlighting is not available. -l Display long lines. By default, lines are truncated to either the COLUMNS environment variable or the display width. If neither of these methods work, the default of 132 columns is used. -n Sort processes with the same parent by PID instead of by name. (Numeric sort.) -N Show individual trees for each namespace of the type specified. The available types are: ipc, mnt, net, pid, time, user, uts. Regular users don't have access to other users' processes information, so the output will be limited. -p Show PIDs. PIDs are shown as decimal numbers in parentheses after each process name. -p implicitly disables compaction. -s Show parent processes of the specified process. -S Show namespaces transitions. Like -N, the output is limited when running as a regular user. -t Show full names for threads when available. -T Hide threads and only show processes. -u Show uid transitions. Whenever the uid of a process differs from the uid of its parent, the new uid is shown in parentheses after the process name. -U Use UTF-8 (Unicode) line drawing characters. Under Linux 1.1-54 and above, UTF-8 mode is entered on the console with echo -e ' 33%8' and left with echo -e ' 33%@'. -V Display version information. -Z Show the current security attributes of the process. For SELinux systems this will be the security context. FILES top /proc location of the proc file system BUGS top Some character sets may be incompatible with the VT100 characters. SEE ALSO top ps(1), top(1), proc(5). COLOPHON top This page is part of the psmisc (Small utilities that use the /proc filesystem) project. Information about the project can be found at https://gitlab.com/psmisc/psmisc. If you have a bug report for this manual page, see https://gitlab.com/psmisc/psmisc/issues. This page was obtained from the project's upstream Git repository https://gitlab.com/psmisc/psmisc.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-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 psmisc 2021-06-21 PSTREE(1) Pages that refer to this page: ps(1), 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. git(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training git(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | GIT COMMANDS | HIGH-LEVEL COMMANDS (PORCELAIN) | LOW-LEVEL COMMANDS (PLUMBING) | GUIDES | REPOSITORY, COMMAND AND FILE INTERFACES | FILE FORMATS, PROTOCOLS AND OTHER DEVELOPER INTERFACES | CONFIGURATION MECHANISM | IDENTIFIER TERMINOLOGY | SYMBOLIC IDENTIFIERS | FILE/DIRECTORY STRUCTURE | TERMINOLOGY | ENVIRONMENT VARIABLES | DISCUSSION | FURTHER DOCUMENTATION | AUTHORS | REPORTING BUGS | SEE ALSO | GIT | NOTES | COLOPHON GIT(1) Git Manual GIT(1) NAME top git - the stupid content tracker SYNOPSIS top git [-v | --version] [-h | --help] [-C <path>] [-c <name>=<value>] [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path] [-p|--paginate|-P|--no-pager] [--no-replace-objects] [--bare] [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>] [--config-env=<name>=<envvar>] <command> [<args>] DESCRIPTION top Git is a fast, scalable, distributed revision control system with an unusually rich command set that provides both high-level operations and full access to internals. See gittutorial(7) to get started, then see giteveryday(7) for a useful minimum set of commands. The Git Users Manual[1] has a more in-depth introduction. After you mastered the basic concepts, you can come back to this page to learn what commands Git offers. You can learn more about individual Git commands with "git help command". gitcli(7) manual page gives you an overview of the command-line command syntax. A formatted and hyperlinked copy of the latest Git documentation can be viewed at https://git.github.io/htmldocs/git.html or https://git-scm.com/docs . OPTIONS top -v, --version Prints the Git suite version that the git program came from. This option is internally converted to git version ... and accepts the same options as the git-version(1) command. If --help is also given, it takes precedence over --version. -h, --help Prints the synopsis and a list of the most commonly used commands. If the option --all or -a is given then all available commands are printed. If a Git command is named this option will bring up the manual page for that command. Other options are available to control how the manual page is displayed. See git-help(1) for more information, because git --help ... is converted internally into git help .... -C <path> Run as if git was started in <path> instead of the current working directory. When multiple -C options are given, each subsequent non-absolute -C <path> is interpreted relative to the preceding -C <path>. If <path> is present but empty, e.g. -C "", then the current working directory is left unchanged. This option affects options that expect path name like --git-dir and --work-tree in that their interpretations of the path names would be made relative to the working directory caused by the -C option. For example the following invocations are equivalent: git --git-dir=a.git --work-tree=b -C c status git --git-dir=c/a.git --work-tree=c/b status -c <name>=<value> Pass a configuration parameter to the command. The value given will override values from configuration files. The <name> is expected in the same format as listed by git config (subkeys separated by dots). Note that omitting the = in git -c foo.bar ... is allowed and sets foo.bar to the boolean true value (just like [foo]bar would in a config file). Including the equals but with an empty value (like git -c foo.bar= ...) sets foo.bar to the empty string which git config --type=bool will convert to false. --config-env=<name>=<envvar> Like -c <name>=<value>, give configuration variable <name> a value, where <envvar> is the name of an environment variable from which to retrieve the value. Unlike -c there is no shortcut for directly setting the value to an empty string, instead the environment variable itself must be set to the empty string. It is an error if the <envvar> does not exist in the environment. <envvar> may not contain an equals sign to avoid ambiguity with <name> containing one. This is useful for cases where you want to pass transitory configuration options to git, but are doing so on operating systems where other processes might be able to read your command line (e.g. /proc/self/cmdline), but not your environment (e.g. /proc/self/environ). That behavior is the default on Linux, but may not be on your system. Note that this might add security for variables such as http.extraHeader where the sensitive information is part of the value, but not e.g. url.<base>.insteadOf where the sensitive information can be part of the key. --exec-path[=<path>] Path to wherever your core Git programs are installed. This can also be controlled by setting the GIT_EXEC_PATH environment variable. If no path is given, git will print the current setting and then exit. --html-path Print the path, without trailing slash, where Gits HTML documentation is installed and exit. --man-path Print the manpath (see man(1)) for the man pages for this version of Git and exit. --info-path Print the path where the Info files documenting this version of Git are installed and exit. -p, --paginate Pipe all output into less (or if set, $PAGER) if standard output is a terminal. This overrides the pager.<cmd> configuration options (see the "Configuration Mechanism" section below). -P, --no-pager Do not pipe Git output into a pager. --git-dir=<path> Set the path to the repository (".git" directory). This can also be controlled by setting the GIT_DIR environment variable. It can be an absolute path or relative path to current working directory. Specifying the location of the ".git" directory using this option (or GIT_DIR environment variable) turns off the repository discovery that tries to find a directory with ".git" subdirectory (which is how the repository and the top-level of the working tree are discovered), and tells Git that you are at the top level of the working tree. If you are not at the top-level directory of the working tree, you should tell Git where the top-level of the working tree is, with the --work-tree=<path> option (or GIT_WORK_TREE environment variable) If you just want to run git as if it was started in <path> then use git -C <path>. --work-tree=<path> Set the path to the working tree. It can be an absolute path or a path relative to the current working directory. This can also be controlled by setting the GIT_WORK_TREE environment variable and the core.worktree configuration variable (see core.worktree in git-config(1) for a more detailed discussion). --namespace=<path> Set the Git namespace. See gitnamespaces(7) for more details. Equivalent to setting the GIT_NAMESPACE environment variable. --bare Treat the repository as a bare repository. If GIT_DIR environment is not set, it is set to the current working directory. --no-replace-objects Do not use replacement refs to replace Git objects. See git-replace(1) for more information. --literal-pathspecs Treat pathspecs literally (i.e. no globbing, no pathspec magic). This is equivalent to setting the GIT_LITERAL_PATHSPECS environment variable to 1. --glob-pathspecs Add "glob" magic to all pathspec. This is equivalent to setting the GIT_GLOB_PATHSPECS environment variable to 1. Disabling globbing on individual pathspecs can be done using pathspec magic ":(literal)" --noglob-pathspecs Add "literal" magic to all pathspec. This is equivalent to setting the GIT_NOGLOB_PATHSPECS environment variable to 1. Enabling globbing on individual pathspecs can be done using pathspec magic ":(glob)" --icase-pathspecs Add "icase" magic to all pathspec. This is equivalent to setting the GIT_ICASE_PATHSPECS environment variable to 1. --no-optional-locks Do not perform optional operations that require locks. This is equivalent to setting the GIT_OPTIONAL_LOCKS to 0. --list-cmds=group[,group...] List commands by group. This is an internal/experimental option and may change or be removed in the future. Supported groups are: builtins, parseopt (builtin commands that use parse-options), main (all commands in libexec directory), others (all other commands in $PATH that have git- prefix), list-<category> (see categories in command-list.txt), nohelpers (exclude helper commands), alias and config (retrieve command list from config variable completion.commands) --attr-source=<tree-ish> Read gitattributes from <tree-ish> instead of the worktree. See gitattributes(5). This is equivalent to setting the GIT_ATTR_SOURCE environment variable. GIT COMMANDS top We divide Git into high level ("porcelain") commands and low level ("plumbing") commands. HIGH-LEVEL COMMANDS (PORCELAIN) top We separate the porcelain commands into the main commands and some ancillary user utilities. Main porcelain commands git-add(1) Add file contents to the index. git-am(1) Apply a series of patches from a mailbox. git-archive(1) Create an archive of files from a named tree. git-bisect(1) Use binary search to find the commit that introduced a bug. git-branch(1) List, create, or delete branches. git-bundle(1) Move objects and refs by archive. git-checkout(1) Switch branches or restore working tree files. git-cherry-pick(1) Apply the changes introduced by some existing commits. git-citool(1) Graphical alternative to git-commit. git-clean(1) Remove untracked files from the working tree. git-clone(1) Clone a repository into a new directory. git-commit(1) Record changes to the repository. git-describe(1) Give an object a human readable name based on an available ref. git-diff(1) Show changes between commits, commit and working tree, etc. git-fetch(1) Download objects and refs from another repository. git-format-patch(1) Prepare patches for e-mail submission. git-gc(1) Cleanup unnecessary files and optimize the local repository. git-grep(1) Print lines matching a pattern. git-gui(1) A portable graphical interface to Git. git-init(1) Create an empty Git repository or reinitialize an existing one. git-log(1) Show commit logs. git-maintenance(1) Run tasks to optimize Git repository data. git-merge(1) Join two or more development histories together. git-mv(1) Move or rename a file, a directory, or a symlink. git-notes(1) Add or inspect object notes. git-pull(1) Fetch from and integrate with another repository or a local branch. git-push(1) Update remote refs along with associated objects. git-range-diff(1) Compare two commit ranges (e.g. two versions of a branch). git-rebase(1) Reapply commits on top of another base tip. git-reset(1) Reset current HEAD to the specified state. git-restore(1) Restore working tree files. git-revert(1) Revert some existing commits. git-rm(1) Remove files from the working tree and from the index. git-shortlog(1) Summarize git log output. git-show(1) Show various types of objects. git-sparse-checkout(1) Reduce your working tree to a subset of tracked files. git-stash(1) Stash the changes in a dirty working directory away. git-status(1) Show the working tree status. git-submodule(1) Initialize, update or inspect submodules. git-switch(1) Switch branches. git-tag(1) Create, list, delete or verify a tag object signed with GPG. git-worktree(1) Manage multiple working trees. gitk(1) The Git repository browser. scalar(1) A tool for managing large Git repositories. Ancillary Commands Manipulators: git-config(1) Get and set repository or global options. git-fast-export(1) Git data exporter. git-fast-import(1) Backend for fast Git data importers. git-filter-branch(1) Rewrite branches. git-mergetool(1) Run merge conflict resolution tools to resolve merge conflicts. git-pack-refs(1) Pack heads and tags for efficient repository access. git-prune(1) Prune all unreachable objects from the object database. git-reflog(1) Manage reflog information. git-remote(1) Manage set of tracked repositories. git-repack(1) Pack unpacked objects in a repository. git-replace(1) Create, list, delete refs to replace objects. Interrogators: git-annotate(1) Annotate file lines with commit information. git-blame(1) Show what revision and author last modified each line of a file. git-bugreport(1) Collect information for user to file a bug report. git-count-objects(1) Count unpacked number of objects and their disk consumption. git-diagnose(1) Generate a zip archive of diagnostic information. git-difftool(1) Show changes using common diff tools. git-fsck(1) Verifies the connectivity and validity of the objects in the database. git-help(1) Display help information about Git. git-instaweb(1) Instantly browse your working repository in gitweb. git-merge-tree(1) Perform merge without touching index or working tree. git-rerere(1) Reuse recorded resolution of conflicted merges. git-show-branch(1) Show branches and their commits. git-verify-commit(1) Check the GPG signature of commits. git-verify-tag(1) Check the GPG signature of tags. git-version(1) Display version information about Git. git-whatchanged(1) Show logs with differences each commit introduces. gitweb(1) Git web interface (web frontend to Git repositories). Interacting with Others These commands are to interact with foreign SCM and with other people via patch over e-mail. git-archimport(1) Import a GNU Arch repository into Git. git-cvsexportcommit(1) Export a single commit to a CVS checkout. git-cvsimport(1) Salvage your data out of another SCM people love to hate. git-cvsserver(1) A CVS server emulator for Git. git-imap-send(1) Send a collection of patches from stdin to an IMAP folder. git-p4(1) Import from and submit to Perforce repositories. git-quiltimport(1) Applies a quilt patchset onto the current branch. git-request-pull(1) Generates a summary of pending changes. git-send-email(1) Send a collection of patches as emails. git-svn(1) Bidirectional operation between a Subversion repository and Git. Reset, restore and revert There are three commands with similar names: git reset, git restore and git revert. git-revert(1) is about making a new commit that reverts the changes made by other commits. git-restore(1) is about restoring files in the working tree from either the index or another commit. This command does not update your branch. The command can also be used to restore files in the index from another commit. git-reset(1) is about updating your branch, moving the tip in order to add or remove commits from the branch. This operation changes the commit history. git reset can also be used to restore the index, overlapping with git restore. LOW-LEVEL COMMANDS (PLUMBING) top Although Git includes its own porcelain layer, its low-level commands are sufficient to support development of alternative porcelains. Developers of such porcelains might start by reading about git-update-index(1) and git-read-tree(1). The interface (input, output, set of options and the semantics) to these low-level commands are meant to be a lot more stable than Porcelain level commands, because these commands are primarily for scripted use. The interface to Porcelain commands on the other hand are subject to change in order to improve the end user experience. The following description divides the low-level commands into commands that manipulate objects (in the repository, index, and working tree), commands that interrogate and compare objects, and commands that move objects and references between repositories. Manipulation commands git-apply(1) Apply a patch to files and/or to the index. git-checkout-index(1) Copy files from the index to the working tree. git-commit-graph(1) Write and verify Git commit-graph files. git-commit-tree(1) Create a new commit object. git-hash-object(1) Compute object ID and optionally create an object from a file. git-index-pack(1) Build pack index file for an existing packed archive. git-merge-file(1) Run a three-way file merge. git-merge-index(1) Run a merge for files needing merging. git-mktag(1) Creates a tag object with extra validation. git-mktree(1) Build a tree-object from ls-tree formatted text. git-multi-pack-index(1) Write and verify multi-pack-indexes. git-pack-objects(1) Create a packed archive of objects. git-prune-packed(1) Remove extra objects that are already in pack files. git-read-tree(1) Reads tree information into the index. git-replay(1) EXPERIMENTAL: Replay commits on a new base, works with bare repos too. git-symbolic-ref(1) Read, modify and delete symbolic refs. git-unpack-objects(1) Unpack objects from a packed archive. git-update-index(1) Register file contents in the working tree to the index. git-update-ref(1) Update the object name stored in a ref safely. git-write-tree(1) Create a tree object from the current index. Interrogation commands git-cat-file(1) Provide contents or details of repository objects. git-cherry(1) Find commits yet to be applied to upstream. git-diff-files(1) Compares files in the working tree and the index. git-diff-index(1) Compare a tree to the working tree or index. git-diff-tree(1) Compares the content and mode of blobs found via two tree objects. git-for-each-ref(1) Output information on each ref. git-for-each-repo(1) Run a Git command on a list of repositories. git-get-tar-commit-id(1) Extract commit ID from an archive created using git-archive. git-ls-files(1) Show information about files in the index and the working tree. git-ls-remote(1) List references in a remote repository. git-ls-tree(1) List the contents of a tree object. git-merge-base(1) Find as good common ancestors as possible for a merge. git-name-rev(1) Find symbolic names for given revs. git-pack-redundant(1) Find redundant pack files. git-rev-list(1) Lists commit objects in reverse chronological order. git-rev-parse(1) Pick out and massage parameters. git-show-index(1) Show packed archive index. git-show-ref(1) List references in a local repository. git-unpack-file(1) Creates a temporary file with a blobs contents. git-var(1) Show a Git logical variable. git-verify-pack(1) Validate packed Git archive files. In general, the interrogate commands do not touch the files in the working tree. Syncing repositories git-daemon(1) A really simple server for Git repositories. git-fetch-pack(1) Receive missing objects from another repository. git-http-backend(1) Server side implementation of Git over HTTP. git-send-pack(1) Push objects over Git protocol to another repository. git-update-server-info(1) Update auxiliary info file to help dumb servers. The following are helper commands used by the above; end users typically do not use them directly. git-http-fetch(1) Download from a remote Git repository via HTTP. git-http-push(1) Push objects over HTTP/DAV to another repository. git-receive-pack(1) Receive what is pushed into the repository. git-shell(1) Restricted login shell for Git-only SSH access. git-upload-archive(1) Send archive back to git-archive. git-upload-pack(1) Send objects packed back to git-fetch-pack. Internal helper commands These are internal helper commands used by other commands; end users typically do not use them directly. git-check-attr(1) Display gitattributes information. git-check-ignore(1) Debug gitignore / exclude files. git-check-mailmap(1) Show canonical names and email addresses of contacts. git-check-ref-format(1) Ensures that a reference name is well formed. git-column(1) Display data in columns. git-credential(1) Retrieve and store user credentials. git-credential-cache(1) Helper to temporarily store passwords in memory. git-credential-store(1) Helper to store credentials on disk. git-fmt-merge-msg(1) Produce a merge commit message. git-hook(1) Run git hooks. git-interpret-trailers(1) Add or parse structured information in commit messages. git-mailinfo(1) Extracts patch and authorship from a single e-mail message. git-mailsplit(1) Simple UNIX mbox splitter program. git-merge-one-file(1) The standard helper program to use with git-merge-index. git-patch-id(1) Compute unique ID for a patch. git-sh-i18n(1) Gits i18n setup code for shell scripts. git-sh-setup(1) Common Git shell script setup code. git-stripspace(1) Remove unnecessary whitespace. GUIDES top The following documentation pages are guides about Git concepts. gitcore-tutorial(7) A Git core tutorial for developers. gitcredentials(7) Providing usernames and passwords to Git. gitcvs-migration(7) Git for CVS users. gitdiffcore(7) Tweaking diff output. giteveryday(7) A useful minimum set of commands for Everyday Git. gitfaq(7) Frequently asked questions about using Git. gitglossary(7) A Git Glossary. gitnamespaces(7) Git namespaces. gitremote-helpers(7) Helper programs to interact with remote repositories. gitsubmodules(7) Mounting one repository inside another. gittutorial(7) A tutorial introduction to Git. gittutorial-2(7) A tutorial introduction to Git: part two. gitworkflows(7) An overview of recommended workflows with Git. REPOSITORY, COMMAND AND FILE INTERFACES top This documentation discusses repository and command interfaces which users are expected to interact with directly. See --user-formats in git-help(1) for more details on the criteria. gitattributes(5) Defining attributes per path. gitcli(7) Git command-line interface and conventions. githooks(5) Hooks used by Git. gitignore(5) Specifies intentionally untracked files to ignore. gitmailmap(5) Map author/committer names and/or E-Mail addresses. gitmodules(5) Defining submodule properties. gitrepository-layout(5) Git Repository Layout. gitrevisions(7) Specifying revisions and ranges for Git. FILE FORMATS, PROTOCOLS AND OTHER DEVELOPER INTERFACES top This documentation discusses file formats, over-the-wire protocols and other git developer interfaces. See --developer-interfaces in git-help(1). gitformat-bundle(5) The bundle file format. gitformat-chunk(5) Chunk-based file formats. gitformat-commit-graph(5) Git commit-graph format. gitformat-index(5) Git index format. gitformat-pack(5) Git pack format. gitformat-signature(5) Git cryptographic signature formats. gitprotocol-capabilities(5) Protocol v0 and v1 capabilities. gitprotocol-common(5) Things common to various protocols. gitprotocol-http(5) Git HTTP-based protocols. gitprotocol-pack(5) How packs are transferred over-the-wire. gitprotocol-v2(5) Git Wire Protocol, Version 2. CONFIGURATION MECHANISM top Git uses a simple text format to store customizations that are per repository and are per user. Such a configuration file may look like this: # # A '#' or ';' character indicates a comment. # ; core variables [core] ; Don't trust file modes filemode = false ; user identity [user] name = "Junio C Hamano" email = "gitster@pobox.com" Various commands read from the configuration file and adjust their operation accordingly. See git-config(1) for a list and more details about the configuration mechanism. IDENTIFIER TERMINOLOGY top <object> Indicates the object name for any type of object. <blob> Indicates a blob object name. <tree> Indicates a tree object name. <commit> Indicates a commit object name. <tree-ish> Indicates a tree, commit or tag object name. A command that takes a <tree-ish> argument ultimately wants to operate on a <tree> object but automatically dereferences <commit> and <tag> objects that point at a <tree>. <commit-ish> Indicates a commit or tag object name. A command that takes a <commit-ish> argument ultimately wants to operate on a <commit> object but automatically dereferences <tag> objects that point at a <commit>. <type> Indicates that an object type is required. Currently one of: blob, tree, commit, or tag. <file> Indicates a filename - almost always relative to the root of the tree structure GIT_INDEX_FILE describes. SYMBOLIC IDENTIFIERS top Any Git command accepting any <object> can also use the following symbolic notation: HEAD indicates the head of the current branch. <tag> a valid tag name (i.e. a refs/tags/<tag> reference). <head> a valid head name (i.e. a refs/heads/<head> reference). For a more complete list of ways to spell object names, see "SPECIFYING REVISIONS" section in gitrevisions(7). FILE/DIRECTORY STRUCTURE top Please see the gitrepository-layout(5) document. Read githooks(5) for more details about each hook. Higher level SCMs may provide and manage additional information in the $GIT_DIR. TERMINOLOGY top Please see gitglossary(7). ENVIRONMENT VARIABLES top Various Git commands pay attention to environment variables and change their behavior. The environment variables marked as "Boolean" take their values the same way as Boolean valued configuration variables, e.g. "true", "yes", "on" and positive numbers are taken as "yes". Here are the variables: The Git Repository These environment variables apply to all core Git commands. Nb: it is worth noting that they may be used/overridden by SCMS sitting above Git so take care if using a foreign front-end. GIT_INDEX_FILE This environment variable specifies an alternate index file. If not specified, the default of $GIT_DIR/index is used. GIT_INDEX_VERSION This environment variable specifies what index version is used when writing the index file out. It wont affect existing index files. By default index file version 2 or 3 is used. See git-update-index(1) for more information. GIT_OBJECT_DIRECTORY If the object storage directory is specified via this environment variable then the sha1 directories are created underneath - otherwise the default $GIT_DIR/objects directory is used. GIT_ALTERNATE_OBJECT_DIRECTORIES Due to the immutable nature of Git objects, old objects can be archived into shared, read-only directories. This variable specifies a ":" separated (on Windows ";" separated) list of Git object directories which can be used to search for Git objects. New objects will not be written to these directories. Entries that begin with " (double-quote) will be interpreted as C-style quoted paths, removing leading and trailing double-quotes and respecting backslash escapes. E.g., the value "path-with-\"-and-:-in-it":vanilla-path has two paths: path-with-"-and-:-in-it and vanilla-path. GIT_DIR If the GIT_DIR environment variable is set then it specifies a path to use instead of the default .git for the base of the repository. The --git-dir command-line option also sets this value. GIT_WORK_TREE Set the path to the root of the working tree. This can also be controlled by the --work-tree command-line option and the core.worktree configuration variable. GIT_NAMESPACE Set the Git namespace; see gitnamespaces(7) for details. The --namespace command-line option also sets this value. GIT_CEILING_DIRECTORIES This should be a colon-separated list of absolute paths. If set, it is a list of directories that Git should not chdir up into while looking for a repository directory (useful for excluding slow-loading network directories). It will not exclude the current working directory or a GIT_DIR set on the command line or in the environment. Normally, Git has to read the entries in this list and resolve any symlink that might be present in order to compare them with the current directory. However, if even this access is slow, you can add an empty entry to the list to tell Git that the subsequent entries are not symlinks and neednt be resolved; e.g., GIT_CEILING_DIRECTORIES=/maybe/symlink::/very/slow/non/symlink. GIT_DISCOVERY_ACROSS_FILESYSTEM When run in a directory that does not have ".git" repository directory, Git tries to find such a directory in the parent directories to find the top of the working tree, but by default it does not cross filesystem boundaries. This Boolean environment variable can be set to true to tell Git not to stop at filesystem boundaries. Like GIT_CEILING_DIRECTORIES, this will not affect an explicit repository directory set via GIT_DIR or on the command line. GIT_COMMON_DIR If this variable is set to a path, non-worktree files that are normally in $GIT_DIR will be taken from this path instead. Worktree-specific files such as HEAD or index are taken from $GIT_DIR. See gitrepository-layout(5) and git-worktree(1) for details. This variable has lower precedence than other path variables such as GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY... GIT_DEFAULT_HASH If this variable is set, the default hash algorithm for new repositories will be set to this value. This value is ignored when cloning and the setting of the remote repository is always used. The default is "sha1". See --object-format in git-init(1). Git Commits GIT_AUTHOR_NAME The human-readable name used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.name and author.name configuration settings. GIT_AUTHOR_EMAIL The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.email and author.email configuration settings. GIT_AUTHOR_DATE The date used for the author identity when creating commit or tag objects, or when writing reflogs. See git-commit(1) for valid formats. GIT_COMMITTER_NAME The human-readable name used in the committer identity when creating commit or tag objects, or when writing reflogs. Overrides the user.name and committer.name configuration settings. GIT_COMMITTER_EMAIL The email address used in the author identity when creating commit or tag objects, or when writing reflogs. Overrides the user.email and committer.email configuration settings. GIT_COMMITTER_DATE The date used for the committer identity when creating commit or tag objects, or when writing reflogs. See git-commit(1) for valid formats. EMAIL The email address used in the author and committer identities if no other relevant environment variable or configuration setting has been set. Git Diffs GIT_DIFF_OPTS Only valid setting is "--unified=??" or "-u??" to set the number of context lines shown when a unified diff is created. This takes precedence over any "-U" or "--unified" option value passed on the Git diff command line. GIT_EXTERNAL_DIFF When the environment variable GIT_EXTERNAL_DIFF is set, the program named by it is called to generate diffs, and Git does not use its builtin diff machinery. For a path that is added, removed, or modified, GIT_EXTERNAL_DIFF is called with 7 parameters: path old-file old-hex old-mode new-file new-hex new-mode where: <old|new>-file are files GIT_EXTERNAL_DIFF can use to read the contents of <old|new>, <old|new>-hex are the 40-hexdigit SHA-1 hashes, <old|new>-mode are the octal representation of the file modes. The file parameters can point at the users working file (e.g. new-file in "git-diff-files"), /dev/null (e.g. old-file when a new file is added), or a temporary file (e.g. old-file in the index). GIT_EXTERNAL_DIFF should not worry about unlinking the temporary file it is removed when GIT_EXTERNAL_DIFF exits. For a path that is unmerged, GIT_EXTERNAL_DIFF is called with 1 parameter, <path>. For each path GIT_EXTERNAL_DIFF is called, two environment variables, GIT_DIFF_PATH_COUNTER and GIT_DIFF_PATH_TOTAL are set. GIT_DIFF_PATH_COUNTER A 1-based counter incremented by one for every path. GIT_DIFF_PATH_TOTAL The total number of paths. other GIT_MERGE_VERBOSITY A number controlling the amount of output shown by the recursive merge strategy. Overrides merge.verbosity. See git-merge(1) GIT_PAGER This environment variable overrides $PAGER. If it is set to an empty string or to the value "cat", Git will not launch a pager. See also the core.pager option in git-config(1). GIT_PROGRESS_DELAY A number controlling how many seconds to delay before showing optional progress indicators. Defaults to 2. GIT_EDITOR This environment variable overrides $EDITOR and $VISUAL. It is used by several Git commands when, on interactive mode, an editor is to be launched. See also git-var(1) and the core.editor option in git-config(1). GIT_SEQUENCE_EDITOR This environment variable overrides the configured Git editor when editing the todo list of an interactive rebase. See also git-rebase(1) and the sequence.editor option in git-config(1). GIT_SSH, GIT_SSH_COMMAND If either of these environment variables is set then git fetch and git push will use the specified command instead of ssh when they need to connect to a remote system. The command-line parameters passed to the configured command are determined by the ssh variant. See ssh.variant option in git-config(1) for details. $GIT_SSH_COMMAND takes precedence over $GIT_SSH, and is interpreted by the shell, which allows additional arguments to be included. $GIT_SSH on the other hand must be just the path to a program (which can be a wrapper shell script, if additional arguments are needed). Usually it is easier to configure any desired options through your personal .ssh/config file. Please consult your ssh documentation for further details. GIT_SSH_VARIANT If this environment variable is set, it overrides Gits autodetection whether GIT_SSH/GIT_SSH_COMMAND/core.sshCommand refer to OpenSSH, plink or tortoiseplink. This variable overrides the config setting ssh.variant that serves the same purpose. GIT_SSL_NO_VERIFY Setting and exporting this environment variable to any value tells Git not to verify the SSL certificate when fetching or pushing over HTTPS. GIT_ATTR_SOURCE Sets the treeish that gitattributes will be read from. GIT_ASKPASS If this environment variable is set, then Git commands which need to acquire passwords or passphrases (e.g. for HTTP or IMAP authentication) will call this program with a suitable prompt as command-line argument and read the password from its STDOUT. See also the core.askPass option in git-config(1). GIT_TERMINAL_PROMPT If this Boolean environment variable is set to false, git will not prompt on the terminal (e.g., when asking for HTTP authentication). GIT_CONFIG_GLOBAL, GIT_CONFIG_SYSTEM Take the configuration from the given files instead from global or system-level configuration files. If GIT_CONFIG_SYSTEM is set, the system config file defined at build time (usually /etc/gitconfig) will not be read. Likewise, if GIT_CONFIG_GLOBAL is set, neither $HOME/.gitconfig nor $XDG_CONFIG_HOME/git/config will be read. Can be set to /dev/null to skip reading configuration files of the respective level. GIT_CONFIG_NOSYSTEM Whether to skip reading settings from the system-wide $(prefix)/etc/gitconfig file. This Boolean environment variable can be used along with $HOME and $XDG_CONFIG_HOME to create a predictable environment for a picky script, or you can set it to true to temporarily avoid using a buggy /etc/gitconfig file while waiting for someone with sufficient permissions to fix it. GIT_FLUSH If this environment variable is set to "1", then commands such as git blame (in incremental mode), git rev-list, git log, git check-attr and git check-ignore will force a flush of the output stream after each record have been flushed. If this variable is set to "0", the output of these commands will be done using completely buffered I/O. If this environment variable is not set, Git will choose buffered or record-oriented flushing based on whether stdout appears to be redirected to a file or not. GIT_TRACE Enables general trace messages, e.g. alias expansion, built-in command execution and external command execution. If this variable is set to "1", "2" or "true" (comparison is case insensitive), trace messages will be printed to stderr. If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as an open file descriptor and will try to write the trace messages into this file descriptor. Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file path and will try to append the trace messages to it. Unsetting the variable, or setting it to empty, "0" or "false" (case insensitive) disables trace messages. GIT_TRACE_FSMONITOR Enables trace messages for the filesystem monitor extension. See GIT_TRACE for available trace output options. GIT_TRACE_PACK_ACCESS Enables trace messages for all accesses to any packs. For each access, the pack file name and an offset in the pack is recorded. This may be helpful for troubleshooting some pack-related performance problems. See GIT_TRACE for available trace output options. GIT_TRACE_PACKET Enables trace messages for all packets coming in or out of a given program. This can help with debugging object negotiation or other protocol issues. Tracing is turned off at a packet starting with "PACK" (but see GIT_TRACE_PACKFILE below). See GIT_TRACE for available trace output options. GIT_TRACE_PACKFILE Enables tracing of packfiles sent or received by a given program. Unlike other trace output, this trace is verbatim: no headers, and no quoting of binary data. You almost certainly want to direct into a file (e.g., GIT_TRACE_PACKFILE=/tmp/my.pack) rather than displaying it on the terminal or mixing it with other trace output. Note that this is currently only implemented for the client side of clones and fetches. GIT_TRACE_PERFORMANCE Enables performance related trace messages, e.g. total execution time of each Git command. See GIT_TRACE for available trace output options. GIT_TRACE_REFS Enables trace messages for operations on the ref database. See GIT_TRACE for available trace output options. GIT_TRACE_SETUP Enables trace messages printing the .git, working tree and current working directory after Git has completed its setup phase. See GIT_TRACE for available trace output options. GIT_TRACE_SHALLOW Enables trace messages that can help debugging fetching / cloning of shallow repositories. See GIT_TRACE for available trace output options. GIT_TRACE_CURL Enables a curl full trace dump of all incoming and outgoing data, including descriptive information, of the git transport protocol. This is similar to doing curl --trace-ascii on the command line. See GIT_TRACE for available trace output options. GIT_TRACE_CURL_NO_DATA When a curl trace is enabled (see GIT_TRACE_CURL above), do not dump data (that is, only dump info lines and headers). GIT_TRACE2 Enables more detailed trace messages from the "trace2" library. Output from GIT_TRACE2 is a simple text-based format for human readability. If this variable is set to "1", "2" or "true" (comparison is case insensitive), trace messages will be printed to stderr. If the variable is set to an integer value greater than 2 and lower than 10 (strictly) then Git will interpret this value as an open file descriptor and will try to write the trace messages into this file descriptor. Alternatively, if the variable is set to an absolute path (starting with a / character), Git will interpret this as a file path and will try to append the trace messages to it. If the path already exists and is a directory, the trace messages will be written to files (one per process) in that directory, named according to the last component of the SID and an optional counter (to avoid filename collisions). In addition, if the variable is set to af_unix:[<socket_type>:]<absolute-pathname>, Git will try to open the path as a Unix Domain Socket. The socket type can be either stream or dgram. Unsetting the variable, or setting it to empty, "0" or "false" (case insensitive) disables trace messages. See Trace2 documentation[2] for full details. GIT_TRACE2_EVENT This setting writes a JSON-based format that is suited for machine interpretation. See GIT_TRACE2 for available trace output options and Trace2 documentation[2] for full details. GIT_TRACE2_PERF In addition to the text-based messages available in GIT_TRACE2, this setting writes a column-based format for understanding nesting regions. See GIT_TRACE2 for available trace output options and Trace2 documentation[2] for full details. GIT_TRACE_REDACT By default, when tracing is activated, Git redacts the values of cookies, the "Authorization:" header, the "Proxy-Authorization:" header and packfile URIs. Set this Boolean environment variable to false to prevent this redaction. GIT_LITERAL_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs literally, rather than as glob patterns. For example, running GIT_LITERAL_PATHSPECS=1 git log -- '*.c' will search for commits that touch the path *.c, not any paths that the glob *.c matches. You might want this if you are feeding literal paths to Git (e.g., paths previously given to you by git ls-tree, --raw diff output, etc). GIT_GLOB_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as glob patterns (aka "glob" magic). GIT_NOGLOB_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as literal (aka "literal" magic). GIT_ICASE_PATHSPECS Setting this Boolean environment variable to true will cause Git to treat all pathspecs as case-insensitive. GIT_REFLOG_ACTION When a ref is updated, reflog entries are created to keep track of the reason why the ref was updated (which is typically the name of the high-level command that updated the ref), in addition to the old and new values of the ref. A scripted Porcelain command can use set_reflog_action helper function in git-sh-setup to set its name to this variable when it is invoked as the top level command by the end user, to be recorded in the body of the reflog. GIT_REF_PARANOIA If this Boolean environment variable is set to false, ignore broken or badly named refs when iterating over lists of refs. Normally Git will try to include any such refs, which may cause some operations to fail. This is usually preferable, as potentially destructive operations (e.g., git-prune(1)) are better off aborting rather than ignoring broken refs (and thus considering the history they point to as not worth saving). The default value is 1 (i.e., be paranoid about detecting and aborting all operations). You should not normally need to set this to 0, but it may be useful when trying to salvage data from a corrupted repository. GIT_COMMIT_GRAPH_PARANOIA When loading a commit object from the commit-graph, Git performs an existence check on the object in the object database. This is done to avoid issues with stale commit-graphs that contain references to already-deleted commits, but comes with a performance penalty. The default is "false", which disables the aforementioned behavior. Setting this to "true" enables the existence check so that stale commits will never be returned from the commit-graph at the cost of performance. GIT_ALLOW_PROTOCOL If set to a colon-separated list of protocols, behave as if protocol.allow is set to never, and each of the listed protocols has protocol.<name>.allow set to always (overriding any existing configuration). See the description of protocol.allow in git-config(1) for more details. GIT_PROTOCOL_FROM_USER Set this Boolean environment variable to false to prevent protocols used by fetch/push/clone which are configured to the user state. This is useful to restrict recursive submodule initialization from an untrusted repository or for programs which feed potentially-untrusted URLS to git commands. See git-config(1) for more details. GIT_PROTOCOL For internal use only. Used in handshaking the wire protocol. Contains a colon : separated list of keys with optional values key[=value]. Presence of unknown keys and values must be ignored. Note that servers may need to be configured to allow this variable to pass over some transports. It will be propagated automatically when accessing local repositories (i.e., file:// or a filesystem path), as well as over the git:// protocol. For git-over-http, it should work automatically in most configurations, but see the discussion in git-http-backend(1). For git-over-ssh, the ssh server may need to be configured to allow clients to pass this variable (e.g., by using AcceptEnv GIT_PROTOCOL with OpenSSH). This configuration is optional. If the variable is not propagated, then clients will fall back to the original "v0" protocol (but may miss out on some performance improvements or features). This variable currently only affects clones and fetches; it is not yet used for pushes (but may be in the future). GIT_OPTIONAL_LOCKS If this Boolean environment variable is set to false, Git will complete any requested operation without performing any optional sub-operations that require taking a lock. For example, this will prevent git status from refreshing the index as a side effect. This is useful for processes running in the background which do not want to cause lock contention with other operations on the repository. Defaults to 1. GIT_REDIRECT_STDIN, GIT_REDIRECT_STDOUT, GIT_REDIRECT_STDERR Windows-only: allow redirecting the standard input/output/error handles to paths specified by the environment variables. This is particularly useful in multi-threaded applications where the canonical way to pass standard handles via CreateProcess() is not an option because it would require the handles to be marked inheritable (and consequently every spawned process would inherit them, possibly blocking regular Git operations). The primary intended use case is to use named pipes for communication (e.g. \\.\pipe\my-git-stdin-123). Two special values are supported: off will simply close the corresponding standard handle, and if GIT_REDIRECT_STDERR is 2>&1, standard error will be redirected to the same handle as standard output. GIT_PRINT_SHA1_ELLIPSIS (deprecated) If set to yes, print an ellipsis following an (abbreviated) SHA-1 value. This affects indications of detached HEADs ( git-checkout(1)) and the raw diff output (git-diff(1)). Printing an ellipsis in the cases mentioned is no longer considered adequate and support for it is likely to be removed in the foreseeable future (along with the variable). DISCUSSION top More detail on the following is available from the Git concepts chapter of the user-manual[3] and gitcore-tutorial(7). A Git project normally consists of a working directory with a ".git" subdirectory at the top level. The .git directory contains, among other things, a compressed object database representing the complete history of the project, an "index" file which links that history to the current contents of the working tree, and named pointers into that history such as tags and branch heads. The object database contains objects of three main types: blobs, which hold file data; trees, which point to blobs and other trees to build up directory hierarchies; and commits, which each reference a single tree and some number of parent commits. The commit, equivalent to what other systems call a "changeset" or "version", represents a step in the projects history, and each parent represents an immediately preceding step. Commits with more than one parent represent merges of independent lines of development. All objects are named by the SHA-1 hash of their contents, normally written as a string of 40 hex digits. Such names are globally unique. The entire history leading up to a commit can be vouched for by signing just that commit. A fourth object type, the tag, is provided for this purpose. When first created, objects are stored in individual files, but for efficiency may later be compressed together into "pack files". Named pointers called refs mark interesting points in history. A ref may contain the SHA-1 name of an object or the name of another ref. Refs with names beginning ref/head/ contain the SHA-1 name of the most recent commit (or "head") of a branch under development. SHA-1 names of tags of interest are stored under ref/tags/. A special ref named HEAD contains the name of the currently checked-out branch. The index file is initialized with a list of all paths and, for each path, a blob object and a set of attributes. The blob object represents the contents of the file as of the head of the current branch. The attributes (last modified time, size, etc.) are taken from the corresponding file in the working tree. Subsequent changes to the working tree can be found by comparing these attributes. The index may be updated with new content, and new commits may be created from the content stored in the index. The index is also capable of storing multiple entries (called "stages") for a given pathname. These stages are used to hold the various unmerged version of a file when a merge is in progress. FURTHER DOCUMENTATION top See the references in the "description" section to get started using Git. The following is probably more detail than necessary for a first-time user. The Git concepts chapter of the user-manual[3] and gitcore-tutorial(7) both provide introductions to the underlying Git architecture. See gitworkflows(7) for an overview of recommended workflows. See also the howto[4] documents for some useful examples. The internals are documented in the Git API documentation[5]. Users migrating from CVS may also want to read gitcvs-migration(7). AUTHORS top Git was started by Linus Torvalds, and is currently maintained by Junio C Hamano. Numerous contributions have come from the Git mailing list <git@vger.kernel.org[6]>. https://openhub.net/p/git/contributors/summary gives you a more complete list of contributors. If you have a clone of git.git itself, the output of git-shortlog(1) and git-blame(1) can show you the authors for specific parts of the project. REPORTING BUGS top Report bugs to the Git mailing list <git@vger.kernel.org[6]> where the development and maintenance is primarily done. You do not have to be subscribed to the list to send a message there. See the list archive at https://lore.kernel.org/git for previous bug reports and other discussions. Issues which are security relevant should be disclosed privately to the Git Security mailing list <git-security@googlegroups.com[7]>. SEE ALSO top gittutorial(7), gittutorial-2(7), giteveryday(7), gitcvs-migration(7), gitglossary(7), gitcore-tutorial(7), gitcli(7), The Git Users Manual[1], gitworkflows(7) GIT top Part of the git(1) suite NOTES top 1. Git Users Manual file:///home/mtk/share/doc/git-doc/user-manual.html 2. Trace2 documentation file:///home/mtk/share/doc/git-doc/technical/api-trace2.html 3. Git concepts chapter of the user-manual file:///home/mtk/share/doc/git-doc/user-manual.html#git-concepts 4. howto file:///home/mtk/share/doc/git-doc/howto-index.html 5. Git API documentation file:///home/mtk/share/doc/git-doc/technical/api-index.html 6. git@vger.kernel.org mailto:git@vger.kernel.org 7. git-security@googlegroups.com mailto:git-security@googlegroups.com COLOPHON top This page is part of the git (Git distributed version control system) project. Information about the project can be found at http://git-scm.com/. If you have a bug report for this manual page, see http://git-scm.com/community. This page was obtained from the project's upstream Git repository https://github.com/git/git.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-12-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 Git 2.43.0.174.g055bb6 2023-12-20 GIT(1) Pages that refer to this page: git(1), git-add(1), git-am(1), git-annotate(1), git-apply(1), git-archimport(1), git-archive(1), git-bisect(1), git-blame(1), git-branch(1), git-bugreport(1), git-bundle(1), git-cat-file(1), git-check-attr(1), git-check-ignore(1), git-check-mailmap(1), git-checkout(1), git-checkout-index(1), git-check-ref-format(1), git-cherry(1), git-cherry-pick(1), git-citool(1), git-clean(1), git-clone(1), git-column(1), git-commit(1), git-commit-graph(1), git-commit-tree(1), git-config(1), git-count-objects(1), git-credential(1), git-credential-cache(1), git-credential-cache--daemon(1), git-credential-store(1), git-cvsexportcommit(1), git-cvsimport(1), git-cvsserver(1), git-daemon(1), git-describe(1), git-diagnose(1), git-diff(1), git-diff-files(1), git-diff-index(1), git-difftool(1), git-diff-tree(1), git-fast-export(1), git-fast-import(1), git-fetch(1), git-fetch-pack(1), git-filter-branch(1), git-fmt-merge-msg(1), git-for-each-ref(1), git-for-each-repo(1), git-format-patch(1), git-fsck(1), git-fsck-objects(1), git-fsmonitor--daemon(1), git-gc(1), git-get-tar-commit-id(1), git-grep(1), git-gui(1), git-hash-object(1), git-help(1), git-hook(1), git-http-backend(1), git-http-fetch(1), git-http-push(1), git-imap-send(1), git-index-pack(1), git-init(1), git-init-db(1), git-instaweb(1), git-interpret-trailers(1), gitk(1), git-log(1), git-ls-files(1), git-ls-remote(1), git-ls-tree(1), git-mailinfo(1), git-mailsplit(1), git-maintenance(1), git-merge(1), git-merge-base(1), git-merge-file(1), git-merge-index(1), git-merge-one-file(1), git-mergetool(1), git-mergetool--lib(1), git-merge-tree(1), git-mktag(1), git-mktree(1), git-multi-pack-index(1), git-mv(1), git-name-rev(1), git-notes(1), git-p4(1), git-pack-objects(1), git-pack-redundant(1), git-pack-refs(1), git-patch-id(1), git-prune(1), git-prune-packed(1), git-pull(1), git-push(1), git-quiltimport(1), git-range-diff(1), git-read-tree(1), git-rebase(1), git-receive-pack(1), git-reflog(1), git-remote(1), git-remote-ext(1), git-remote-fd(1), git-repack(1), git-replace(1), git-replay(1), git-request-pull(1), git-rerere(1), git-reset(1), git-restore(1), git-revert(1), git-rev-list(1), git-rev-parse(1), git-rm(1), git-send-email(1), git-send-pack(1), git-series(1), git-shell(1), git-sh-i18n(1), git-sh-i18n--envsubst(1), git-shortlog(1), git-show(1), git-show-branch(1), git-show-index(1), git-show-ref(1), git-sh-setup(1), git-sparse-checkout(1), git-stage(1), git-stash(1), git-status(1), git-stripspace(1), git-submodule(1), git-svn(1), git-switch(1), git-symbolic-ref(1), git-tag(1), git-unpack-file(1), git-unpack-objects(1), git-update-index(1), git-update-ref(1), git-update-server-info(1), git-upload-archive(1), git-upload-pack(1), git-var(1), git-verify-commit(1), git-verify-pack(1), git-verify-tag(1), git-version(1), gitweb(1), git-web--browse(1), git-whatchanged(1), git-worktree(1), git-write-tree(1), scalar(1), gitattributes(5), gitformat-bundle(5), gitformat-chunk(5), gitformat-commit-graph(5), gitformat-index(5), gitformat-pack(5), gitformat-signature(5), githooks(5), gitignore(5), gitmailmap(5), gitmodules(5), gitprotocol-capabilities(5), gitprotocol-common(5), gitprotocol-http(5), gitprotocol-pack(5), gitprotocol-v2(5), gitrepository-layout(5), gitweb.conf(5), gitcli(7), gitcore-tutorial(7), gitcredentials(7), gitcvs-migration(7), gitdiffcore(7), giteveryday(7), gitfaq(7), gitglossary(7), gitnamespaces(7), gitremote-helpers(7), gitrevisions(7), gitsubmodules(7), gittutorial-2(7), gittutorial(7), gitworkflows(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: Composes full process tree with process id numbers, and prints only those strings that contain 'git'. Bash Command:<START>pstree -p | grep git<END>
Compress "hello world" and save to variable "hey"
hey=$(echo "hello world" | gzip -cf)
['echo']
Output a Bash command to accomplish the following task. Task: Compress "hello world" and save to variable "hey" Bash Command:<START>hey=$(echo "hello world" | gzip -cf)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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: Compress "hello world" and save to variable "hey" Bash Command:<START>hey=$(echo "hello world" | gzip -cf)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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: Compress "hello world" and save to variable "hey" Bash Command:<START>hey=$(echo "hello world" | gzip -cf)<END>
Compress "my_large_file" with gzip and split the result into files of size 1024 MiB with prefix "myfile_split.gz_"
gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_
['split']
Output a Bash command to accomplish the following task. Task: Compress "my_large_file" with gzip and split the result into files of size 1024 MiB with prefix "myfile_split.gz_" Bash Command:<START>gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_<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: Compress "my_large_file" with gzip and split the result into files of size 1024 MiB with prefix "myfile_split.gz_" Bash Command:<START>gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_<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: Compress "my_large_file" with gzip and split the result into files of size 1024 MiB with prefix "myfile_split.gz_" Bash Command:<START>gzip -c my_large_file | split -b 1024MiB - myfile_split.gz_<END>
Compress all ".txt" files in the current directory tree with gzip
find . -type f -name "*.txt" -exec gzip {} \;
['find']
Output a Bash command to accomplish the following task. Task: Compress all ".txt" files in the current directory tree with gzip Bash Command:<START>find . -type f -name "*.txt" -exec gzip {} \;<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: Compress all ".txt" files in the current directory tree with gzip Bash Command:<START>find . -type f -name "*.txt" -exec gzip {} \;<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: Compress all ".txt" files in the current directory tree with gzip Bash Command:<START>find . -type f -name "*.txt" -exec gzip {} \;<END>
Compress all *.img files using bzip2
find ./ -name "*.img" -exec bzip2 -v {} \;
['find']
Output a Bash command to accomplish the following task. Task: Compress all *.img files using bzip2 Bash Command:<START>find ./ -name "*.img" -exec bzip2 -v {} \;<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: Compress all *.img files using bzip2 Bash Command:<START>find ./ -name "*.img" -exec bzip2 -v {} \;<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: Compress all *.img files using bzip2 Bash Command:<START>find ./ -name "*.img" -exec bzip2 -v {} \;<END>
Compress all directories found in $LOGDIR wherein a file's data has been modified within the last 24 hours
find $LOGDIR -type d -mtime +0 -exec compress -r {} \;
['find', 'compress']
Output a Bash command to accomplish the following task. Task: Compress all directories found in $LOGDIR wherein a file's data has been modified within the last 24 hours Bash Command:<START>find $LOGDIR -type d -mtime +0 -exec compress -r {} \;<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 # compress\n\n> Compress files using the Unix `compress` command.\n> More information: <https://manned.org/compress.1>.\n\n- Compress specific files:\n\n`compress {{path/to/file1 path/to/file2 ...}}`\n\n- Compress specific files, ignore non-existent ones:\n\n`compress -f {{path/to/file1 path/to/file2 ...}}`\n\n- Specify the maximum compression bits (9-16 bits):\n\n`compress -b {{bits}}`\n\n- Write to `stdout` (no files are changed):\n\n`compress -c {{path/to/file}}`\n\n- Decompress files (functions like `uncompress`):\n\n`compress -d {{path/to/file}}`\n\n- Display compression percentage:\n\n`compress -v {{path/to/file}}`\n Task: Compress all directories found in $LOGDIR wherein a file's data has been modified within the last 24 hours Bash Command:<START>find $LOGDIR -type d -mtime +0 -exec compress -r {} \;<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. compress(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training compress(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 COMPRESS(1P) POSIX Programmer's Manual COMPRESS(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 compress compress data SYNOPSIS top compress [-fv] [-b bits] [file...] compress [-cfv] [-b bits] [file] DESCRIPTION top The compress utility shall attempt to reduce the size of the named files by using adaptive Lempel-Ziv coding algorithm. Note: Lempel-Ziv is US Patent 4464650, issued to William Eastman, Abraham Lempel, Jacob Ziv, Martin Cohn on August 7th, 1984, and assigned to Sperry Corporation. Lempel-Ziv-Welch compression is covered by US Patent 4558302, issued to Terry A. Welch on December 10th, 1985, and assigned to Sperry Corporation. On systems not supporting adaptive Lempel-Ziv coding algorithm, the input files shall not be changed and an error value greater than two shall be returned. Except when the output is to the standard output, each file shall be replaced by one with the extension .Z. If the invoking process has appropriate privileges, the ownership, modes, access time, and modification time of the original file are preserved. If appending the .Z to the filename would make the name exceed {NAME_MAX} bytes, the command shall fail. If no files are specified, the standard input shall be compressed to the standard output. OPTIONS top The compress utility shall conform to the Base Definitions volume of POSIX.12017, Section 12.2, Utility Syntax Guidelines. The following options shall be supported: -b bits Specify the maximum number of bits to use in a code. For a conforming application, the bits argument shall be: 9 <= bits <= 14 The implementation may allow bits values of greater than 14. The default is 14, 15, or 16. -c Cause compress to write to the standard output; the input file is not changed, and no .Z files are created. -f Force compression of file, even if it does not actually reduce the size of the file, or if the corresponding file.Z file already exists. If the -f option is not given, and the process is not running in the background, the user is prompted as to whether an existing file.Z file should be overwritten. If the response is affirmative, the existing file will be overwritten. -v Write the percentage reduction of each file to standard error. OPERANDS top The following operand shall be supported: file A pathname of a file to be compressed. STDIN top The standard input shall be used only if no file operands are specified, or if a file operand is '-'. INPUT FILES top If file operands are specified, the input files contain the data to be compressed. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of compress: 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 used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category. 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), the behavior of character classes used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category. LC_MESSAGES Determine the locale used to process affirmative responses, and the locale used to affect the format and contents of diagnostic messages, prompts, and the output from the -v option written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. ASYNCHRONOUS EVENTS top Default. STDOUT top If no file operands are specified, or if a file operand is '-', or if the -c option is specified, the standard output contains the compressed output. STDERR top The standard error shall be used only for diagnostic and prompt messages and the output from -v. OUTPUT FILES top The output files shall contain the compressed output. The format of compressed files is unspecified and interchange of such files between implementations (including access via unspecified file sharing mechanisms) is not required by POSIX.12008. EXTENDED DESCRIPTION top None. EXIT STATUS top The following exit values shall be returned: 0 Successful completion. 1 An error occurred. 2 One or more files were not compressed because they would have increased in size (and the -f option was not specified). >2 An error occurred. CONSEQUENCES OF ERRORS top The input file shall remain unmodified. The following sections are informative. APPLICATION USAGE top The amount of compression obtained depends on the size of the input, the number of bits per code, and the distribution of common substrings. Typically, text such as source code or English is reduced by 5060%. Compression is generally much better than that achieved by Huffman coding or adaptive Huffman coding (compact), and takes less time to compute. Although compress strictly follows the default actions upon receipt of a signal or when an error occurs, some unexpected results may occur. In some implementations it is likely that a partially compressed file is left in place, alongside its uncompressed input file. Since the general operation of compress is to delete the uncompressed file only after the .Z file has been successfully filled, an application should always carefully check the exit status of compress before arbitrarily deleting files that have like-named neighbors with .Z suffixes. The limit of 14 on the bits option-argument is to achieve portability to all systems (within the restrictions imposed by the lack of an explicit published file format). Some implementations based on 16-bit architectures cannot support 15 or 16-bit uncompression. EXAMPLES top None. RATIONALE top None. FUTURE DIRECTIONS top None. SEE ALSO top uncompress(1p), zcat(1p) The Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines 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 COMPRESS(1P) Pages that refer to this page: uncompress(1p), zcat(1p) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Compress all directories found in $LOGDIR wherein a file's data has been modified within the last 24 hours Bash Command:<START>find $LOGDIR -type d -mtime +0 -exec compress -r {} \;<END>
Compress all directories found in directory tree $LOGDIR that have been modified within the last 24 hours
find $LOGDIR -type d -mtime -1 -exec compress -r {} \;
['find', 'compress']
Output a Bash command to accomplish the following task. Task: Compress all directories found in directory tree $LOGDIR that have been modified within the last 24 hours Bash Command:<START>find $LOGDIR -type d -mtime -1 -exec compress -r {} \;<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 # compress\n\n> Compress files using the Unix `compress` command.\n> More information: <https://manned.org/compress.1>.\n\n- Compress specific files:\n\n`compress {{path/to/file1 path/to/file2 ...}}`\n\n- Compress specific files, ignore non-existent ones:\n\n`compress -f {{path/to/file1 path/to/file2 ...}}`\n\n- Specify the maximum compression bits (9-16 bits):\n\n`compress -b {{bits}}`\n\n- Write to `stdout` (no files are changed):\n\n`compress -c {{path/to/file}}`\n\n- Decompress files (functions like `uncompress`):\n\n`compress -d {{path/to/file}}`\n\n- Display compression percentage:\n\n`compress -v {{path/to/file}}`\n Task: Compress all directories found in directory tree $LOGDIR that have been modified within the last 24 hours Bash Command:<START>find $LOGDIR -type d -mtime -1 -exec compress -r {} \;<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. compress(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training compress(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 COMPRESS(1P) POSIX Programmer's Manual COMPRESS(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 compress compress data SYNOPSIS top compress [-fv] [-b bits] [file...] compress [-cfv] [-b bits] [file] DESCRIPTION top The compress utility shall attempt to reduce the size of the named files by using adaptive Lempel-Ziv coding algorithm. Note: Lempel-Ziv is US Patent 4464650, issued to William Eastman, Abraham Lempel, Jacob Ziv, Martin Cohn on August 7th, 1984, and assigned to Sperry Corporation. Lempel-Ziv-Welch compression is covered by US Patent 4558302, issued to Terry A. Welch on December 10th, 1985, and assigned to Sperry Corporation. On systems not supporting adaptive Lempel-Ziv coding algorithm, the input files shall not be changed and an error value greater than two shall be returned. Except when the output is to the standard output, each file shall be replaced by one with the extension .Z. If the invoking process has appropriate privileges, the ownership, modes, access time, and modification time of the original file are preserved. If appending the .Z to the filename would make the name exceed {NAME_MAX} bytes, the command shall fail. If no files are specified, the standard input shall be compressed to the standard output. OPTIONS top The compress utility shall conform to the Base Definitions volume of POSIX.12017, Section 12.2, Utility Syntax Guidelines. The following options shall be supported: -b bits Specify the maximum number of bits to use in a code. For a conforming application, the bits argument shall be: 9 <= bits <= 14 The implementation may allow bits values of greater than 14. The default is 14, 15, or 16. -c Cause compress to write to the standard output; the input file is not changed, and no .Z files are created. -f Force compression of file, even if it does not actually reduce the size of the file, or if the corresponding file.Z file already exists. If the -f option is not given, and the process is not running in the background, the user is prompted as to whether an existing file.Z file should be overwritten. If the response is affirmative, the existing file will be overwritten. -v Write the percentage reduction of each file to standard error. OPERANDS top The following operand shall be supported: file A pathname of a file to be compressed. STDIN top The standard input shall be used only if no file operands are specified, or if a file operand is '-'. INPUT FILES top If file operands are specified, the input files contain the data to be compressed. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of compress: 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 used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category. 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), the behavior of character classes used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category. LC_MESSAGES Determine the locale used to process affirmative responses, and the locale used to affect the format and contents of diagnostic messages, prompts, and the output from the -v option written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. ASYNCHRONOUS EVENTS top Default. STDOUT top If no file operands are specified, or if a file operand is '-', or if the -c option is specified, the standard output contains the compressed output. STDERR top The standard error shall be used only for diagnostic and prompt messages and the output from -v. OUTPUT FILES top The output files shall contain the compressed output. The format of compressed files is unspecified and interchange of such files between implementations (including access via unspecified file sharing mechanisms) is not required by POSIX.12008. EXTENDED DESCRIPTION top None. EXIT STATUS top The following exit values shall be returned: 0 Successful completion. 1 An error occurred. 2 One or more files were not compressed because they would have increased in size (and the -f option was not specified). >2 An error occurred. CONSEQUENCES OF ERRORS top The input file shall remain unmodified. The following sections are informative. APPLICATION USAGE top The amount of compression obtained depends on the size of the input, the number of bits per code, and the distribution of common substrings. Typically, text such as source code or English is reduced by 5060%. Compression is generally much better than that achieved by Huffman coding or adaptive Huffman coding (compact), and takes less time to compute. Although compress strictly follows the default actions upon receipt of a signal or when an error occurs, some unexpected results may occur. In some implementations it is likely that a partially compressed file is left in place, alongside its uncompressed input file. Since the general operation of compress is to delete the uncompressed file only after the .Z file has been successfully filled, an application should always carefully check the exit status of compress before arbitrarily deleting files that have like-named neighbors with .Z suffixes. The limit of 14 on the bits option-argument is to achieve portability to all systems (within the restrictions imposed by the lack of an explicit published file format). Some implementations based on 16-bit architectures cannot support 15 or 16-bit uncompression. EXAMPLES top None. RATIONALE top None. FUTURE DIRECTIONS top None. SEE ALSO top uncompress(1p), zcat(1p) The Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines 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 COMPRESS(1P) Pages that refer to this page: uncompress(1p), zcat(1p) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Compress all directories found in directory tree $LOGDIR that have been modified within the last 24 hours Bash Command:<START>find $LOGDIR -type d -mtime -1 -exec compress -r {} \;<END>
Compress all files in directory "$PATH_TO_LOGS" that were last modified more than "$SOME_NUMBER_OF_DAYS" days ago
find $PATH_TO_LOGS -maxdepth 1 -mtime +$SOME_NUMBER_OF_DAYS -exec gzip -N {} \;
['find']
Output a Bash command to accomplish the following task. Task: Compress all files in directory "$PATH_TO_LOGS" that were last modified more than "$SOME_NUMBER_OF_DAYS" days ago Bash Command:<START>find $PATH_TO_LOGS -maxdepth 1 -mtime +$SOME_NUMBER_OF_DAYS -exec gzip -N {} \;<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: Compress all files in directory "$PATH_TO_LOGS" that were last modified more than "$SOME_NUMBER_OF_DAYS" days ago Bash Command:<START>find $PATH_TO_LOGS -maxdepth 1 -mtime +$SOME_NUMBER_OF_DAYS -exec gzip -N {} \;<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: Compress all files in directory "$PATH_TO_LOGS" that were last modified more than "$SOME_NUMBER_OF_DAYS" days ago Bash Command:<START>find $PATH_TO_LOGS -maxdepth 1 -mtime +$SOME_NUMBER_OF_DAYS -exec gzip -N {} \;<END>
Compress all files in the "$FILE" directory tree that were last modified 30 days ago
find $FILE -type f -mtime 30 -exec gzip {} \;
['find']
Output a Bash command to accomplish the following task. Task: Compress all files in the "$FILE" directory tree that were last modified 30 days ago Bash Command:<START>find $FILE -type f -mtime 30 -exec gzip {} \;<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: Compress all files in the "$FILE" directory tree that were last modified 30 days ago Bash Command:<START>find $FILE -type f -mtime 30 -exec gzip {} \;<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: Compress all files in the "$FILE" directory tree that were last modified 30 days ago Bash Command:<START>find $FILE -type f -mtime 30 -exec gzip {} \;<END>
Compress all files in the "$FILE" directory tree that were last modified 30 days ago and have not already been compressed with gzip
find $FILE -type f -not -name '*.gz' -mtime 30 -exec gzip {} \;
['find']
Output a Bash command to accomplish the following task. Task: Compress all files in the "$FILE" directory tree that were last modified 30 days ago and have not already been compressed with gzip Bash Command:<START>find $FILE -type f -not -name '*.gz' -mtime 30 -exec gzip {} \;<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: Compress all files in the "$FILE" directory tree that were last modified 30 days ago and have not already been compressed with gzip Bash Command:<START>find $FILE -type f -not -name '*.gz' -mtime 30 -exec gzip {} \;<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: Compress all files in the "$FILE" directory tree that were last modified 30 days ago and have not already been compressed with gzip Bash Command:<START>find $FILE -type f -not -name '*.gz' -mtime 30 -exec gzip {} \;<END>
Compress all files under /source directory tree using gzip with best compression method
find /source -type f -print0 | xargs -0 -n 1 -P $CORES gzip -9
['find', 'xargs']
Output a Bash command to accomplish the following task. Task: Compress all files under /source directory tree using gzip with best compression method Bash Command:<START>find /source -type f -print0 | xargs -0 -n 1 -P $CORES gzip -9<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # 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: Compress all files under /source directory tree using gzip with best compression method Bash Command:<START>find /source -type f -print0 | xargs -0 -n 1 -P $CORES gzip -9<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. 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: Compress all files under /source directory tree using gzip with best compression method Bash Command:<START>find /source -type f -print0 | xargs -0 -n 1 -P $CORES gzip -9<END>
Compress all files under current directory tree with gzip
find . -type f -print0 | xargs -0r gzip
['find', 'xargs']
Output a Bash command to accomplish the following task. Task: Compress all files under current directory tree with gzip Bash Command:<START>find . -type f -print0 | xargs -0r gzip<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 Task: Compress all files under current directory tree with gzip Bash Command:<START>find . -type f -print0 | xargs -0r gzip<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. Task: Compress all files under current directory tree with gzip Bash Command:<START>find . -type f -print0 | xargs -0r gzip<END>
Compress all files with '.txt' extension under current directory
echo *.txt | xargs gzip -9
['xargs', 'echo']
Output a Bash command to accomplish the following task. Task: Compress all files with '.txt' extension under current directory Bash Command:<START>echo *.txt | xargs gzip -9<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # 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: Compress all files with '.txt' extension under current directory Bash Command:<START>echo *.txt | xargs gzip -9<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. 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: Compress all files with '.txt' extension under current directory Bash Command:<START>echo *.txt | xargs gzip -9<END>
Compress and display the gzip compression ratio of every file on the system that is greater than 100000 bytes and ends in ".log"
sudo find / -xdev -type f -size +100000 -name "*.log" -exec gzip -v {} \;
['find', 'sudo']
Output a Bash command to accomplish the following task. Task: Compress and display the gzip compression ratio of every file on the system that is greater than 100000 bytes and ends in ".log" Bash Command:<START>sudo find / -xdev -type f -size +100000 -name "*.log" -exec gzip -v {} \;<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 # sudo\n\n> Executes a single command as the superuser or another user.\n> More information: <https://www.sudo.ws/sudo.html>.\n\n- Run a command as the superuser:\n\n`sudo {{less /var/log/syslog}}`\n\n- Edit a file as the superuser with your default editor:\n\n`sudo --edit {{/etc/fstab}}`\n\n- Run a command as another user and/or group:\n\n`sudo --user={{user}} --group={{group}} {{id -a}}`\n\n- Repeat the last command prefixed with `sudo` (only in Bash, Zsh, etc.):\n\n`sudo !!`\n\n- Launch the default shell with superuser privileges and run login-specific files (`.profile`, `.bash_profile`, etc.):\n\n`sudo --login`\n\n- Launch the default shell with superuser privileges without changing the environment:\n\n`sudo --shell`\n\n- Launch the default shell as the specified user, loading the user's environment and reading login-specific files (`.profile`, `.bash_profile`, etc.):\n\n`sudo --login --user={{user}}`\n\n- List the allowed (and forbidden) commands for the invoking user:\n\n`sudo --list`\n Task: Compress and display the gzip compression ratio of every file on the system that is greater than 100000 bytes and ends in ".log" Bash Command:<START>sudo find / -xdev -type f -size +100000 -name "*.log" -exec gzip -v {} \;<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. sudo(8) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sudo(8) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND EXECUTION | EXIT VALUE | SECURITY NOTES | ENVIRONMENT | FILES | EXAMPLES | DIAGNOSTICS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | BUGS | SUPPORT | DISCLAIMER | COLOPHON SUDO(8) System Manager's Manual SUDO(8) NAME top sudo, sudoedit execute a command as another user SYNOPSIS top sudo -h | -K | -k | -V sudo -v [-ABkNnS] [-g group] [-h host] [-p prompt] [-u user] sudo -l [-ABkNnS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command [arg ...]] sudo [-ABbEHnPS] [-C num] [-D directory] [-g group] [-h host] [-p prompt] [-R directory] [-T timeout] [-u user] [VAR=value] [-i | -s] [command [arg ...]] sudoedit [-ABkNnS] [-C num] [-D directory] [-g group] [-h host] [-p prompt] [-R directory] [-T timeout] [-u user] file ... DESCRIPTION top allows a permitted user to execute a command as the superuser or another user, as specified by the security policy. The invoking user's real (not effective) user-ID is used to determine the user name with which to query the security policy. supports a plugin architecture for security policies, auditing, and input/output logging. Third parties can develop and distribute their own plugins to work seamlessly with the front- end. The default security policy is sudoers, which is configured via the file /etc/sudoers, or via LDAP. See the Plugins section for more information. The security policy determines what privileges, if any, a user has to run . The policy may require that users authenticate themselves with a password or another authentication mechanism. If authentication is required, will exit if the user's password is not entered within a configurable time limit. This limit is policy-specific; the default password prompt timeout for the sudoers security policy is 5 minutes. Security policies may support credential caching to allow the user to run again for a period of time without requiring authentication. By default, the sudoers policy caches credentials on a per-terminal basis for 5 minutes. See the timestamp_type and timestamp_timeout options in sudoers(5) for more information. By running with the -v option, a user can update the cached credentials without running a command. On systems where is the primary method of gaining superuser privileges, it is imperative to avoid syntax errors in the security policy configuration files. For the default security policy, sudoers(5), changes to the configuration files should be made using the visudo(8) utility which will ensure that no syntax errors are introduced. When invoked as sudoedit, the -e option (described below), is implied. Security policies and audit plugins may log successful and failed attempts to run . If an I/O plugin is configured, the running command's input and output may be logged as well. The options are as follows: -A, --askpass Normally, if requires a password, it will read it from the user's terminal. If the -A (askpass) option is specified, a (possibly graphical) helper program is executed to read the user's password and output the password to the standard output. If the SUDO_ASKPASS environment variable is set, it specifies the path to the helper program. Otherwise, if sudo.conf(5) contains a line specifying the askpass program, that value will be used. For example: # Path to askpass helper program Path askpass /usr/X11R6/bin/ssh-askpass If no askpass program is available, will exit with an error. -B, --bell Ring the bell as part of the password prompt when a terminal is present. This option has no effect if an askpass program is used. -b, --background Run the given command in the background. It is not possible to use shell job control to manipulate background processes started by . Most interactive commands will fail to work properly in background mode. -C num, --close-from=num Close all file descriptors greater than or equal to num before executing a command. Values less than three are not permitted. By default, will close all open file descriptors other than standard input, standard output, and standard error when executing a command. The security policy may restrict the user's ability to use this option. The sudoers policy only permits use of the -C option when the administrator has enabled the closefrom_override option. -D directory, --chdir=directory Run the command in the specified directory instead of the current working directory. The security policy may return an error if the user does not have permission to specify the working directory. -E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment. --preserve-env=list Indicates to the security policy that the user wishes to add the comma-separated list of environment variables to those preserved from the user's environment. The security policy may return an error if the user does not have permission to preserve the environment. This option may be specified multiple times. -e, --edit Edit one or more files instead of running a command. In lieu of a path name, the string "sudoedit" is used when consulting the security policy. If the user is authorized by the policy, the following steps are taken: 1. Temporary copies are made of the files to be edited with the owner set to the invoking user. 2. The editor specified by the policy is run to edit the temporary files. The sudoers policy uses the SUDO_EDITOR, VISUAL and EDITOR environment variables (in that order). If none of SUDO_EDITOR, VISUAL or EDITOR are set, the first program listed in the editor sudoers(5) option is used. 3. If they have been modified, the temporary files are copied back to their original location and the temporary versions are removed. To help prevent the editing of unauthorized files, the following restrictions are enforced unless explicitly allowed by the security policy: Symbolic links may not be edited (version 1.8.15 and higher). Symbolic links along the path to be edited are not followed when the parent directory is writable by the invoking user unless that user is root (version 1.8.16 and higher). Files located in a directory that is writable by the invoking user may not be edited unless that user is root (version 1.8.16 and higher). Users are never allowed to edit device special files. If the specified file does not exist, it will be created. Unlike most commands run by sudo, the editor is run with the invoking user's environment unmodified. If the temporary file becomes empty after editing, the user will be prompted before it is installed. If, for some reason, is unable to update a file with its edited version, the user will receive a warning and the edited copy will remain in a temporary file. -g group, --group=group Run the command with the primary group set to group instead of the primary group specified by the target user's password database entry. The group may be either a group name or a numeric group-ID (GID) prefixed with the # character (e.g., #0 for GID 0). When running a command as a GID, many shells require that the # be escaped with a backslash (\). If no -u option is specified, the command will be run as the invoking user. In either case, the primary group will be set to group. The sudoers policy permits any of the target user's groups to be specified via the -g option as long as the -P option is not in use. -H, --set-home Request that the security policy set the HOME environment variable to the home directory specified by the target user's password database entry. Depending on the policy, this may be the default behavior. -h, --help Display a short help message to the standard output and exit. -h host, --host=host Run the command on the specified host if the security policy plugin supports remote commands. The sudoers plugin does not currently support running remote commands. This may also be used in conjunction with the -l option to list a user's privileges for the remote host. -i, --login Run the shell specified by the target user's password database entry as a login shell. This means that login- specific resource files such as .profile, .bash_profile, or .login will be read by the shell. If a command is specified, it is passed to the shell as a simple command using the -c option. The command and any args are concatenated, separated by spaces, after escaping each character (including white space) with a backslash (\) except for alphanumerics, underscores, hyphens, and dollar signs. If no command is specified, an interactive shell is executed. attempts to change to that user's home directory before running the shell. The command is run with an environment similar to the one a user would receive at log in. Most shells behave differently when a command is specified as compared to an interactive session; consult the shell's manual for details. The Command environment section in the sudoers(5) manual documents how the -i option affects the environment in which a command is run when the sudoers policy is in use. -K, --remove-timestamp Similar to the -k option, except that it removes every cached credential for the user, regardless of the terminal or parent process ID. The next time is run, a password must be entered if the security policy requires authentication. It is not possible to use the -K option in conjunction with a command or other option. This option does not require a password. Not all security policies support credential caching. -k, --reset-timestamp When used without a command, invalidates the user's cached credentials for the current session. The next time is run in the session, a password must be entered if the security policy requires authentication. By default, the sudoers policy uses a separate record in the credential cache for each terminal (or parent process ID if no terminal is present). This prevents the -k option from interfering with commands run in a different terminal session. See the timestamp_type option in sudoers(5) for more information. This option does not require a password, and was added to allow a user to revoke permissions from a .logout file. When used in conjunction with a command or an option that may require a password, this option will cause to ignore the user's cached credentials. As a result, will prompt for a password (if one is required by the security policy) and will not update the user's cached credentials. Not all security policies support credential caching. -l, --list If no command is specified, list the privileges for the invoking user (or the user specified by the -U option) on the current host. A longer list format is used if this option is specified multiple times and the security policy supports a verbose output format. If a command is specified and is permitted by the security policy for the invoking user (or the, user specified by the -U option) on the current host, the fully-qualified path to the command is displayed along with any args. If -l is specified more than once (and the security policy supports it), the matching rule is displayed in a verbose format along with the command. If a command is specified but not allowed by the policy, will exit with a status value of 1. -N, --no-update Do not update the user's cached credentials, even if the user successfully authenticates. Unlike the -k flag, existing cached credentials are used if they are valid. To detect when the user's cached credentials are valid (or when no authentication is required), the following can be used: sudo -Nnv Not all security policies support credential caching. -n, --non-interactive Avoid prompting the user for input of any kind. If a password is required for the command to run, will display an error message and exit. -P, --preserve-groups Preserve the invoking user's group vector unaltered. By default, the sudoers policy will initialize the group vector to the list of groups the target user is a member of. The real and effective group-IDs, however, are still set to match the target user. -p prompt, --prompt=prompt Use a custom password prompt with optional escape sequences. The following percent (%) escape sequences are supported by the sudoers policy: %H expanded to the host name including the domain name (only if the machine's host name is fully qualified or the fqdn option is set in sudoers(5)) %h expanded to the local host name without the domain name %p expanded to the name of the user whose password is being requested (respects the rootpw, targetpw, and runaspw flags in sudoers(5)) %U expanded to the login name of the user the command will be run as (defaults to root unless the -u option is also specified) %u expanded to the invoking user's login name %% two consecutive % characters are collapsed into a single % character The custom prompt will override the default prompt specified by either the security policy or the SUDO_PROMPT environment variable. On systems that use PAM, the custom prompt will also override the prompt specified by a PAM module unless the passprompt_override flag is disabled in sudoers. -R directory, --chroot=directory Change to the specified root directory (see chroot(8)) before running the command. The security policy may return an error if the user does not have permission to specify the root directory. -S, --stdin Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. -s, --shell Run the shell specified by the SHELL environment variable if it is set or the shell specified by the invoking user's password database entry. If a command is specified, it is passed to the shell as a simple command using the -c option. The command and any args are concatenated, separated by spaces, after escaping each character (including white space) with a backslash (\) except for alphanumerics, underscores, hyphens, and dollar signs. If no command is specified, an interactive shell is executed. Most shells behave differently when a command is specified as compared to an interactive session; consult the shell's manual for details. -U user, --other-user=user Used in conjunction with the -l option to list the privileges for user instead of for the invoking user. The security policy may restrict listing other users' privileges. When using the sudoers policy, the -U option is restricted to the root user and users with either the list priviege for the specified user or the ability to run any command as root or user on the current host. -T timeout, --command-timeout=timeout Used to set a timeout for the command. If the timeout expires before the command has exited, the command will be terminated. The security policy may restrict the user's ability to set timeouts. The sudoers policy requires that user-specified timeouts be explicitly enabled. -u user, --user=user Run the command as a user other than the default target user (usually root). The user may be either a user name or a numeric user-ID (UID) prefixed with the # character (e.g., #0 for UID 0). When running commands as a UID, many shells require that the # be escaped with a backslash (\). Some security policies may restrict UIDs to those listed in the password database. The sudoers policy allows UIDs that are not in the password database as long as the targetpw option is not set. Other security policies may not support this. -V, --version Print the version string as well as the version string of any configured plugins. If the invoking user is already root, the -V option will display the options passed to configure when was built; plugins may display additional information such as default options. -v, --validate Update the user's cached credentials, authenticating the user if necessary. For the sudoers plugin, this extends the timeout for another 5 minutes by default, but does not run a command. Not all security policies support cached credentials. -- The -- is used to delimit the end of the options. Subsequent options are passed to the command. Options that take a value may only be specified once unless otherwise indicated in the description. This is to help guard against problems caused by poorly written scripts that invoke sudo with user-controlled input. Environment variables to be set for the command may also be passed as options to in the form VAR=value, for example LD_LIBRARY_PATH=/usr/local/pkg/lib. Environment variables may be subject to restrictions imposed by the security policy plugin. The sudoers policy subjects environment variables passed as options to the same restrictions as existing environment variables with one important difference. If the setenv option is set in sudoers, the command to be run has the SETENV tag set or the command matched is ALL, the user may set variables that would otherwise be forbidden. See sudoers(5) for more information. COMMAND EXECUTION top When executes a command, the security policy specifies the execution environment for the command. Typically, the real and effective user and group and IDs are set to match those of the target user, as specified in the password database, and the group vector is initialized based on the group database (unless the -P option was specified). The following parameters may be specified by security policy: real and effective user-ID real and effective group-ID supplementary group-IDs the environment list current working directory file creation mode mask (umask) scheduling priority (aka nice value) Process model There are two distinct ways can run a command. If an I/O logging plugin is configured to log terminal I/O, or if the security policy explicitly requests it, a new pseudo-terminal (pty) is allocated and fork(2) is used to create a second process, referred to as the monitor. The monitor creates a new terminal session with itself as the leader and the pty as its controlling terminal, calls fork(2) again, sets up the execution environment as described above, and then uses the execve(2) system call to run the command in the child process. The monitor exists to relay job control signals between the user's terminal and the pty the command is being run in. This makes it possible to suspend and resume the command normally. Without the monitor, the command would be in what POSIX terms an orphaned process group and it would not receive any job control signals from the kernel. When the command exits or is terminated by a signal, the monitor passes the command's exit status to the main process and exits. After receiving the command's exit status, the main process passes the command's exit status to the security policy's close function, as well as the close function of any configured audit plugin, and exits. This mode is the default for sudo versions 1.9.14 and above when using the sudoers policy. If no pty is used, calls fork(2), sets up the execution environment as described above, and uses the execve(2) system call to run the command in the child process. The main process waits until the command has completed, then passes the command's exit status to the security policy's close function, as well as the close function of any configured audit plugins, and exits. As a special case, if the policy plugin does not define a close function, will execute the command directly instead of calling fork(2) first. The sudoers policy plugin will only define a close function when I/O logging is enabled, a pty is required, an SELinux role is specified, the command has an associated timeout, or the pam_session or pam_setcred options are enabled. Both pam_session and pam_setcred are enabled by default on systems using PAM. This mode is the default for sudo versions prior to 1.9.14 when using the sudoers policy. On systems that use PAM, the security policy's close function is responsible for closing the PAM session. It may also log the command's exit status. Signal handling When the command is run as a child of the process, will relay signals it receives to the command. The SIGINT and SIGQUIT signals are only relayed when the command is being run in a new pty or when the signal was sent by a user process, not the kernel. This prevents the command from receiving SIGINT twice each time the user enters control-C. Some signals, such as SIGSTOP and SIGKILL, cannot be caught and thus will not be relayed to the command. As a general rule, SIGTSTP should be used instead of SIGSTOP when you wish to suspend a command being run by . As a special case, will not relay signals that were sent by the command it is running. This prevents the command from accidentally killing itself. On some systems, the reboot(8) utility sends SIGTERM to all non-system processes other than itself before rebooting the system. This prevents from relaying the SIGTERM signal it received back to reboot(8), which might then exit before the system was actually rebooted, leaving it in a half-dead state similar to single user mode. Note, however, that this check only applies to the command run by and not any other processes that the command may create. As a result, running a script that calls reboot(8) or shutdown(8) via may cause the system to end up in this undefined state unless the reboot(8) or shutdown(8) are run using the exec() family of functions instead of system() (which interposes a shell between the command and the calling process). Plugins Plugins may be specified via Plugin directives in the sudo.conf(5) file. They may be loaded as dynamic shared objects (on systems that support them), or compiled directly into the binary. If no sudo.conf(5) file is present, or if it doesn't contain any Plugin lines, will use sudoers(5) for the policy, auditing, and I/O logging plugins. See the sudo.conf(5) manual for details of the /etc/sudo.conf file and the sudo_plugin(5) manual for more information about the plugin architecture. EXIT VALUE top Upon successful execution of a command, the exit status from will be the exit status of the program that was executed. If the command terminated due to receipt of a signal, will send itself the same signal that terminated the command. If the -l option was specified without a command, will exit with a value of 0 if the user is allowed to run and they authenticated successfully (as required by the security policy). If a command is specified with the -l option, the exit value will only be 0 if the command is permitted by the security policy, otherwise it will be 1. If there is an authentication failure, a configuration/permission problem, or if the given command cannot be executed, exits with a value of 1. In the latter case, the error string is printed to the standard error. If cannot stat(2) one or more entries in the user's PATH, an error is printed to the standard error. (If the directory does not exist or if it is not really a directory, the entry is ignored and no error is printed.) This should not happen under normal circumstances. The most common reason for stat(2) to return permission denied is if you are running an automounter and one of the directories in your PATH is on a machine that is currently unreachable. SECURITY NOTES top tries to be safe when executing external commands. To prevent command spoofing, checks "." and "" (both denoting current directory) last when searching for a command in the user's PATH (if one or both are in the PATH). Depending on the security policy, the user's PATH environment variable may be modified, replaced, or passed unchanged to the program that executes. Users should never be granted privileges to execute files that are writable by the user or that reside in a directory that is writable by the user. If the user can modify or replace the command there is no way to limit what additional commands they can run. By default, will only log the command it explicitly runs. If a user runs a command such as sudo su or sudo sh, subsequent commands run from that shell are not subject to sudo's security policy. The same is true for commands that offer shell escapes (including most editors). If I/O logging is enabled, subsequent commands will have their input and/or output logged, but there will not be traditional logs for those commands. Because of this, care must be taken when giving users access to commands via to verify that the command does not inadvertently give the user an effective root shell. For information on ways to address this, see the Preventing shell escapes section in sudoers(5). To prevent the disclosure of potentially sensitive information, disables core dumps by default while it is executing (they are re-enabled for the command that is run). This historical practice dates from a time when most operating systems allowed set-user-ID processes to dump core by default. To aid in debugging crashes, you may wish to re-enable core dumps by setting disable_coredump to false in the sudo.conf(5) file as follows: Set disable_coredump false See the sudo.conf(5) manual for more information. ENVIRONMENT top utilizes the following environment variables. The security policy has control over the actual content of the command's environment. EDITOR Default editor to use in -e (sudoedit) mode if neither SUDO_EDITOR nor VISUAL is set. MAIL Set to the mail spool of the target user when the -i option is specified, or when env_reset is enabled in sudoers (unless MAIL is present in the env_keep list). HOME Set to the home directory of the target user when the -i or -H options are specified, when the -s option is specified and set_home is set in sudoers, when always_set_home is enabled in sudoers, or when env_reset is enabled in sudoers and HOME is not present in the env_keep list. LOGNAME Set to the login name of the target user when the -i option is specified, when the set_logname option is enabled in sudoers, or when the env_reset option is enabled in sudoers (unless LOGNAME is present in the env_keep list). PATH May be overridden by the security policy. SHELL Used to determine shell to run with -s option. SUDO_ASKPASS Specifies the path to a helper program used to read the password if no terminal is available or if the -A option is specified. SUDO_COMMAND Set to the command run by sudo, including any args. The args are truncated at 4096 characters to prevent a potential execution error. SUDO_EDITOR Default editor to use in -e (sudoedit) mode. SUDO_GID Set to the group-ID of the user who invoked sudo. SUDO_PROMPT Used as the default password prompt unless the -p option was specified. SUDO_PS1 If set, PS1 will be set to its value for the program being run. SUDO_UID Set to the user-ID of the user who invoked sudo. SUDO_USER Set to the login name of the user who invoked sudo. USER Set to the same value as LOGNAME, described above. VISUAL Default editor to use in -e (sudoedit) mode if SUDO_EDITOR is not set. FILES top /etc/sudo.conf front-end configuration EXAMPLES top The following examples assume a properly configured security policy. To get a file listing of an unreadable directory: $ sudo ls /usr/local/protected To list the home directory of user yaz on a machine where the file system holding ~yaz is not exported as root: $ sudo -u yaz ls ~yaz To edit the index.html file as user www: $ sudoedit -u www ~www/htdocs/index.html To view system logs only accessible to root and users in the adm group: $ sudo -g adm more /var/log/syslog To run an editor as jim with a different primary group: $ sudoedit -u jim -g audio ~jim/sound.txt To shut down a machine: $ sudo shutdown -r +15 "quick reboot" To make a usage listing of the directories in the /home partition. The commands are run in a sub-shell to allow the cd command and file redirection to work. $ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE" DIAGNOSTICS top Error messages produced by include: editing files in a writable directory is not permitted By default, sudoedit does not permit editing a file when any of the parent directories are writable by the invoking user. This avoids a race condition that could allow the user to overwrite an arbitrary file. See the sudoedit_checkdir option in sudoers(5) for more information. editing symbolic links is not permitted By default, sudoedit does not follow symbolic links when opening files. See the sudoedit_follow option in sudoers(5) for more information. effective uid is not 0, is sudo installed setuid root? was not run with root privileges. The binary must be owned by the root user and have the set-user-ID bit set. Also, it must not be located on a file system mounted with the nosuid option or on an NFS file system that maps uid 0 to an unprivileged uid. effective uid is not 0, is sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges? was not run with root privileges. The binary has the proper owner and permissions but it still did not run with root privileges. The most common reason for this is that the file system the binary is located on is mounted with the nosuid option or it is an NFS file system that maps uid 0 to an unprivileged uid. fatal error, unable to load plugins An error occurred while loading or initializing the plugins specified in sudo.conf(5). invalid environment variable name One or more environment variable names specified via the -E option contained an equal sign (=). The arguments to the -E option should be environment variable names without an associated value. no password was provided When tried to read the password, it did not receive any characters. This may happen if no terminal is available (or the -S option is specified) and the standard input has been redirected from /dev/null. a terminal is required to read the password needs to read the password but there is no mechanism available for it to do so. A terminal is not present to read the password from, has not been configured to read from the standard input, the -S option was not used, and no askpass helper has been specified either via the sudo.conf(5) file or the SUDO_ASKPASS environment variable. no writable temporary directory found sudoedit was unable to find a usable temporary directory in which to store its intermediate files. The no new privileges flag is set, which prevents sudo from running as root. was run by a process that has the Linux no new privileges flag is set. This causes the set-user-ID bit to be ignored when running an executable, which will prevent from functioning. The most likely cause for this is running within a container that sets this flag. Check the documentation to see if it is possible to configure the container such that the flag is not set. sudo must be owned by uid 0 and have the setuid bit set was not run with root privileges. The binary does not have the correct owner or permissions. It must be owned by the root user and have the set-user-ID bit set. sudoedit is not supported on this platform It is only possible to run sudoedit on systems that support setting the effective user-ID. timed out reading password The user did not enter a password before the password timeout (5 minutes by default) expired. you do not exist in the passwd database Your user-ID does not appear in the system passwd database. you may not specify environment variables in edit mode It is only possible to specify environment variables when running a command. When editing a file, the editor is run with the user's environment unmodified. SEE ALSO top su(1), stat(2), login_cap(3), passwd(5), sudo.conf(5), sudo_plugin(5), sudoers(5), sudoers_timestamp(5), sudoreplay(8), visudo(8) HISTORY top See the HISTORY.md file in the distribution (https://www.sudo.ws/about/history/) for a brief history of sudo. AUTHORS top Many people have worked on over the years; this version consists of code written primarily by: Todd C. Miller See the CONTRIBUTORS.md file in the distribution (https://www.sudo.ws/about/contributors/) for an exhaustive list of people who have contributed to . CAVEATS top There is no easy way to prevent a user from gaining a root shell if that user is allowed to run arbitrary commands via . Also, many programs (such as editors) allow the user to run commands via shell escapes, thus avoiding sudo's checks. However, on most systems it is possible to prevent shell escapes with the sudoers(5) plugin's noexec functionality. It is not meaningful to run the cd command directly via sudo, e.g., $ sudo cd /usr/local/protected since when the command exits the parent process (your shell) will still be the same. The -D option can be used to run a command in a specific directory. Running shell scripts via can expose the same kernel bugs that make set-user-ID shell scripts unsafe on some operating systems (if your OS has a /dev/fd/ directory, set-user-ID shell scripts are generally safe). BUGS top If you believe you have found a bug in , you can submit a bug report at https://bugzilla.sudo.ws/ SUPPORT top Limited free support is available via the sudo-users mailing list, see https://www.sudo.ws/mailman/listinfo/sudo-users to subscribe or search the archives. DISCLAIMER top is provided AS IS and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. See the LICENSE.md file distributed with or https://www.sudo.ws/about/license/ for complete details. COLOPHON top This page is part of the sudo (execute a command as another user) project. Information about the project can be found at https://www.sudo.ws/. If you have a bug report for this manual page, see https://bugzilla.sudo.ws/. This page was obtained from the project's upstream Git repository https://github.com/sudo-project/sudo on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-12-21.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org Sudo 1.9.15p4 August 9, 2023 SUDO(8) Pages that refer to this page: homectl(1), journalctl(1), localectl(1), loginctl(1), machinectl(1), portablectl(1), setpriv(1), systemctl(1), systemd(1), systemd-analyze(1), systemd-ask-password(1), systemd-inhibit(1), systemd-nspawn(1), systemd-vmspawn(1), timedatectl(1), uid0(1), userdbctl(1), nsswitch.conf(5), credentials(7), systemd-tmpfiles(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: Compress and display the gzip compression ratio of every file on the system that is greater than 100000 bytes and ends in ".log" Bash Command:<START>sudo find / -xdev -type f -size +100000 -name "*.log" -exec gzip -v {} \;<END>
Compress and display the original filename of every file on the system that is greater than 100000 bytes and ends in ".log"
sudo find / -xdev -type f -size +100000 -name "*.log" -exec gzip {} \; -exec echo {} \;
['find', 'echo', 'sudo']
Output a Bash command to accomplish the following task. Task: Compress and display the original filename of every file on the system that is greater than 100000 bytes and ends in ".log" Bash Command:<START>sudo find / -xdev -type f -size +100000 -name "*.log" -exec gzip {} \; -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 # sudo\n\n> Executes a single command as the superuser or another user.\n> More information: <https://www.sudo.ws/sudo.html>.\n\n- Run a command as the superuser:\n\n`sudo {{less /var/log/syslog}}`\n\n- Edit a file as the superuser with your default editor:\n\n`sudo --edit {{/etc/fstab}}`\n\n- Run a command as another user and/or group:\n\n`sudo --user={{user}} --group={{group}} {{id -a}}`\n\n- Repeat the last command prefixed with `sudo` (only in Bash, Zsh, etc.):\n\n`sudo !!`\n\n- Launch the default shell with superuser privileges and run login-specific files (`.profile`, `.bash_profile`, etc.):\n\n`sudo --login`\n\n- Launch the default shell with superuser privileges without changing the environment:\n\n`sudo --shell`\n\n- Launch the default shell as the specified user, loading the user's environment and reading login-specific files (`.profile`, `.bash_profile`, etc.):\n\n`sudo --login --user={{user}}`\n\n- List the allowed (and forbidden) commands for the invoking user:\n\n`sudo --list`\n Task: Compress and display the original filename of every file on the system that is greater than 100000 bytes and ends in ".log" Bash Command:<START>sudo find / -xdev -type f -size +100000 -name "*.log" -exec gzip {} \; -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. sudo(8) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sudo(8) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND EXECUTION | EXIT VALUE | SECURITY NOTES | ENVIRONMENT | FILES | EXAMPLES | DIAGNOSTICS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | BUGS | SUPPORT | DISCLAIMER | COLOPHON SUDO(8) System Manager's Manual SUDO(8) NAME top sudo, sudoedit execute a command as another user SYNOPSIS top sudo -h | -K | -k | -V sudo -v [-ABkNnS] [-g group] [-h host] [-p prompt] [-u user] sudo -l [-ABkNnS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command [arg ...]] sudo [-ABbEHnPS] [-C num] [-D directory] [-g group] [-h host] [-p prompt] [-R directory] [-T timeout] [-u user] [VAR=value] [-i | -s] [command [arg ...]] sudoedit [-ABkNnS] [-C num] [-D directory] [-g group] [-h host] [-p prompt] [-R directory] [-T timeout] [-u user] file ... DESCRIPTION top allows a permitted user to execute a command as the superuser or another user, as specified by the security policy. The invoking user's real (not effective) user-ID is used to determine the user name with which to query the security policy. supports a plugin architecture for security policies, auditing, and input/output logging. Third parties can develop and distribute their own plugins to work seamlessly with the front- end. The default security policy is sudoers, which is configured via the file /etc/sudoers, or via LDAP. See the Plugins section for more information. The security policy determines what privileges, if any, a user has to run . The policy may require that users authenticate themselves with a password or another authentication mechanism. If authentication is required, will exit if the user's password is not entered within a configurable time limit. This limit is policy-specific; the default password prompt timeout for the sudoers security policy is 5 minutes. Security policies may support credential caching to allow the user to run again for a period of time without requiring authentication. By default, the sudoers policy caches credentials on a per-terminal basis for 5 minutes. See the timestamp_type and timestamp_timeout options in sudoers(5) for more information. By running with the -v option, a user can update the cached credentials without running a command. On systems where is the primary method of gaining superuser privileges, it is imperative to avoid syntax errors in the security policy configuration files. For the default security policy, sudoers(5), changes to the configuration files should be made using the visudo(8) utility which will ensure that no syntax errors are introduced. When invoked as sudoedit, the -e option (described below), is implied. Security policies and audit plugins may log successful and failed attempts to run . If an I/O plugin is configured, the running command's input and output may be logged as well. The options are as follows: -A, --askpass Normally, if requires a password, it will read it from the user's terminal. If the -A (askpass) option is specified, a (possibly graphical) helper program is executed to read the user's password and output the password to the standard output. If the SUDO_ASKPASS environment variable is set, it specifies the path to the helper program. Otherwise, if sudo.conf(5) contains a line specifying the askpass program, that value will be used. For example: # Path to askpass helper program Path askpass /usr/X11R6/bin/ssh-askpass If no askpass program is available, will exit with an error. -B, --bell Ring the bell as part of the password prompt when a terminal is present. This option has no effect if an askpass program is used. -b, --background Run the given command in the background. It is not possible to use shell job control to manipulate background processes started by . Most interactive commands will fail to work properly in background mode. -C num, --close-from=num Close all file descriptors greater than or equal to num before executing a command. Values less than three are not permitted. By default, will close all open file descriptors other than standard input, standard output, and standard error when executing a command. The security policy may restrict the user's ability to use this option. The sudoers policy only permits use of the -C option when the administrator has enabled the closefrom_override option. -D directory, --chdir=directory Run the command in the specified directory instead of the current working directory. The security policy may return an error if the user does not have permission to specify the working directory. -E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment. --preserve-env=list Indicates to the security policy that the user wishes to add the comma-separated list of environment variables to those preserved from the user's environment. The security policy may return an error if the user does not have permission to preserve the environment. This option may be specified multiple times. -e, --edit Edit one or more files instead of running a command. In lieu of a path name, the string "sudoedit" is used when consulting the security policy. If the user is authorized by the policy, the following steps are taken: 1. Temporary copies are made of the files to be edited with the owner set to the invoking user. 2. The editor specified by the policy is run to edit the temporary files. The sudoers policy uses the SUDO_EDITOR, VISUAL and EDITOR environment variables (in that order). If none of SUDO_EDITOR, VISUAL or EDITOR are set, the first program listed in the editor sudoers(5) option is used. 3. If they have been modified, the temporary files are copied back to their original location and the temporary versions are removed. To help prevent the editing of unauthorized files, the following restrictions are enforced unless explicitly allowed by the security policy: Symbolic links may not be edited (version 1.8.15 and higher). Symbolic links along the path to be edited are not followed when the parent directory is writable by the invoking user unless that user is root (version 1.8.16 and higher). Files located in a directory that is writable by the invoking user may not be edited unless that user is root (version 1.8.16 and higher). Users are never allowed to edit device special files. If the specified file does not exist, it will be created. Unlike most commands run by sudo, the editor is run with the invoking user's environment unmodified. If the temporary file becomes empty after editing, the user will be prompted before it is installed. If, for some reason, is unable to update a file with its edited version, the user will receive a warning and the edited copy will remain in a temporary file. -g group, --group=group Run the command with the primary group set to group instead of the primary group specified by the target user's password database entry. The group may be either a group name or a numeric group-ID (GID) prefixed with the # character (e.g., #0 for GID 0). When running a command as a GID, many shells require that the # be escaped with a backslash (\). If no -u option is specified, the command will be run as the invoking user. In either case, the primary group will be set to group. The sudoers policy permits any of the target user's groups to be specified via the -g option as long as the -P option is not in use. -H, --set-home Request that the security policy set the HOME environment variable to the home directory specified by the target user's password database entry. Depending on the policy, this may be the default behavior. -h, --help Display a short help message to the standard output and exit. -h host, --host=host Run the command on the specified host if the security policy plugin supports remote commands. The sudoers plugin does not currently support running remote commands. This may also be used in conjunction with the -l option to list a user's privileges for the remote host. -i, --login Run the shell specified by the target user's password database entry as a login shell. This means that login- specific resource files such as .profile, .bash_profile, or .login will be read by the shell. If a command is specified, it is passed to the shell as a simple command using the -c option. The command and any args are concatenated, separated by spaces, after escaping each character (including white space) with a backslash (\) except for alphanumerics, underscores, hyphens, and dollar signs. If no command is specified, an interactive shell is executed. attempts to change to that user's home directory before running the shell. The command is run with an environment similar to the one a user would receive at log in. Most shells behave differently when a command is specified as compared to an interactive session; consult the shell's manual for details. The Command environment section in the sudoers(5) manual documents how the -i option affects the environment in which a command is run when the sudoers policy is in use. -K, --remove-timestamp Similar to the -k option, except that it removes every cached credential for the user, regardless of the terminal or parent process ID. The next time is run, a password must be entered if the security policy requires authentication. It is not possible to use the -K option in conjunction with a command or other option. This option does not require a password. Not all security policies support credential caching. -k, --reset-timestamp When used without a command, invalidates the user's cached credentials for the current session. The next time is run in the session, a password must be entered if the security policy requires authentication. By default, the sudoers policy uses a separate record in the credential cache for each terminal (or parent process ID if no terminal is present). This prevents the -k option from interfering with commands run in a different terminal session. See the timestamp_type option in sudoers(5) for more information. This option does not require a password, and was added to allow a user to revoke permissions from a .logout file. When used in conjunction with a command or an option that may require a password, this option will cause to ignore the user's cached credentials. As a result, will prompt for a password (if one is required by the security policy) and will not update the user's cached credentials. Not all security policies support credential caching. -l, --list If no command is specified, list the privileges for the invoking user (or the user specified by the -U option) on the current host. A longer list format is used if this option is specified multiple times and the security policy supports a verbose output format. If a command is specified and is permitted by the security policy for the invoking user (or the, user specified by the -U option) on the current host, the fully-qualified path to the command is displayed along with any args. If -l is specified more than once (and the security policy supports it), the matching rule is displayed in a verbose format along with the command. If a command is specified but not allowed by the policy, will exit with a status value of 1. -N, --no-update Do not update the user's cached credentials, even if the user successfully authenticates. Unlike the -k flag, existing cached credentials are used if they are valid. To detect when the user's cached credentials are valid (or when no authentication is required), the following can be used: sudo -Nnv Not all security policies support credential caching. -n, --non-interactive Avoid prompting the user for input of any kind. If a password is required for the command to run, will display an error message and exit. -P, --preserve-groups Preserve the invoking user's group vector unaltered. By default, the sudoers policy will initialize the group vector to the list of groups the target user is a member of. The real and effective group-IDs, however, are still set to match the target user. -p prompt, --prompt=prompt Use a custom password prompt with optional escape sequences. The following percent (%) escape sequences are supported by the sudoers policy: %H expanded to the host name including the domain name (only if the machine's host name is fully qualified or the fqdn option is set in sudoers(5)) %h expanded to the local host name without the domain name %p expanded to the name of the user whose password is being requested (respects the rootpw, targetpw, and runaspw flags in sudoers(5)) %U expanded to the login name of the user the command will be run as (defaults to root unless the -u option is also specified) %u expanded to the invoking user's login name %% two consecutive % characters are collapsed into a single % character The custom prompt will override the default prompt specified by either the security policy or the SUDO_PROMPT environment variable. On systems that use PAM, the custom prompt will also override the prompt specified by a PAM module unless the passprompt_override flag is disabled in sudoers. -R directory, --chroot=directory Change to the specified root directory (see chroot(8)) before running the command. The security policy may return an error if the user does not have permission to specify the root directory. -S, --stdin Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. -s, --shell Run the shell specified by the SHELL environment variable if it is set or the shell specified by the invoking user's password database entry. If a command is specified, it is passed to the shell as a simple command using the -c option. The command and any args are concatenated, separated by spaces, after escaping each character (including white space) with a backslash (\) except for alphanumerics, underscores, hyphens, and dollar signs. If no command is specified, an interactive shell is executed. Most shells behave differently when a command is specified as compared to an interactive session; consult the shell's manual for details. -U user, --other-user=user Used in conjunction with the -l option to list the privileges for user instead of for the invoking user. The security policy may restrict listing other users' privileges. When using the sudoers policy, the -U option is restricted to the root user and users with either the list priviege for the specified user or the ability to run any command as root or user on the current host. -T timeout, --command-timeout=timeout Used to set a timeout for the command. If the timeout expires before the command has exited, the command will be terminated. The security policy may restrict the user's ability to set timeouts. The sudoers policy requires that user-specified timeouts be explicitly enabled. -u user, --user=user Run the command as a user other than the default target user (usually root). The user may be either a user name or a numeric user-ID (UID) prefixed with the # character (e.g., #0 for UID 0). When running commands as a UID, many shells require that the # be escaped with a backslash (\). Some security policies may restrict UIDs to those listed in the password database. The sudoers policy allows UIDs that are not in the password database as long as the targetpw option is not set. Other security policies may not support this. -V, --version Print the version string as well as the version string of any configured plugins. If the invoking user is already root, the -V option will display the options passed to configure when was built; plugins may display additional information such as default options. -v, --validate Update the user's cached credentials, authenticating the user if necessary. For the sudoers plugin, this extends the timeout for another 5 minutes by default, but does not run a command. Not all security policies support cached credentials. -- The -- is used to delimit the end of the options. Subsequent options are passed to the command. Options that take a value may only be specified once unless otherwise indicated in the description. This is to help guard against problems caused by poorly written scripts that invoke sudo with user-controlled input. Environment variables to be set for the command may also be passed as options to in the form VAR=value, for example LD_LIBRARY_PATH=/usr/local/pkg/lib. Environment variables may be subject to restrictions imposed by the security policy plugin. The sudoers policy subjects environment variables passed as options to the same restrictions as existing environment variables with one important difference. If the setenv option is set in sudoers, the command to be run has the SETENV tag set or the command matched is ALL, the user may set variables that would otherwise be forbidden. See sudoers(5) for more information. COMMAND EXECUTION top When executes a command, the security policy specifies the execution environment for the command. Typically, the real and effective user and group and IDs are set to match those of the target user, as specified in the password database, and the group vector is initialized based on the group database (unless the -P option was specified). The following parameters may be specified by security policy: real and effective user-ID real and effective group-ID supplementary group-IDs the environment list current working directory file creation mode mask (umask) scheduling priority (aka nice value) Process model There are two distinct ways can run a command. If an I/O logging plugin is configured to log terminal I/O, or if the security policy explicitly requests it, a new pseudo-terminal (pty) is allocated and fork(2) is used to create a second process, referred to as the monitor. The monitor creates a new terminal session with itself as the leader and the pty as its controlling terminal, calls fork(2) again, sets up the execution environment as described above, and then uses the execve(2) system call to run the command in the child process. The monitor exists to relay job control signals between the user's terminal and the pty the command is being run in. This makes it possible to suspend and resume the command normally. Without the monitor, the command would be in what POSIX terms an orphaned process group and it would not receive any job control signals from the kernel. When the command exits or is terminated by a signal, the monitor passes the command's exit status to the main process and exits. After receiving the command's exit status, the main process passes the command's exit status to the security policy's close function, as well as the close function of any configured audit plugin, and exits. This mode is the default for sudo versions 1.9.14 and above when using the sudoers policy. If no pty is used, calls fork(2), sets up the execution environment as described above, and uses the execve(2) system call to run the command in the child process. The main process waits until the command has completed, then passes the command's exit status to the security policy's close function, as well as the close function of any configured audit plugins, and exits. As a special case, if the policy plugin does not define a close function, will execute the command directly instead of calling fork(2) first. The sudoers policy plugin will only define a close function when I/O logging is enabled, a pty is required, an SELinux role is specified, the command has an associated timeout, or the pam_session or pam_setcred options are enabled. Both pam_session and pam_setcred are enabled by default on systems using PAM. This mode is the default for sudo versions prior to 1.9.14 when using the sudoers policy. On systems that use PAM, the security policy's close function is responsible for closing the PAM session. It may also log the command's exit status. Signal handling When the command is run as a child of the process, will relay signals it receives to the command. The SIGINT and SIGQUIT signals are only relayed when the command is being run in a new pty or when the signal was sent by a user process, not the kernel. This prevents the command from receiving SIGINT twice each time the user enters control-C. Some signals, such as SIGSTOP and SIGKILL, cannot be caught and thus will not be relayed to the command. As a general rule, SIGTSTP should be used instead of SIGSTOP when you wish to suspend a command being run by . As a special case, will not relay signals that were sent by the command it is running. This prevents the command from accidentally killing itself. On some systems, the reboot(8) utility sends SIGTERM to all non-system processes other than itself before rebooting the system. This prevents from relaying the SIGTERM signal it received back to reboot(8), which might then exit before the system was actually rebooted, leaving it in a half-dead state similar to single user mode. Note, however, that this check only applies to the command run by and not any other processes that the command may create. As a result, running a script that calls reboot(8) or shutdown(8) via may cause the system to end up in this undefined state unless the reboot(8) or shutdown(8) are run using the exec() family of functions instead of system() (which interposes a shell between the command and the calling process). Plugins Plugins may be specified via Plugin directives in the sudo.conf(5) file. They may be loaded as dynamic shared objects (on systems that support them), or compiled directly into the binary. If no sudo.conf(5) file is present, or if it doesn't contain any Plugin lines, will use sudoers(5) for the policy, auditing, and I/O logging plugins. See the sudo.conf(5) manual for details of the /etc/sudo.conf file and the sudo_plugin(5) manual for more information about the plugin architecture. EXIT VALUE top Upon successful execution of a command, the exit status from will be the exit status of the program that was executed. If the command terminated due to receipt of a signal, will send itself the same signal that terminated the command. If the -l option was specified without a command, will exit with a value of 0 if the user is allowed to run and they authenticated successfully (as required by the security policy). If a command is specified with the -l option, the exit value will only be 0 if the command is permitted by the security policy, otherwise it will be 1. If there is an authentication failure, a configuration/permission problem, or if the given command cannot be executed, exits with a value of 1. In the latter case, the error string is printed to the standard error. If cannot stat(2) one or more entries in the user's PATH, an error is printed to the standard error. (If the directory does not exist or if it is not really a directory, the entry is ignored and no error is printed.) This should not happen under normal circumstances. The most common reason for stat(2) to return permission denied is if you are running an automounter and one of the directories in your PATH is on a machine that is currently unreachable. SECURITY NOTES top tries to be safe when executing external commands. To prevent command spoofing, checks "." and "" (both denoting current directory) last when searching for a command in the user's PATH (if one or both are in the PATH). Depending on the security policy, the user's PATH environment variable may be modified, replaced, or passed unchanged to the program that executes. Users should never be granted privileges to execute files that are writable by the user or that reside in a directory that is writable by the user. If the user can modify or replace the command there is no way to limit what additional commands they can run. By default, will only log the command it explicitly runs. If a user runs a command such as sudo su or sudo sh, subsequent commands run from that shell are not subject to sudo's security policy. The same is true for commands that offer shell escapes (including most editors). If I/O logging is enabled, subsequent commands will have their input and/or output logged, but there will not be traditional logs for those commands. Because of this, care must be taken when giving users access to commands via to verify that the command does not inadvertently give the user an effective root shell. For information on ways to address this, see the Preventing shell escapes section in sudoers(5). To prevent the disclosure of potentially sensitive information, disables core dumps by default while it is executing (they are re-enabled for the command that is run). This historical practice dates from a time when most operating systems allowed set-user-ID processes to dump core by default. To aid in debugging crashes, you may wish to re-enable core dumps by setting disable_coredump to false in the sudo.conf(5) file as follows: Set disable_coredump false See the sudo.conf(5) manual for more information. ENVIRONMENT top utilizes the following environment variables. The security policy has control over the actual content of the command's environment. EDITOR Default editor to use in -e (sudoedit) mode if neither SUDO_EDITOR nor VISUAL is set. MAIL Set to the mail spool of the target user when the -i option is specified, or when env_reset is enabled in sudoers (unless MAIL is present in the env_keep list). HOME Set to the home directory of the target user when the -i or -H options are specified, when the -s option is specified and set_home is set in sudoers, when always_set_home is enabled in sudoers, or when env_reset is enabled in sudoers and HOME is not present in the env_keep list. LOGNAME Set to the login name of the target user when the -i option is specified, when the set_logname option is enabled in sudoers, or when the env_reset option is enabled in sudoers (unless LOGNAME is present in the env_keep list). PATH May be overridden by the security policy. SHELL Used to determine shell to run with -s option. SUDO_ASKPASS Specifies the path to a helper program used to read the password if no terminal is available or if the -A option is specified. SUDO_COMMAND Set to the command run by sudo, including any args. The args are truncated at 4096 characters to prevent a potential execution error. SUDO_EDITOR Default editor to use in -e (sudoedit) mode. SUDO_GID Set to the group-ID of the user who invoked sudo. SUDO_PROMPT Used as the default password prompt unless the -p option was specified. SUDO_PS1 If set, PS1 will be set to its value for the program being run. SUDO_UID Set to the user-ID of the user who invoked sudo. SUDO_USER Set to the login name of the user who invoked sudo. USER Set to the same value as LOGNAME, described above. VISUAL Default editor to use in -e (sudoedit) mode if SUDO_EDITOR is not set. FILES top /etc/sudo.conf front-end configuration EXAMPLES top The following examples assume a properly configured security policy. To get a file listing of an unreadable directory: $ sudo ls /usr/local/protected To list the home directory of user yaz on a machine where the file system holding ~yaz is not exported as root: $ sudo -u yaz ls ~yaz To edit the index.html file as user www: $ sudoedit -u www ~www/htdocs/index.html To view system logs only accessible to root and users in the adm group: $ sudo -g adm more /var/log/syslog To run an editor as jim with a different primary group: $ sudoedit -u jim -g audio ~jim/sound.txt To shut down a machine: $ sudo shutdown -r +15 "quick reboot" To make a usage listing of the directories in the /home partition. The commands are run in a sub-shell to allow the cd command and file redirection to work. $ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE" DIAGNOSTICS top Error messages produced by include: editing files in a writable directory is not permitted By default, sudoedit does not permit editing a file when any of the parent directories are writable by the invoking user. This avoids a race condition that could allow the user to overwrite an arbitrary file. See the sudoedit_checkdir option in sudoers(5) for more information. editing symbolic links is not permitted By default, sudoedit does not follow symbolic links when opening files. See the sudoedit_follow option in sudoers(5) for more information. effective uid is not 0, is sudo installed setuid root? was not run with root privileges. The binary must be owned by the root user and have the set-user-ID bit set. Also, it must not be located on a file system mounted with the nosuid option or on an NFS file system that maps uid 0 to an unprivileged uid. effective uid is not 0, is sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges? was not run with root privileges. The binary has the proper owner and permissions but it still did not run with root privileges. The most common reason for this is that the file system the binary is located on is mounted with the nosuid option or it is an NFS file system that maps uid 0 to an unprivileged uid. fatal error, unable to load plugins An error occurred while loading or initializing the plugins specified in sudo.conf(5). invalid environment variable name One or more environment variable names specified via the -E option contained an equal sign (=). The arguments to the -E option should be environment variable names without an associated value. no password was provided When tried to read the password, it did not receive any characters. This may happen if no terminal is available (or the -S option is specified) and the standard input has been redirected from /dev/null. a terminal is required to read the password needs to read the password but there is no mechanism available for it to do so. A terminal is not present to read the password from, has not been configured to read from the standard input, the -S option was not used, and no askpass helper has been specified either via the sudo.conf(5) file or the SUDO_ASKPASS environment variable. no writable temporary directory found sudoedit was unable to find a usable temporary directory in which to store its intermediate files. The no new privileges flag is set, which prevents sudo from running as root. was run by a process that has the Linux no new privileges flag is set. This causes the set-user-ID bit to be ignored when running an executable, which will prevent from functioning. The most likely cause for this is running within a container that sets this flag. Check the documentation to see if it is possible to configure the container such that the flag is not set. sudo must be owned by uid 0 and have the setuid bit set was not run with root privileges. The binary does not have the correct owner or permissions. It must be owned by the root user and have the set-user-ID bit set. sudoedit is not supported on this platform It is only possible to run sudoedit on systems that support setting the effective user-ID. timed out reading password The user did not enter a password before the password timeout (5 minutes by default) expired. you do not exist in the passwd database Your user-ID does not appear in the system passwd database. you may not specify environment variables in edit mode It is only possible to specify environment variables when running a command. When editing a file, the editor is run with the user's environment unmodified. SEE ALSO top su(1), stat(2), login_cap(3), passwd(5), sudo.conf(5), sudo_plugin(5), sudoers(5), sudoers_timestamp(5), sudoreplay(8), visudo(8) HISTORY top See the HISTORY.md file in the distribution (https://www.sudo.ws/about/history/) for a brief history of sudo. AUTHORS top Many people have worked on over the years; this version consists of code written primarily by: Todd C. Miller See the CONTRIBUTORS.md file in the distribution (https://www.sudo.ws/about/contributors/) for an exhaustive list of people who have contributed to . CAVEATS top There is no easy way to prevent a user from gaining a root shell if that user is allowed to run arbitrary commands via . Also, many programs (such as editors) allow the user to run commands via shell escapes, thus avoiding sudo's checks. However, on most systems it is possible to prevent shell escapes with the sudoers(5) plugin's noexec functionality. It is not meaningful to run the cd command directly via sudo, e.g., $ sudo cd /usr/local/protected since when the command exits the parent process (your shell) will still be the same. The -D option can be used to run a command in a specific directory. Running shell scripts via can expose the same kernel bugs that make set-user-ID shell scripts unsafe on some operating systems (if your OS has a /dev/fd/ directory, set-user-ID shell scripts are generally safe). BUGS top If you believe you have found a bug in , you can submit a bug report at https://bugzilla.sudo.ws/ SUPPORT top Limited free support is available via the sudo-users mailing list, see https://www.sudo.ws/mailman/listinfo/sudo-users to subscribe or search the archives. DISCLAIMER top is provided AS IS and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. See the LICENSE.md file distributed with or https://www.sudo.ws/about/license/ for complete details. COLOPHON top This page is part of the sudo (execute a command as another user) project. Information about the project can be found at https://www.sudo.ws/. If you have a bug report for this manual page, see https://bugzilla.sudo.ws/. This page was obtained from the project's upstream Git repository https://github.com/sudo-project/sudo on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-12-21.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org Sudo 1.9.15p4 August 9, 2023 SUDO(8) Pages that refer to this page: homectl(1), journalctl(1), localectl(1), loginctl(1), machinectl(1), portablectl(1), setpriv(1), systemctl(1), systemd(1), systemd-analyze(1), systemd-ask-password(1), systemd-inhibit(1), systemd-nspawn(1), systemd-vmspawn(1), timedatectl(1), uid0(1), userdbctl(1), nsswitch.conf(5), credentials(7), systemd-tmpfiles(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: Compress and display the original filename of every file on the system that is greater than 100000 bytes and ends in ".log" Bash Command:<START>sudo find / -xdev -type f -size +100000 -name "*.log" -exec gzip {} \; -exec echo {} \;<END>
Compress every file in the current directory tree that matches "*cache.html" and keep the original file
find . -type f -name "*cache.html" -exec gzip -k {} \;
['find']
Output a Bash command to accomplish the following task. Task: Compress every file in the current directory tree that matches "*cache.html" and keep the original file Bash Command:<START>find . -type f -name "*cache.html" -exec gzip -k {} \;<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: Compress every file in the current directory tree that matches "*cache.html" and keep the original file Bash Command:<START>find . -type f -name "*cache.html" -exec gzip -k {} \;<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: Compress every file in the current directory tree that matches "*cache.html" and keep the original file Bash Command:<START>find . -type f -name "*cache.html" -exec gzip -k {} \;<END>
Compress every file in the current directory tree with gzip and keep file extensions the same
find folder -type f -exec gzip -9 {} \; -exec mv {}.gz {} \;
['find', 'mv']
Output a Bash command to accomplish the following task. Task: Compress every file in the current directory tree with gzip and keep file extensions the same Bash Command:<START>find folder -type f -exec gzip -9 {} \; -exec mv {}.gz {} \;<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 # mv\n\n> Move or rename files and directories.\n> More information: <https://www.gnu.org/software/coreutils/mv>.\n\n- Rename a file or directory when the target is not an existing directory:\n\n`mv {{path/to/source}} {{path/to/target}}`\n\n- Move a file or directory into an existing directory:\n\n`mv {{path/to/source}} {{path/to/existing_directory}}`\n\n- Move multiple files into an existing directory, keeping the filenames unchanged:\n\n`mv {{path/to/source1 path/to/source2 ...}} {{path/to/existing_directory}}`\n\n- Do not prompt for confirmation before overwriting existing files:\n\n`mv -f {{path/to/source}} {{path/to/target}}`\n\n- Prompt for confirmation before overwriting existing files, regardless of file permissions:\n\n`mv -i {{path/to/source}} {{path/to/target}}`\n\n- Do not overwrite existing files at the target:\n\n`mv -n {{path/to/source}} {{path/to/target}}`\n\n- Move files in verbose mode, showing files after they are moved:\n\n`mv -v {{path/to/source}} {{path/to/target}}`\n Task: Compress every file in the current directory tree with gzip and keep file extensions the same Bash Command:<START>find folder -type f -exec gzip -9 {} \; -exec mv {}.gz {} \;<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. mv(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training mv(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON MV(1) User Commands MV(1) NAME top mv - move (rename) files SYNOPSIS top mv [OPTION]... [-T] SOURCE DEST mv [OPTION]... SOURCE... DIRECTORY mv [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --debug explain how a file is copied. Implies -v -f, --force do not prompt before overwriting -i, --interactive prompt before overwrite -n, --no-clobber do not overwrite an existing file If you specify more than one of -i, -f, -n, only the final one takes effect. --no-copy do not copy if renaming fails --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -Z, --context set SELinux security context of destination file to default type --help display this help and exit --version output version information and exit UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups AUTHOR top Written by Mike Parker, 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 rename(2) Full documentation <https://www.gnu.org/software/coreutils/mv> or available locally via: info '(coreutils) mv 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 MV(1) Pages that refer to this page: rename(1), sshfs(1), rename(2), inotify(7), symlink(7), 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: Compress every file in the current directory tree with gzip and keep file extensions the same Bash Command:<START>find folder -type f -exec gzip -9 {} \; -exec mv {}.gz {} \;<END>
Compress files excluding *.Z files
find . \! -name "*.Z" -exec compress -f {} \;
['find', 'compress']
Output a Bash command to accomplish the following task. Task: Compress files excluding *.Z files Bash Command:<START>find . \! -name "*.Z" -exec compress -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 # compress\n\n> Compress files using the Unix `compress` command.\n> More information: <https://manned.org/compress.1>.\n\n- Compress specific files:\n\n`compress {{path/to/file1 path/to/file2 ...}}`\n\n- Compress specific files, ignore non-existent ones:\n\n`compress -f {{path/to/file1 path/to/file2 ...}}`\n\n- Specify the maximum compression bits (9-16 bits):\n\n`compress -b {{bits}}`\n\n- Write to `stdout` (no files are changed):\n\n`compress -c {{path/to/file}}`\n\n- Decompress files (functions like `uncompress`):\n\n`compress -d {{path/to/file}}`\n\n- Display compression percentage:\n\n`compress -v {{path/to/file}}`\n Task: Compress files excluding *.Z files Bash Command:<START>find . \! -name "*.Z" -exec compress -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. compress(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training compress(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 COMPRESS(1P) POSIX Programmer's Manual COMPRESS(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 compress compress data SYNOPSIS top compress [-fv] [-b bits] [file...] compress [-cfv] [-b bits] [file] DESCRIPTION top The compress utility shall attempt to reduce the size of the named files by using adaptive Lempel-Ziv coding algorithm. Note: Lempel-Ziv is US Patent 4464650, issued to William Eastman, Abraham Lempel, Jacob Ziv, Martin Cohn on August 7th, 1984, and assigned to Sperry Corporation. Lempel-Ziv-Welch compression is covered by US Patent 4558302, issued to Terry A. Welch on December 10th, 1985, and assigned to Sperry Corporation. On systems not supporting adaptive Lempel-Ziv coding algorithm, the input files shall not be changed and an error value greater than two shall be returned. Except when the output is to the standard output, each file shall be replaced by one with the extension .Z. If the invoking process has appropriate privileges, the ownership, modes, access time, and modification time of the original file are preserved. If appending the .Z to the filename would make the name exceed {NAME_MAX} bytes, the command shall fail. If no files are specified, the standard input shall be compressed to the standard output. OPTIONS top The compress utility shall conform to the Base Definitions volume of POSIX.12017, Section 12.2, Utility Syntax Guidelines. The following options shall be supported: -b bits Specify the maximum number of bits to use in a code. For a conforming application, the bits argument shall be: 9 <= bits <= 14 The implementation may allow bits values of greater than 14. The default is 14, 15, or 16. -c Cause compress to write to the standard output; the input file is not changed, and no .Z files are created. -f Force compression of file, even if it does not actually reduce the size of the file, or if the corresponding file.Z file already exists. If the -f option is not given, and the process is not running in the background, the user is prompted as to whether an existing file.Z file should be overwritten. If the response is affirmative, the existing file will be overwritten. -v Write the percentage reduction of each file to standard error. OPERANDS top The following operand shall be supported: file A pathname of a file to be compressed. STDIN top The standard input shall be used only if no file operands are specified, or if a file operand is '-'. INPUT FILES top If file operands are specified, the input files contain the data to be compressed. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of compress: 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 used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category. 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), the behavior of character classes used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category. LC_MESSAGES Determine the locale used to process affirmative responses, and the locale used to affect the format and contents of diagnostic messages, prompts, and the output from the -v option written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. ASYNCHRONOUS EVENTS top Default. STDOUT top If no file operands are specified, or if a file operand is '-', or if the -c option is specified, the standard output contains the compressed output. STDERR top The standard error shall be used only for diagnostic and prompt messages and the output from -v. OUTPUT FILES top The output files shall contain the compressed output. The format of compressed files is unspecified and interchange of such files between implementations (including access via unspecified file sharing mechanisms) is not required by POSIX.12008. EXTENDED DESCRIPTION top None. EXIT STATUS top The following exit values shall be returned: 0 Successful completion. 1 An error occurred. 2 One or more files were not compressed because they would have increased in size (and the -f option was not specified). >2 An error occurred. CONSEQUENCES OF ERRORS top The input file shall remain unmodified. The following sections are informative. APPLICATION USAGE top The amount of compression obtained depends on the size of the input, the number of bits per code, and the distribution of common substrings. Typically, text such as source code or English is reduced by 5060%. Compression is generally much better than that achieved by Huffman coding or adaptive Huffman coding (compact), and takes less time to compute. Although compress strictly follows the default actions upon receipt of a signal or when an error occurs, some unexpected results may occur. In some implementations it is likely that a partially compressed file is left in place, alongside its uncompressed input file. Since the general operation of compress is to delete the uncompressed file only after the .Z file has been successfully filled, an application should always carefully check the exit status of compress before arbitrarily deleting files that have like-named neighbors with .Z suffixes. The limit of 14 on the bits option-argument is to achieve portability to all systems (within the restrictions imposed by the lack of an explicit published file format). Some implementations based on 16-bit architectures cannot support 15 or 16-bit uncompression. EXAMPLES top None. RATIONALE top None. FUTURE DIRECTIONS top None. SEE ALSO top uncompress(1p), zcat(1p) The Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines 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 COMPRESS(1P) Pages that refer to this page: uncompress(1p), zcat(1p) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Compress files excluding *.Z files Bash Command:<START>find . \! -name "*.Z" -exec compress -f {} \;<END>
Compress from standard input and print the byte count preceded with 'gzip.'
echo gzip. $( gzip | wc -c )
['wc', 'echo']
Output a Bash command to accomplish the following task. Task: Compress from standard input and print the byte count preceded with 'gzip.' Bash Command:<START>echo gzip. $( gzip | wc -c )<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # wc\n\n> Count lines, words, and bytes.\n> More information: <https://www.gnu.org/software/coreutils/wc>.\n\n- Count all lines in a file:\n\n`wc --lines {{path/to/file}}`\n\n- Count all words in a file:\n\n`wc --words {{path/to/file}}`\n\n- Count all bytes in a file:\n\n`wc --bytes {{path/to/file}}`\n\n- Count all characters in a file (taking multi-byte characters into account):\n\n`wc --chars {{path/to/file}}`\n\n- Count all lines, words and bytes from `stdin`:\n\n`{{find .}} | wc`\n\n- Count the length of the longest line in number of characters:\n\n`wc --max-line-length {{path/to/file}}`\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: Compress from standard input and print the byte count preceded with 'gzip.' Bash Command:<START>echo gzip. $( gzip | wc -c )<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: wc(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training wc(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON WC(1) User Commands WC(1) NAME top wc - print newline, word, and byte counts for each file SYNOPSIS top wc [OPTION]... [FILE]... wc [OPTION]... --files0-from=F DESCRIPTION top Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified. A word is a non-zero-length sequence of printable characters delimited by white space. With no FILE, or when FILE is -, read standard input. The options below may be used to select which counts are printed, always in the following order: newline, word, character, byte, maximum line length. -c, --bytes print the byte counts -m, --chars print the character counts -l, --lines print the newline counts --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 -L, --max-line-length print the maximum display width -w, --words print the word counts --total=WHEN when to print a line with total counts; WHEN can be: auto, always, only, never --help display this help and exit --version output version information and exit AUTHOR top Written by Paul Rubin 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/wc> or available locally via: info '(coreutils) wc 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 WC(1) Pages that refer to this page: bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. echo(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training echo(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON ECHO(1) User Commands ECHO(1) NAME top echo - display a line of text SYNOPSIS top echo [SHORT-OPTION]... [STRING]... echo LONG-OPTION DESCRIPTION top Echo the STRING(s) to standard output. -n do not output the trailing newline -e enable interpretation of backslash escapes -E disable interpretation of backslash escapes (default) --help display this help and exit --version output version information and exit If -e is in effect, the following sequences are recognized: \\ backslash \a alert (BEL) \b backspace \c produce no further output \e escape \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \0NNN byte with octal value NNN (1 to 3 digits) \xHH byte with hexadecimal value HH (1 to 2 digits) NOTE: your shell may have its own version of echo, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. NOTE: printf(1) is a preferred alternative, which does not have issues outputting option-like strings. AUTHOR top Written by Brian Fox and Chet Ramey. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top printf(1) Full documentation <https://www.gnu.org/software/coreutils/echo> or available locally via: info '(coreutils) echo invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 ECHO(1) Pages that refer to this page: ldapcompare(1), systemd-ask-password(1), systemd-run(1), cpuset(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Compress from standard input and print the byte count preceded with 'gzip.' Bash Command:<START>echo gzip. $( gzip | wc -c )<END>
Compress the file 'file' with 'bzip2' and append all output to the file 'logfile' and stdout
bzip2 file | tee -a logfile
['tee', 'file']
Output a Bash command to accomplish the following task. Task: Compress the file 'file' with 'bzip2' and append all output to the file 'logfile' and stdout Bash Command:<START>bzip2 file | tee -a logfile<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 # file\n\n> Determine file type.\n> More information: <https://manned.org/file>.\n\n- Give a description of the type of the specified file. Works fine for files with no file extension:\n\n`file {{path/to/file}}`\n\n- Look inside a zipped file and determine the file type(s) inside:\n\n`file -z {{foo.zip}}`\n\n- Allow file to work with special or device files:\n\n`file -s {{path/to/file}}`\n\n- Don't stop at first file type match; keep going until the end of the file:\n\n`file -k {{path/to/file}}`\n\n- Determine the MIME encoding type of a file:\n\n`file -i {{path/to/file}}`\n Task: Compress the file 'file' with 'bzip2' and append all output to the file 'logfile' and stdout Bash Command:<START>bzip2 file | tee -a logfile<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. file(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training file(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | ENVIRONMENT | FILES | EXIT STATUS | EXAMPLES | SEE ALSO | STANDARDS CONFORMANCE | SECURITY | MAGIC DIRECTORY | HISTORY | LEGAL NOTICE | BUGS | TODO | AVAILABILITY | COLOPHON FILE(1) General Commands Manual FILE(1) NAME top file determine file type SYNOPSIS top [-bcdEhiklLNnprsSvzZ0] [--apple] [--exclude-quiet] [--extension] [--mime-encoding] [--mime-type] [-e testname] [-F separator] [-f namefile] [-m magicfiles] [-P name=value] file ... -C [-m magicfiles] [--help] DESCRIPTION top This manual page documents version 5.45 of the command. tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic tests, and language tests. The first test that succeeds causes the file type to be printed. The type printed will usually contain one of the words text (the file contains only printing characters and a few common control characters and is probably safe to read on an ASCII terminal), executable (the file contains the result of compiling a program in a form understandable to some UNIX kernel or another), or data meaning anything else (data is usually binary or non- printable). Exceptions are well-known file formats (core files, tar archives) that are known to contain binary data. When modifying magic files or the program itself, make sure to preserve these keywords. Users depend on knowing that all the readable files in a directory have the word text printed. Don't do as Berkeley did and change shell commands text to shell script. The filesystem tests are based on examining the return from a stat(2) system call. The program checks to see if the file is empty, or if it's some sort of special file. Any known file types appropriate to the system you are running on (sockets, symbolic links, or named pipes (FIFOs) on those systems that implement them) are intuited if they are defined in the system header file <sys/stat.h>. The magic tests are used to check for files with data in particular fixed formats. The canonical example of this is a binary executable (compiled program) a.out file, whose format is defined in <elf.h>, <a.out.h> and possibly <exec.h> in the standard include directory. These files have a magic number stored in a particular place near the beginning of the file that tells the UNIX operating system that the file is a binary executable, and which of several types thereof. The concept of a magic number has been applied by extension to data files. Any file with some invariant identifier at a small fixed offset into the file can usually be described in this way. The information identifying these files is read from the compiled magic file /usr/local/share/misc/magic.mgc, or the files in the directory /usr/local/share/misc/magic if the compiled file does not exist. In addition, if $HOME/.magic.mgc or $HOME/.magic exists, it will be used in preference to the system magic files. If a file does not match any of the entries in the magic file, it is examined to see if it seems to be a text file. ASCII, ISO-8859-x, non-ISO 8-bit extended-ASCII character sets (such as those used on Macintosh and IBM PC systems), UTF-8-encoded Unicode, UTF-16-encoded Unicode, and EBCDIC character sets can be distinguished by the different ranges and sequences of bytes that constitute printable text in each set. If a file passes any of these tests, its character set is reported. ASCII, ISO-8859-x, UTF-8, and extended-ASCII files are identified as text because they will be mostly readable on nearly any terminal; UTF-16 and EBCDIC are only character data because, while they contain text, it is text that will require translation before it can be read. In addition, will attempt to determine other characteristics of text-type files. If the lines of a file are terminated by CR, CRLF, or NEL, instead of the Unix-standard LF, this will be reported. Files that contain embedded escape sequences or overstriking will also be identified. Once has determined the character set used in a text-type file, it will attempt to determine in what language the file is written. The language tests look for particular strings (cf. <names.h>) that can appear anywhere in the first few blocks of a file. For example, the keyword .br indicates that the file is most likely a troff(1) input file, just as the keyword struct indicates a C program. These tests are less reliable than the previous two groups, so they are performed last. The language test routines also test for some miscellany (such as tar(1) archives, JSON files). Any file that cannot be identified as having been written in any of the character sets listed above is simply said to be data. OPTIONS top --apple Causes the command to output the file type and creator code as used by older MacOS versions. The code consists of eight letters, the first describing the file type, the latter the creator. This option works properly only for file formats that have the apple-style output defined. -b, --brief Do not prepend filenames to output lines (brief mode). -C, --compile Write a magic.mgc output file that contains a pre-parsed version of the magic file or directory. -c, --checking-printout Cause a checking printout of the parsed form of the magic file. This is usually used in conjunction with the -m option to debug a new magic file before installing it. -d Prints internal debugging information to stderr. -E On filesystem errors (file not found etc), instead of handling the error as regular output as POSIX mandates and keep going, issue an error message and exit. -e, --exclude testname Exclude the test named in testname from the list of tests made to determine the file type. Valid test names are: apptype EMX application type (only on EMX). ascii Various types of text files (this test will try to guess the text encoding, irrespective of the setting of the encoding option). encoding Different text encodings for soft magic tests. tokens Ignored for backwards compatibility. cdf Prints details of Compound Document Files. compress Checks for, and looks inside, compressed files. csv Checks Comma Separated Value files. elf Prints ELF file details, provided soft magic tests are enabled and the elf magic is found. json Examines JSON (RFC-7159) files by parsing them for compliance. soft Consults magic files. simh Examines SIMH tape files. tar Examines tar files by verifying the checksum of the 512 byte tar header. Excluding this test can provide more detailed content description by using the soft magic method. text A synonym for ascii. --exclude-quiet Like --exclude but ignore tests that does not know about. This is intended for compatibility with older versions of . --extension Print a slash-separated list of valid extensions for the file type found. -F, --separator separator Use the specified string as the separator between the filename and the file result returned. Defaults to :. -f, --files-from namefile Read the names of the files to be examined from namefile (one per line) before the argument list. Either namefile or at least one filename argument must be present; to test the standard input, use - as a filename argument. Please note that namefile is unwrapped and the enclosed filenames are processed when this option is encountered and before any further options processing is done. This allows one to process multiple lists of files with different command line arguments on the same invocation. Thus if you want to set the delimiter, you need to do it before you specify the list of files, like: -F @ -f namefile, instead of: -f namefile -F @. -h, --no-dereference This option causes symlinks not to be followed (on systems that support symbolic links). This is the default if the environment variable POSIXLY_CORRECT is not defined. -i, --mime Causes the command to output mime type strings rather than the more traditional human readable ones. Thus it may say text/plain; charset=us-ascii rather than ASCII text. --mime-type, --mime-encoding Like -i, but print only the specified element(s). -k, --keep-going Don't stop at the first match, keep going. Subsequent matches will be have the string \012- prepended. (If you want a newline, see the -r option.) The magic pattern with the highest strength (see the -l option) comes first. -l, --list Shows a list of patterns and their strength sorted descending by magic(4) strength which is used for the matching (see also the -k option). -L, --dereference This option causes symlinks to be followed, as the like- named option in ls(1) (on systems that support symbolic links). This is the default if the environment variable POSIXLY_CORRECT is defined. -m, --magic-file magicfiles Specify an alternate list of files and directories containing magic. This can be a single item, or a colon- separated list. If a compiled magic file is found alongside a file or directory, it will be used instead. -N, --no-pad Don't pad filenames so that they align in the output. -n, --no-buffer Force stdout to be flushed after checking each file. This is only useful if checking a list of files. It is intended to be used by programs that want filetype output from a pipe. -p, --preserve-date On systems that support utime(3) or utimes(2), attempt to preserve the access time of files analyzed, to pretend that never read them. -P, --parameter name=value Set various parameter limits. Name Default Explanation bytes 1M max number of bytes to read from file elf_notes 256 max ELF notes processed elf_phnum 2K max ELF program sections processed elf_shnum 32K max ELF sections processed elf_shsize 128MB max ELF section size processed encoding 65K max number of bytes to determine encoding indir 50 recursion limit for indirect magic name 50 use count limit for name/use magic regex 8K length limit for regex searches -r, --raw Don't translate unprintable characters to \ooo. Normally translates unprintable characters to their octal representation. -s, --special-files Normally, only attempts to read and determine the type of argument files which stat(2) reports are ordinary files. This prevents problems, because reading special files may have peculiar consequences. Specifying the -s option causes to also read argument files which are block or character special files. This is useful for determining the filesystem types of the data in raw disk partitions, which are block special files. This option also causes to disregard the file size as reported by stat(2) since on some systems it reports a zero size for raw disk partitions. -S, --no-sandbox On systems where libseccomp (https://github.com/seccomp/libseccomp ) is available, the -S option disables sandboxing which is enabled by default. This option is needed for to execute external decompressing programs, i.e. when the -z option is specified and the built-in decompressors are not available. On systems where sandboxing is not available, this option has no effect. -v, --version Print the version of the program and exit. -z, --uncompress Try to look inside compressed files. -Z, --uncompress-noreport Try to look inside compressed files, but report information about the contents only not the compression. -0, --print0 Output a null character \0 after the end of the filename. Nice to cut(1) the output. This does not affect the separator, which is still printed. If this option is repeated more than once, then prints just the filename followed by a NUL followed by the description (or ERROR: text) followed by a second NUL for each entry. --help Print a help message and exit. ENVIRONMENT top The environment variable MAGIC can be used to set the default magic file name. If that variable is set, then will not attempt to open $HOME/.magic. adds .mgc to the value of this variable as appropriate. The environment variable POSIXLY_CORRECT controls (on systems that support symbolic links), whether will attempt to follow symlinks or not. If set, then follows symlink, otherwise it does not. This is also controlled by the -L and -h options. FILES top /usr/local/share/misc/magic.mgc Default compiled list of magic. /usr/local/share/misc/magic Directory containing default magic files. EXIT STATUS top will exit with 0 if the operation was successful or >0 if an error was encountered. The following errors cause diagnostic messages, but don't affect the program exit code (as POSIX requires), unless -E is specified: A file cannot be found There is no permission to read a file The file type cannot be determined EXAMPLES top $ file file.c file /dev/{wd0a,hda} file.c: C program text file: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), stripped /dev/wd0a: block special (0/0) /dev/hda: block special (3/0) $ file -s /dev/wd0{b,d} /dev/wd0b: data /dev/wd0d: x86 boot sector $ file -s /dev/hda{,1,2,3,4,5,6,7,8,9,10} /dev/hda: x86 boot sector /dev/hda1: Linux/i386 ext2 filesystem /dev/hda2: x86 boot sector /dev/hda3: x86 boot sector, extended partition table /dev/hda4: Linux/i386 ext2 filesystem /dev/hda5: Linux/i386 swap file /dev/hda6: Linux/i386 swap file /dev/hda7: Linux/i386 swap file /dev/hda8: Linux/i386 swap file /dev/hda9: empty /dev/hda10: empty $ file -i file.c file /dev/{wd0a,hda} file.c: text/x-c file: application/x-executable /dev/hda: application/x-not-regular-file /dev/wd0a: application/x-not-regular-file SEE ALSO top hexdump(1), od(1), strings(1), magic(4) STANDARDS CONFORMANCE top This program is believed to exceed the System V Interface Definition of FILE(CMD), as near as one can determine from the vague language contained therein. Its behavior is mostly compatible with the System V program of the same name. This version knows more magic, however, so it will produce different (albeit more accurate) output in many cases. The one significant difference between this version and System V is that this version treats any white space as a delimiter, so that spaces in pattern strings must be escaped. For example, >10 string language impress (imPRESS data) in an existing magic file would have to be changed to >10 string language\ impress (imPRESS data) In addition, in this version, if a pattern string contains a backslash, it must be escaped. For example 0 string \begindata Andrew Toolkit document in an existing magic file would have to be changed to 0 string \\begindata Andrew Toolkit document SunOS releases 3.2 and later from Sun Microsystems include a command derived from the System V one, but with some extensions. This version differs from Sun's only in minor ways. It includes the extension of the & operator, used as, for example, >16 long&0x7fffffff >0 not stripped SECURITY top On systems where libseccomp (https://github.com/seccomp/libseccomp ) is available, is enforces limiting system calls to only the ones necessary for the operation of the program. This enforcement does not provide any security benefit when is asked to decompress input files running external programs with the -z option. To enable execution of external decompressors, one needs to disable sandboxing using the -S option. MAGIC DIRECTORY top The magic file entries have been collected from various sources, mainly USENET, and contributed by various authors. Christos Zoulas (address below) will collect additional or corrected magic file entries. A consolidation of magic file entries will be distributed periodically. The order of entries in the magic file is significant. Depending on what system you are using, the order that they are put together may be incorrect. If your old command uses a magic file, keep the old magic file around for comparison purposes (rename it to /usr/local/share/misc/magic.orig). HISTORY top There has been a command in every UNIX since at least Research Version 4 (man page dated November, 1973). The System V version introduced one significant major change: the external list of magic types. This slowed the program down slightly but made it a lot more flexible. This program, based on the System V version, was written by Ian Darwin ian@darwinsys.com without looking at anybody else's source code. John Gilmore revised the code extensively, making it better than the first version. Geoff Collyer found several inadequacies and provided some magic file entries. Contributions of the & operator by Rob McMahon, cudcv@warwick.ac.uk, 1989. Guy Harris, guy@netapp.com, made many changes from 1993 to the present. Primary development and maintenance from 1990 to the present by Christos Zoulas christos@astron.com. Altered by Chris Lowth chris@lowth.com, 2000: handle the -i option to output mime type strings, using an alternative magic file and internal logic. Altered by Eric Fischer enf@pobox.com, July, 2000, to identify character codes and attempt to identify the languages of non- ASCII files. Altered by Reuben Thomas rrt@sc3d.org, 2007-2011, to improve MIME support, merge MIME and non-MIME magic, support directories as well as files of magic, apply many bug fixes, update and fix a lot of magic, improve the build system, improve the documentation, and rewrite the Python bindings in pure Python. The list of contributors to the magic directory (magic files) is too long to include here. You know who you are; thank you. Many contributors are listed in the source files. LEGAL NOTICE top Copyright (c) Ian F. Darwin, Toronto, Canada, 1986-1999. Covered by the standard Berkeley Software Distribution copyright; see the file COPYING in the source distribution. The files tar.h and is_tar.c were written by John Gilmore from his public-domain tar(1) program, and are not covered by the above license. BUGS top Please report bugs and send patches to the bug tracker at https://bugs.astron.com/ or the mailing list at file@astron.com (visit https://mailman.astron.com/mailman/listinfo/file first to subscribe). TODO top Fix output so that tests for MIME and APPLE flags are not needed all over the place, and actual output is only done in one place. This needs a design. Suggestion: push possible outputs on to a list, then pick the last-pushed (most specific, one hopes) value at the end, or use a default if the list is empty. This should not slow down evaluation. The handling of MAGIC_CONTINUE and printing \012- between entries is clumsy and complicated; refactor and centralize. Some of the encoding logic is hard-coded in encoding.c and can be moved to the magic files if we had a !:charset annotation. Continue to squash all magic bugs. See Debian BTS for a good source. Store arbitrarily long strings, for example for %s patterns, so that they can be printed out. Fixes Debian bug #271672. This can be done by allocating strings in a string pool, storing the string pool at the end of the magic file and converting all the string pointers to relative offsets from the string pool. Add syntax for relative offsets after current level (Debian bug #466037). Make file -ki work, i.e. give multiple MIME types. Add a zip library so we can peek inside Office2007 documents to print more details about their contents. Add an option to print URLs for the sources of the file descriptions. Combine script searches and add a way to map executable names to MIME types (e.g. have a magic value for !:mime which causes the resulting string to be looked up in a table). This would avoid adding the same magic repeatedly for each new hash-bang interpreter. When a file descriptor is available, we can skip and adjust the buffer instead of the hacky buffer management we do now. Fix name and use to check for consistency at compile time (duplicate name, use pointing to undefined name ). Make name / use more efficient by keeping a sorted list of names. Special-case ^ to flip endianness in the parser so that it does not have to be escaped, and document it. If the offsets specified internally in the file exceed the buffer size ( HOWMANY variable in file.h), then we don't seek to that offset, but we give up. It would be better if buffer managements was done when the file descriptor is available so we can seek around the file. One must be careful though because this has performance and thus security considerations, because one can slow down things by repeatedly seeking. There is support now for keeping separate buffers and having offsets from the end of the file, but the internal buffer management still needs an overhaul. AVAILABILITY top You can obtain the original author's latest version by anonymous FTP on ftp.astron.com in the directory /pub/file/file-X.YZ.tar.gz. COLOPHON top This page is part of the file (a file type guesser) project. Information about the project can be found at http://www.darwinsys.com/file/. If you have a bug report for this manual page, see http://bugs.gw.com/my_view_page.php. This page was obtained from the project's upstream Git read-only mirror of the CVS repository https://github.com/glensc/file on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-12-21.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU May 21, 2023 FILE(1) Pages that refer to this page: dh_installmanpages(1), dh_strip(1), ippeveprinter(1), pmcd(1), scr_dump(5), term(5), suffixes(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Compress the file 'file' with 'bzip2' and append all output to the file 'logfile' and stdout Bash Command:<START>bzip2 file | tee -a logfile<END>
Compresses all '*.xml' files under current directory with 'bzip2' utility.
find -name \*.xml -print0 | xargs -0 -n 1 -P 3 bzip2
['find', 'xargs']
Output a Bash command to accomplish the following task. Task: Compresses all '*.xml' files under current directory with 'bzip2' utility. Bash Command:<START>find -name \*.xml -print0 | xargs -0 -n 1 -P 3 bzip2<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 Task: Compresses all '*.xml' files under current directory with 'bzip2' utility. Bash Command:<START>find -name \*.xml -print0 | xargs -0 -n 1 -P 3 bzip2<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. Task: Compresses all '*.xml' files under current directory with 'bzip2' utility. Bash Command:<START>find -name \*.xml -print0 | xargs -0 -n 1 -P 3 bzip2<END>
Compresses all files in the directory 'PATH_TO_FOLDER' without recursion and keeps uncompressed files from deletion.
find PATH_TO_FOLDER -maxdepth 1 -type f -exec bzip2 -zk {} \;
['find']
Output a Bash command to accomplish the following task. Task: Compresses all files in the directory 'PATH_TO_FOLDER' without recursion and keeps uncompressed files from deletion. Bash Command:<START>find PATH_TO_FOLDER -maxdepth 1 -type f -exec bzip2 -zk {} \;<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: Compresses all files in the directory 'PATH_TO_FOLDER' without recursion and keeps uncompressed files from deletion. Bash Command:<START>find PATH_TO_FOLDER -maxdepth 1 -type f -exec bzip2 -zk {} \;<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: Compresses all files in the directory 'PATH_TO_FOLDER' without recursion and keeps uncompressed files from deletion. Bash Command:<START>find PATH_TO_FOLDER -maxdepth 1 -type f -exec bzip2 -zk {} \;<END>
Compresses all files listed in array $*, executing in background.
compress $* &
['compress']
Output a Bash command to accomplish the following task. Task: Compresses all files listed in array $*, executing in background. Bash Command:<START>compress $* &<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # compress\n\n> Compress files using the Unix `compress` command.\n> More information: <https://manned.org/compress.1>.\n\n- Compress specific files:\n\n`compress {{path/to/file1 path/to/file2 ...}}`\n\n- Compress specific files, ignore non-existent ones:\n\n`compress -f {{path/to/file1 path/to/file2 ...}}`\n\n- Specify the maximum compression bits (9-16 bits):\n\n`compress -b {{bits}}`\n\n- Write to `stdout` (no files are changed):\n\n`compress -c {{path/to/file}}`\n\n- Decompress files (functions like `uncompress`):\n\n`compress -d {{path/to/file}}`\n\n- Display compression percentage:\n\n`compress -v {{path/to/file}}`\n Task: Compresses all files listed in array $*, executing in background. Bash Command:<START>compress $* &<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: compress(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training compress(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 COMPRESS(1P) POSIX Programmer's Manual COMPRESS(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 compress compress data SYNOPSIS top compress [-fv] [-b bits] [file...] compress [-cfv] [-b bits] [file] DESCRIPTION top The compress utility shall attempt to reduce the size of the named files by using adaptive Lempel-Ziv coding algorithm. Note: Lempel-Ziv is US Patent 4464650, issued to William Eastman, Abraham Lempel, Jacob Ziv, Martin Cohn on August 7th, 1984, and assigned to Sperry Corporation. Lempel-Ziv-Welch compression is covered by US Patent 4558302, issued to Terry A. Welch on December 10th, 1985, and assigned to Sperry Corporation. On systems not supporting adaptive Lempel-Ziv coding algorithm, the input files shall not be changed and an error value greater than two shall be returned. Except when the output is to the standard output, each file shall be replaced by one with the extension .Z. If the invoking process has appropriate privileges, the ownership, modes, access time, and modification time of the original file are preserved. If appending the .Z to the filename would make the name exceed {NAME_MAX} bytes, the command shall fail. If no files are specified, the standard input shall be compressed to the standard output. OPTIONS top The compress utility shall conform to the Base Definitions volume of POSIX.12017, Section 12.2, Utility Syntax Guidelines. The following options shall be supported: -b bits Specify the maximum number of bits to use in a code. For a conforming application, the bits argument shall be: 9 <= bits <= 14 The implementation may allow bits values of greater than 14. The default is 14, 15, or 16. -c Cause compress to write to the standard output; the input file is not changed, and no .Z files are created. -f Force compression of file, even if it does not actually reduce the size of the file, or if the corresponding file.Z file already exists. If the -f option is not given, and the process is not running in the background, the user is prompted as to whether an existing file.Z file should be overwritten. If the response is affirmative, the existing file will be overwritten. -v Write the percentage reduction of each file to standard error. OPERANDS top The following operand shall be supported: file A pathname of a file to be compressed. STDIN top The standard input shall be used only if no file operands are specified, or if a file operand is '-'. INPUT FILES top If file operands are specified, the input files contain the data to be compressed. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of compress: 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 used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category. 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), the behavior of character classes used in the extended regular expression defined for the yesexpr locale keyword in the LC_MESSAGES category. LC_MESSAGES Determine the locale used to process affirmative responses, and the locale used to affect the format and contents of diagnostic messages, prompts, and the output from the -v option written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. ASYNCHRONOUS EVENTS top Default. STDOUT top If no file operands are specified, or if a file operand is '-', or if the -c option is specified, the standard output contains the compressed output. STDERR top The standard error shall be used only for diagnostic and prompt messages and the output from -v. OUTPUT FILES top The output files shall contain the compressed output. The format of compressed files is unspecified and interchange of such files between implementations (including access via unspecified file sharing mechanisms) is not required by POSIX.12008. EXTENDED DESCRIPTION top None. EXIT STATUS top The following exit values shall be returned: 0 Successful completion. 1 An error occurred. 2 One or more files were not compressed because they would have increased in size (and the -f option was not specified). >2 An error occurred. CONSEQUENCES OF ERRORS top The input file shall remain unmodified. The following sections are informative. APPLICATION USAGE top The amount of compression obtained depends on the size of the input, the number of bits per code, and the distribution of common substrings. Typically, text such as source code or English is reduced by 5060%. Compression is generally much better than that achieved by Huffman coding or adaptive Huffman coding (compact), and takes less time to compute. Although compress strictly follows the default actions upon receipt of a signal or when an error occurs, some unexpected results may occur. In some implementations it is likely that a partially compressed file is left in place, alongside its uncompressed input file. Since the general operation of compress is to delete the uncompressed file only after the .Z file has been successfully filled, an application should always carefully check the exit status of compress before arbitrarily deleting files that have like-named neighbors with .Z suffixes. The limit of 14 on the bits option-argument is to achieve portability to all systems (within the restrictions imposed by the lack of an explicit published file format). Some implementations based on 16-bit architectures cannot support 15 or 16-bit uncompression. EXAMPLES top None. RATIONALE top None. FUTURE DIRECTIONS top None. SEE ALSO top uncompress(1p), zcat(1p) The Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines 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 COMPRESS(1P) Pages that refer to this page: uncompress(1p), zcat(1p) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Compresses all files listed in array $*, executing in background. Bash Command:<START>compress $* &<END>
Compresses with compression level 9 all files under the current folder but already compressed '*.bz2' files, performing in background.
find "$1" -type f | egrep -v '\.bz2' | xargs bzip2 -9 &
['find', 'xargs']
Output a Bash command to accomplish the following task. Task: Compresses with compression level 9 all files under the current folder but already compressed '*.bz2' files, performing in background. Bash Command:<START>find "$1" -type f | egrep -v '\.bz2' | xargs bzip2 -9 &<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # 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: Compresses with compression level 9 all files under the current folder but already compressed '*.bz2' files, performing in background. Bash Command:<START>find "$1" -type f | egrep -v '\.bz2' | xargs bzip2 -9 &<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. 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: Compresses with compression level 9 all files under the current folder but already compressed '*.bz2' files, performing in background. Bash Command:<START>find "$1" -type f | egrep -v '\.bz2' | xargs bzip2 -9 &<END>
Compute the mean average of the word count of *.txt files smaller than 2000 words in the home directory
find ~/Journalism -name '*.txt' -print0 | xargs -0 wc -w | awk '$1 < 2000 {v += $1; c++} END {print v/c}'
['find', 'wc', 'awk', 'xargs']
Output a Bash command to accomplish the following task. Task: Compute the mean average of the word count of *.txt files smaller than 2000 words in the home directory Bash Command:<START>find ~/Journalism -name '*.txt' -print0 | xargs -0 wc -w | awk '$1 < 2000 {v += $1; c++} END {print v/c}'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # wc\n\n> Count lines, words, and bytes.\n> More information: <https://www.gnu.org/software/coreutils/wc>.\n\n- Count all lines in a file:\n\n`wc --lines {{path/to/file}}`\n\n- Count all words in a file:\n\n`wc --words {{path/to/file}}`\n\n- Count all bytes in a file:\n\n`wc --bytes {{path/to/file}}`\n\n- Count all characters in a file (taking multi-byte characters into account):\n\n`wc --chars {{path/to/file}}`\n\n- Count all lines, words and bytes from `stdin`:\n\n`{{find .}} | wc`\n\n- Count the length of the longest line in number of characters:\n\n`wc --max-line-length {{path/to/file}}`\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 # 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: Compute the mean average of the word count of *.txt files smaller than 2000 words in the home directory Bash Command:<START>find ~/Journalism -name '*.txt' -print0 | xargs -0 wc -w | awk '$1 < 2000 {v += $1; c++} END {print v/c}'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. wc(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training wc(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON WC(1) User Commands WC(1) NAME top wc - print newline, word, and byte counts for each file SYNOPSIS top wc [OPTION]... [FILE]... wc [OPTION]... --files0-from=F DESCRIPTION top Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified. A word is a non-zero-length sequence of printable characters delimited by white space. With no FILE, or when FILE is -, read standard input. The options below may be used to select which counts are printed, always in the following order: newline, word, character, byte, maximum line length. -c, --bytes print the byte counts -m, --chars print the character counts -l, --lines print the newline counts --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 -L, --max-line-length print the maximum display width -w, --words print the word counts --total=WHEN when to print a line with total counts; WHEN can be: auto, always, only, never --help display this help and exit --version output version information and exit AUTHOR top Written by Paul Rubin 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/wc> or available locally via: info '(coreutils) wc 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 WC(1) Pages that refer to this page: 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. 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. 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: Compute the mean average of the word count of *.txt files smaller than 2000 words in the home directory Bash Command:<START>find ~/Journalism -name '*.txt' -print0 | xargs -0 wc -w | awk '$1 < 2000 {v += $1; c++} END {print v/c}'<END>
Concatenate all files under the current directory and below that contain "test" in their names
find . -iname '*test*' -exec cat {} \;
['find', 'cat']
Output a Bash command to accomplish the following task. Task: Concatenate all files under the current directory and below that contain "test" in their names Bash Command:<START>find . -iname '*test*' -exec cat {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cat\n\n> Print and concatenate files.\n> More information: <https://www.gnu.org/software/coreutils/cat>.\n\n- Print the contents of a file to `stdout`:\n\n`cat {{path/to/file}}`\n\n- Concatenate several files into an output file:\n\n`cat {{path/to/file1 path/to/file2 ...}} > {{path/to/output_file}}`\n\n- Append several files to an output file:\n\n`cat {{path/to/file1 path/to/file2 ...}} >> {{path/to/output_file}}`\n\n- Write `stdin` to a file:\n\n`cat - > {{path/to/file}}`\n\n- [n]umber all output lines:\n\n`cat -n {{path/to/file}}`\n\n- Display non-printable and whitespace characters (with `M-` prefix if non-ASCII):\n\n`cat -v -t -e {{path/to/file}}`\n Task: Concatenate all files under the current directory and below that contain "test" in their names Bash Command:<START>find . -iname '*test*' -exec cat {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cat(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cat(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CAT(1) User Commands CAT(1) NAME top cat - concatenate files and print on the standard output SYNOPSIS top cat [OPTION]... [FILE]... DESCRIPTION top Concatenate FILE(s) to standard output. With no FILE, or when FILE is -, read standard input. -A, --show-all equivalent to -vET -b, --number-nonblank number nonempty output lines, overrides -n -e equivalent to -vE -E, --show-ends display $ at end of each line -n, --number number all output lines -s, --squeeze-blank suppress repeated empty output lines -t equivalent to -vT -T, --show-tabs display TAB characters as ^I -u (ignored) -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB --help display this help and exit --version output version information and exit EXAMPLES top cat f - g Output f's contents, then standard input, then g's contents. cat Copy standard input to standard output. AUTHOR top Written by Torbjorn Granlund and Richard M. Stallman. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top tac(1) Full documentation <https://www.gnu.org/software/coreutils/cat> or available locally via: info '(coreutils) cat invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CAT(1) Pages that refer to this page: pmlogrewrite(1), pv(1), systemd-socket-activate(1), tac(1), ul(1), proc(5), cpuset(7), time_namespaces(7), readprofile(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Concatenate all files under the current directory and below that contain "test" in their names Bash Command:<START>find . -iname '*test*' -exec cat {} \;<END>
Concatenate files containing `test' in their names
find . -name '*test*' -exec cat {} \;
['find', 'cat']
Output a Bash command to accomplish the following task. Task: Concatenate files containing `test' in their names Bash Command:<START>find . -name '*test*' -exec cat {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cat\n\n> Print and concatenate files.\n> More information: <https://www.gnu.org/software/coreutils/cat>.\n\n- Print the contents of a file to `stdout`:\n\n`cat {{path/to/file}}`\n\n- Concatenate several files into an output file:\n\n`cat {{path/to/file1 path/to/file2 ...}} > {{path/to/output_file}}`\n\n- Append several files to an output file:\n\n`cat {{path/to/file1 path/to/file2 ...}} >> {{path/to/output_file}}`\n\n- Write `stdin` to a file:\n\n`cat - > {{path/to/file}}`\n\n- [n]umber all output lines:\n\n`cat -n {{path/to/file}}`\n\n- Display non-printable and whitespace characters (with `M-` prefix if non-ASCII):\n\n`cat -v -t -e {{path/to/file}}`\n Task: Concatenate files containing `test' in their names Bash Command:<START>find . -name '*test*' -exec cat {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cat(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cat(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CAT(1) User Commands CAT(1) NAME top cat - concatenate files and print on the standard output SYNOPSIS top cat [OPTION]... [FILE]... DESCRIPTION top Concatenate FILE(s) to standard output. With no FILE, or when FILE is -, read standard input. -A, --show-all equivalent to -vET -b, --number-nonblank number nonempty output lines, overrides -n -e equivalent to -vE -E, --show-ends display $ at end of each line -n, --number number all output lines -s, --squeeze-blank suppress repeated empty output lines -t equivalent to -vT -T, --show-tabs display TAB characters as ^I -u (ignored) -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB --help display this help and exit --version output version information and exit EXAMPLES top cat f - g Output f's contents, then standard input, then g's contents. cat Copy standard input to standard output. AUTHOR top Written by Torbjorn Granlund and Richard M. Stallman. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top tac(1) Full documentation <https://www.gnu.org/software/coreutils/cat> or available locally via: info '(coreutils) cat invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CAT(1) Pages that refer to this page: pmlogrewrite(1), pv(1), systemd-socket-activate(1), tac(1), ul(1), proc(5), cpuset(7), time_namespaces(7), readprofile(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Concatenate files containing `test' in their names Bash Command:<START>find . -name '*test*' -exec cat {} \;<END>
Concatenate with a space every other line in "input.txt"
paste -s -d' \n' input.txt
['paste']
Output a Bash command to accomplish the following task. Task: Concatenate with a space every other line in "input.txt" Bash Command:<START>paste -s -d' \n' input.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # paste\n\n> Merge lines of files.\n> More information: <https://www.gnu.org/software/coreutils/paste>.\n\n- Join all the lines into a single line, using TAB as delimiter:\n\n`paste -s {{path/to/file}}`\n\n- Join all the lines into a single line, using the specified delimiter:\n\n`paste -s -d {{delimiter}} {{path/to/file}}`\n\n- Merge two files side by side, each in its column, using TAB as delimiter:\n\n`paste {{file1}} {{file2}}`\n\n- Merge two files side by side, each in its column, using the specified delimiter:\n\n`paste -d {{delimiter}} {{file1}} {{file2}}`\n\n- Merge two files, with lines added alternatively:\n\n`paste -d '\n' {{file1}} {{file2}}`\n Task: Concatenate with a space every other line in "input.txt" Bash Command:<START>paste -s -d' \n' input.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: paste(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training paste(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON PASTE(1) User Commands PASTE(1) NAME top paste - merge lines of files SYNOPSIS top paste [OPTION]... [FILE]... DESCRIPTION top Write lines consisting of the sequentially corresponding lines from each FILE, separated by TABs, to standard output. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -d, --delimiters=LIST reuse characters from LIST instead of TABs -s, --serial paste one file at a time instead of in parallel -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit AUTHOR top Written by David M. Ihnat 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/paste> or available locally via: info '(coreutils) paste 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 PASTE(1) Pages that refer to this page: colrm(1), column(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: Concatenate with a space every other line in "input.txt" Bash Command:<START>paste -s -d' \n' input.txt<END>
Connect as ssh user specified by variable USER to host whose IP address or host name is specified by HOST, and copy remote file specified by variable SRC to location on local host specified by variable DEST, disabling progress info but enabling debug info.
scp -qv $USER@$HOST:$SRC $DEST
['scp']
Output a Bash command to accomplish the following task. Task: Connect as ssh user specified by variable USER to host whose IP address or host name is specified by HOST, and copy remote file specified by variable SRC to location on local host specified by variable DEST, disabling progress info but enabling debug info. Bash Command:<START>scp -qv $USER@$HOST:$SRC $DEST<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # scp\n\n> Secure copy.\n> Copy files between hosts using Secure Copy Protocol over SSH.\n> More information: <https://man.openbsd.org/scp>.\n\n- Copy a local file to a remote host:\n\n`scp {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific port when connecting to the remote host:\n\n`scp -P {{port}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Copy a file from a remote host to a local directory:\n\n`scp {{remote_host}}:{{path/to/remote_file}} {{path/to/local_directory}}`\n\n- Recursively copy the contents of a directory from a remote host to a local directory:\n\n`scp -r {{remote_host}}:{{path/to/remote_directory}} {{path/to/local_directory}}`\n\n- Copy a file between two remote hosts transferring through the local host:\n\n`scp -3 {{host1}}:{{path/to/remote_file}} {{host2}}:{{path/to/remote_directory}}`\n\n- Use a specific username when connecting to the remote host:\n\n`scp {{path/to/local_file}} {{remote_username}}@{{remote_host}}:{{path/to/remote_directory}}`\n\n- Use a specific SSH private key for authentication with the remote host:\n\n`scp -i {{~/.ssh/private_key}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific proxy when connecting to the remote host:\n\n`scp -J {{proxy_username}}@{{proxy_host}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n Task: Connect as ssh user specified by variable USER to host whose IP address or host name is specified by HOST, and copy remote file specified by variable SRC to location on local host specified by variable DEST, disabling progress info but enabling debug info. Bash Command:<START>scp -qv $USER@$HOST:$SRC $DEST<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: scp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training scp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXIT STATUS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | COLOPHON SCP(1) General Commands Manual SCP(1) NAME top scp OpenSSH secure file copy SYNOPSIS top scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] [-X sftp_option] source ... target DESCRIPTION top copies files between hosts on a network. uses the SFTP protocol over a ssh(1) connection for data transfer, and uses the same authentication and provides the same security as a login session. will ask for passwords or passphrases if they are needed for authentication. The source and target may be specified as a local pathname, a remote host with optional path in the form [user@]host:[path], or a URI in the form scp://[user@]host[:port][/path]. Local file names can be made explicit using absolute or relative pathnames to avoid treating file names containing : as host specifiers. When copying between two remote hosts, if the URI format is used, a port cannot be specified on the target if the -R option is used. The options are as follows: -3 Copies between two remote hosts are transferred through the local host. Without this option the data is copied directly between the two remote hosts. Note that, when using the legacy SCP protocol (via the -O flag), this option selects batch mode for the second host as cannot ask for passwords or passphrases for both hosts. This mode is the default. -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Allows forwarding of ssh-agent(1) to the remote system. The default is not to forward an authentication agent. -B Selects batch mode (prevents asking for passwords or passphrases). -C Compression enable. Passes the -C flag to ssh(1) to enable compression. -c cipher Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1). -D sftp_server_path Connect directly to a local SFTP server program rather than a remote one via ssh(1). This option may be useful in debugging the client and server. -F ssh_config Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh(1). -i identity_file Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh(1). -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. This option is directly passed to ssh(1). -l limit Limits the used bandwidth, specified in Kbit/s. -O Use the legacy SCP protocol for file transfers instead of the SFTP protocol. Forcing the use of the SCP protocol may be necessary for servers that do not implement SFTP, for backwards-compatibility for particular filename wildcard patterns and for expanding paths with a ~ prefix for older SFTP servers. -o ssh_option Can be used to pass options to ssh in the format used in ssh_config(5). This is useful for specifying options for which there is no separate scp command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddressFamily BatchMode BindAddress BindInterface CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LogLevel MACs NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SetEnv StrictHostKeyChecking TCPKeepAlive UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS -P port Specifies the port to connect to on the remote host. Note that this option is written with a capital P, because -p is already reserved for preserving the times and mode bits of the file. -p Preserves modification times, access times, and file mode bits from the source file. -q Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1). -R Copies between two remote hosts are performed by connecting to the origin host and executing there. This requires that running on the origin host can authenticate to the destination host without requiring a password. -r Recursively copy entire directories. Note that follows symbolic links encountered in the tree traversal. -S program Name of program to use for the encrypted connection. The program must understand ssh(1) options. -T Disable strict filename checking. By default when copying files from a remote host to a local directory checks that the received filenames match those requested on the command-line to prevent the remote end from sending unexpected or unwanted files. Because of differences in how various operating systems and shells interpret filename wildcards, these checks may cause wanted files to be rejected. This option disables these checks at the expense of fully trusting that the server will not send unexpected filenames. -v Verbose mode. Causes and ssh(1) to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems. -X sftp_option Specify an option that controls aspects of SFTP protocol behaviour. The valid options are: nrequests=value Controls how many concurrent SFTP read or write requests may be in progress at any point in time during a download or upload. By default 64 requests may be active concurrently. buffer=value Controls the maximum buffer size for a single SFTP read/write operation used during download or upload. By default a 32KB buffer is used. EXIT STATUS top The scp utility exits 0 on success, and >0 if an error occurs. SEE ALSO top sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh_config(5), sftp-server(8), sshd(8) HISTORY top is based on the rcp program in BSD source code from the Regents of the University of California. Since OpenSSH 9.0, has used the SFTP protocol for transfers by default. AUTHORS top Timo Rinne <tri@iki.fi> Tatu Ylonen <ylo@cs.hut.fi> CAVEATS top The legacy SCP protocol (selected by the -O flag) requires execution of the remote user's shell to perform glob(3) pattern matching. This requires careful quoting of any characters that have special meaning to the remote shell, such as quote characters. 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 December 16, 2022 SCP(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: Connect as ssh user specified by variable USER to host whose IP address or host name is specified by HOST, and copy remote file specified by variable SRC to location on local host specified by variable DEST, disabling progress info but enabling debug info. Bash Command:<START>scp -qv $USER@$HOST:$SRC $DEST<END>
Connect to "$USER_AT_HOST" using connection sharing on "$SSHSOCKET" and request the master to exit
ssh -S "$SSHSOCKET" -O exit "$USER_AT_HOST"
['exit', 'ssh']
Output a Bash command to accomplish the following task. Task: Connect to "$USER_AT_HOST" using connection sharing on "$SSHSOCKET" and request the master to exit Bash Command:<START>ssh -S "$SSHSOCKET" -O exit "$USER_AT_HOST"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # exit\n\n> Exit the shell.\n> More information: <https://manned.org/exit.1posix>.\n\n- Exit with the exit status of the most recently executed command:\n\n`exit`\n\n- Exit with a specific exit status:\n\n`exit {{exit_code}}`\n # 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: Connect to "$USER_AT_HOST" using connection sharing on "$SSHSOCKET" and request the master to exit Bash Command:<START>ssh -S "$SSHSOCKET" -O exit "$USER_AT_HOST"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: exit(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training exit(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 EXIT(1P) POSIX Programmer's Manual EXIT(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 exit cause the shell to exit SYNOPSIS top exit [n] DESCRIPTION top The exit utility shall cause the shell to exit from its current execution environment with the exit status specified by the unsigned decimal integer n. If the current execution environment is a subshell environment, the shell shall exit from the subshell environment with the specified exit status and continue in the environment from which that subshell environment was invoked; otherwise, the shell utility shall terminate with the specified exit status. If n is specified, but its value is not between 0 and 255 inclusively, the exit status is undefined. A trap on EXIT shall be executed before the shell terminates, except when the exit utility is invoked in that trap itself, in which case the shell shall exit immediately. OPTIONS top None. OPERANDS top See the DESCRIPTION. STDIN top Not used. INPUT FILES top None. ENVIRONMENT VARIABLES top None. ASYNCHRONOUS EVENTS top Default. STDOUT top Not used. STDERR top The standard error shall be used only for diagnostic messages. OUTPUT FILES top None. EXTENDED DESCRIPTION top None. EXIT STATUS top The exit status shall be n, if specified, except that the behavior is unspecified if n is not an unsigned decimal integer or is greater than 255. Otherwise, the value shall be the exit value of the last command executed, or zero if no command was executed. When exit is executed in a trap action, the last command is considered to be the command that executed immediately preceding the trap action. CONSEQUENCES OF ERRORS top Default. The following sections are informative. APPLICATION USAGE top None. EXAMPLES top Exit with a true value: exit 0 Exit with a false value: exit 1 Propagate error handling from within a subshell: ( command1 || exit 1 command2 || exit 1 exec command3 ) > outputfile || exit 1 echo "outputfile created successfully" RATIONALE top As explained in other sections, certain exit status values have been reserved for special uses and should be used by applications only for those purposes: 126 A file to be executed was found, but it was not an executable utility. 127 A utility to be executed was not found. >128 A command was interrupted by a signal. The behavior of exit when given an invalid argument or unknown option is unspecified, because of differing practices in the various historical implementations. A value larger than 255 might be truncated by the shell, and be unavailable even to a parent process that uses waitid() to get the full exit value. It is recommended that implementations that detect any usage error should cause a non-zero exit status (or, if the shell is interactive and the error does not cause the shell to abort, store a non-zero value in "$?"), but even this was not done historically in all shells. FUTURE DIRECTIONS top None. SEE ALSO top Section 2.14, Special Built-In Utilities 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 EXIT(1P) Pages that refer to this page: return(1p), sh(1p) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. 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: Connect to "$USER_AT_HOST" using connection sharing on "$SSHSOCKET" and request the master to exit Bash Command:<START>ssh -S "$SSHSOCKET" -O exit "$USER_AT_HOST"<END>
Connect to host "$USER_AT_HOST" in master mode in the background without executing any commands and set the ControlPath to "$SSHSOCKET"
ssh -M -f -N -o ControlPath="$SSHSOCKET" "$USER_AT_HOST"
['ssh']
Output a Bash command to accomplish the following task. Task: Connect to host "$USER_AT_HOST" in master mode in the background without executing any commands and set the ControlPath to "$SSHSOCKET" Bash Command:<START>ssh -M -f -N -o ControlPath="$SSHSOCKET" "$USER_AT_HOST"<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: Connect to host "$USER_AT_HOST" in master mode in the background without executing any commands and set the ControlPath to "$SSHSOCKET" Bash Command:<START>ssh -M -f -N -o ControlPath="$SSHSOCKET" "$USER_AT_HOST"<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: Connect to host "$USER_AT_HOST" in master mode in the background without executing any commands and set the ControlPath to "$SSHSOCKET" Bash Command:<START>ssh -M -f -N -o ControlPath="$SSHSOCKET" "$USER_AT_HOST"<END>
Connect to host "${HOSTNAME}" as user "${USERNAME}" and execute "${SCRIPT}" non-interactively
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
['ssh']
Output a Bash command to accomplish the following task. Task: Connect to host "${HOSTNAME}" as user "${USERNAME}" and execute "${SCRIPT}" non-interactively Bash Command:<START>ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"<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: Connect to host "${HOSTNAME}" as user "${USERNAME}" and execute "${SCRIPT}" non-interactively Bash Command:<START>ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"<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: Connect to host "${HOSTNAME}" as user "${USERNAME}" and execute "${SCRIPT}" non-interactively Bash Command:<START>ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"<END>
Connect to host "remotehost" as ssh user "user" to copy remote file "/location/KMST_DataFile_*.kms" to current directory on local host.
scp -v user@remotehost:/location/KMST_DataFile_*.kms
['scp']
Output a Bash command to accomplish the following task. Task: Connect to host "remotehost" as ssh user "user" to copy remote file "/location/KMST_DataFile_*.kms" to current directory on local host. Bash Command:<START>scp -v user@remotehost:/location/KMST_DataFile_*.kms<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # scp\n\n> Secure copy.\n> Copy files between hosts using Secure Copy Protocol over SSH.\n> More information: <https://man.openbsd.org/scp>.\n\n- Copy a local file to a remote host:\n\n`scp {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific port when connecting to the remote host:\n\n`scp -P {{port}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Copy a file from a remote host to a local directory:\n\n`scp {{remote_host}}:{{path/to/remote_file}} {{path/to/local_directory}}`\n\n- Recursively copy the contents of a directory from a remote host to a local directory:\n\n`scp -r {{remote_host}}:{{path/to/remote_directory}} {{path/to/local_directory}}`\n\n- Copy a file between two remote hosts transferring through the local host:\n\n`scp -3 {{host1}}:{{path/to/remote_file}} {{host2}}:{{path/to/remote_directory}}`\n\n- Use a specific username when connecting to the remote host:\n\n`scp {{path/to/local_file}} {{remote_username}}@{{remote_host}}:{{path/to/remote_directory}}`\n\n- Use a specific SSH private key for authentication with the remote host:\n\n`scp -i {{~/.ssh/private_key}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific proxy when connecting to the remote host:\n\n`scp -J {{proxy_username}}@{{proxy_host}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n Task: Connect to host "remotehost" as ssh user "user" to copy remote file "/location/KMST_DataFile_*.kms" to current directory on local host. Bash Command:<START>scp -v user@remotehost:/location/KMST_DataFile_*.kms<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: scp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training scp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXIT STATUS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | COLOPHON SCP(1) General Commands Manual SCP(1) NAME top scp OpenSSH secure file copy SYNOPSIS top scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] [-X sftp_option] source ... target DESCRIPTION top copies files between hosts on a network. uses the SFTP protocol over a ssh(1) connection for data transfer, and uses the same authentication and provides the same security as a login session. will ask for passwords or passphrases if they are needed for authentication. The source and target may be specified as a local pathname, a remote host with optional path in the form [user@]host:[path], or a URI in the form scp://[user@]host[:port][/path]. Local file names can be made explicit using absolute or relative pathnames to avoid treating file names containing : as host specifiers. When copying between two remote hosts, if the URI format is used, a port cannot be specified on the target if the -R option is used. The options are as follows: -3 Copies between two remote hosts are transferred through the local host. Without this option the data is copied directly between the two remote hosts. Note that, when using the legacy SCP protocol (via the -O flag), this option selects batch mode for the second host as cannot ask for passwords or passphrases for both hosts. This mode is the default. -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Allows forwarding of ssh-agent(1) to the remote system. The default is not to forward an authentication agent. -B Selects batch mode (prevents asking for passwords or passphrases). -C Compression enable. Passes the -C flag to ssh(1) to enable compression. -c cipher Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1). -D sftp_server_path Connect directly to a local SFTP server program rather than a remote one via ssh(1). This option may be useful in debugging the client and server. -F ssh_config Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh(1). -i identity_file Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh(1). -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. This option is directly passed to ssh(1). -l limit Limits the used bandwidth, specified in Kbit/s. -O Use the legacy SCP protocol for file transfers instead of the SFTP protocol. Forcing the use of the SCP protocol may be necessary for servers that do not implement SFTP, for backwards-compatibility for particular filename wildcard patterns and for expanding paths with a ~ prefix for older SFTP servers. -o ssh_option Can be used to pass options to ssh in the format used in ssh_config(5). This is useful for specifying options for which there is no separate scp command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddressFamily BatchMode BindAddress BindInterface CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LogLevel MACs NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SetEnv StrictHostKeyChecking TCPKeepAlive UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS -P port Specifies the port to connect to on the remote host. Note that this option is written with a capital P, because -p is already reserved for preserving the times and mode bits of the file. -p Preserves modification times, access times, and file mode bits from the source file. -q Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1). -R Copies between two remote hosts are performed by connecting to the origin host and executing there. This requires that running on the origin host can authenticate to the destination host without requiring a password. -r Recursively copy entire directories. Note that follows symbolic links encountered in the tree traversal. -S program Name of program to use for the encrypted connection. The program must understand ssh(1) options. -T Disable strict filename checking. By default when copying files from a remote host to a local directory checks that the received filenames match those requested on the command-line to prevent the remote end from sending unexpected or unwanted files. Because of differences in how various operating systems and shells interpret filename wildcards, these checks may cause wanted files to be rejected. This option disables these checks at the expense of fully trusting that the server will not send unexpected filenames. -v Verbose mode. Causes and ssh(1) to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems. -X sftp_option Specify an option that controls aspects of SFTP protocol behaviour. The valid options are: nrequests=value Controls how many concurrent SFTP read or write requests may be in progress at any point in time during a download or upload. By default 64 requests may be active concurrently. buffer=value Controls the maximum buffer size for a single SFTP read/write operation used during download or upload. By default a 32KB buffer is used. EXIT STATUS top The scp utility exits 0 on success, and >0 if an error occurs. SEE ALSO top sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh_config(5), sftp-server(8), sshd(8) HISTORY top is based on the rcp program in BSD source code from the Regents of the University of California. Since OpenSSH 9.0, has used the SFTP protocol for transfers by default. AUTHORS top Timo Rinne <tri@iki.fi> Tatu Ylonen <ylo@cs.hut.fi> CAVEATS top The legacy SCP protocol (selected by the -O flag) requires execution of the remote user's shell to perform glob(3) pattern matching. This requires careful quoting of any characters that have special meaning to the remote shell, such as quote characters. 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 December 16, 2022 SCP(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: Connect to host "remotehost" as ssh user "user" to copy remote file "/location/KMST_DataFile_*.kms" to current directory on local host. Bash Command:<START>scp -v user@remotehost:/location/KMST_DataFile_*.kms<END>
Connect to host "server_b" as ssh user "user" and copy local file "/my_folder/my_file.xml" to server_b's directory "/my_new_folder/".
scp -v /my_folder/my_file.xml user@server_b:/my_new_folder/
['scp']
Output a Bash command to accomplish the following task. Task: Connect to host "server_b" as ssh user "user" and copy local file "/my_folder/my_file.xml" to server_b's directory "/my_new_folder/". Bash Command:<START>scp -v /my_folder/my_file.xml user@server_b:/my_new_folder/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # scp\n\n> Secure copy.\n> Copy files between hosts using Secure Copy Protocol over SSH.\n> More information: <https://man.openbsd.org/scp>.\n\n- Copy a local file to a remote host:\n\n`scp {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific port when connecting to the remote host:\n\n`scp -P {{port}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Copy a file from a remote host to a local directory:\n\n`scp {{remote_host}}:{{path/to/remote_file}} {{path/to/local_directory}}`\n\n- Recursively copy the contents of a directory from a remote host to a local directory:\n\n`scp -r {{remote_host}}:{{path/to/remote_directory}} {{path/to/local_directory}}`\n\n- Copy a file between two remote hosts transferring through the local host:\n\n`scp -3 {{host1}}:{{path/to/remote_file}} {{host2}}:{{path/to/remote_directory}}`\n\n- Use a specific username when connecting to the remote host:\n\n`scp {{path/to/local_file}} {{remote_username}}@{{remote_host}}:{{path/to/remote_directory}}`\n\n- Use a specific SSH private key for authentication with the remote host:\n\n`scp -i {{~/.ssh/private_key}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific proxy when connecting to the remote host:\n\n`scp -J {{proxy_username}}@{{proxy_host}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n Task: Connect to host "server_b" as ssh user "user" and copy local file "/my_folder/my_file.xml" to server_b's directory "/my_new_folder/". Bash Command:<START>scp -v /my_folder/my_file.xml user@server_b:/my_new_folder/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: scp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training scp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXIT STATUS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | COLOPHON SCP(1) General Commands Manual SCP(1) NAME top scp OpenSSH secure file copy SYNOPSIS top scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] [-X sftp_option] source ... target DESCRIPTION top copies files between hosts on a network. uses the SFTP protocol over a ssh(1) connection for data transfer, and uses the same authentication and provides the same security as a login session. will ask for passwords or passphrases if they are needed for authentication. The source and target may be specified as a local pathname, a remote host with optional path in the form [user@]host:[path], or a URI in the form scp://[user@]host[:port][/path]. Local file names can be made explicit using absolute or relative pathnames to avoid treating file names containing : as host specifiers. When copying between two remote hosts, if the URI format is used, a port cannot be specified on the target if the -R option is used. The options are as follows: -3 Copies between two remote hosts are transferred through the local host. Without this option the data is copied directly between the two remote hosts. Note that, when using the legacy SCP protocol (via the -O flag), this option selects batch mode for the second host as cannot ask for passwords or passphrases for both hosts. This mode is the default. -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Allows forwarding of ssh-agent(1) to the remote system. The default is not to forward an authentication agent. -B Selects batch mode (prevents asking for passwords or passphrases). -C Compression enable. Passes the -C flag to ssh(1) to enable compression. -c cipher Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1). -D sftp_server_path Connect directly to a local SFTP server program rather than a remote one via ssh(1). This option may be useful in debugging the client and server. -F ssh_config Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh(1). -i identity_file Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh(1). -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. This option is directly passed to ssh(1). -l limit Limits the used bandwidth, specified in Kbit/s. -O Use the legacy SCP protocol for file transfers instead of the SFTP protocol. Forcing the use of the SCP protocol may be necessary for servers that do not implement SFTP, for backwards-compatibility for particular filename wildcard patterns and for expanding paths with a ~ prefix for older SFTP servers. -o ssh_option Can be used to pass options to ssh in the format used in ssh_config(5). This is useful for specifying options for which there is no separate scp command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddressFamily BatchMode BindAddress BindInterface CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LogLevel MACs NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SetEnv StrictHostKeyChecking TCPKeepAlive UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS -P port Specifies the port to connect to on the remote host. Note that this option is written with a capital P, because -p is already reserved for preserving the times and mode bits of the file. -p Preserves modification times, access times, and file mode bits from the source file. -q Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1). -R Copies between two remote hosts are performed by connecting to the origin host and executing there. This requires that running on the origin host can authenticate to the destination host without requiring a password. -r Recursively copy entire directories. Note that follows symbolic links encountered in the tree traversal. -S program Name of program to use for the encrypted connection. The program must understand ssh(1) options. -T Disable strict filename checking. By default when copying files from a remote host to a local directory checks that the received filenames match those requested on the command-line to prevent the remote end from sending unexpected or unwanted files. Because of differences in how various operating systems and shells interpret filename wildcards, these checks may cause wanted files to be rejected. This option disables these checks at the expense of fully trusting that the server will not send unexpected filenames. -v Verbose mode. Causes and ssh(1) to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems. -X sftp_option Specify an option that controls aspects of SFTP protocol behaviour. The valid options are: nrequests=value Controls how many concurrent SFTP read or write requests may be in progress at any point in time during a download or upload. By default 64 requests may be active concurrently. buffer=value Controls the maximum buffer size for a single SFTP read/write operation used during download or upload. By default a 32KB buffer is used. EXIT STATUS top The scp utility exits 0 on success, and >0 if an error occurs. SEE ALSO top sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh_config(5), sftp-server(8), sshd(8) HISTORY top is based on the rcp program in BSD source code from the Regents of the University of California. Since OpenSSH 9.0, has used the SFTP protocol for transfers by default. AUTHORS top Timo Rinne <tri@iki.fi> Tatu Ylonen <ylo@cs.hut.fi> CAVEATS top The legacy SCP protocol (selected by the -O flag) requires execution of the remote user's shell to perform glob(3) pattern matching. This requires careful quoting of any characters that have special meaning to the remote shell, such as quote characters. 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 December 16, 2022 SCP(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: Connect to host "server_b" as ssh user "user" and copy local file "/my_folder/my_file.xml" to server_b's directory "/my_new_folder/". Bash Command:<START>scp -v /my_folder/my_file.xml user@server_b:/my_new_folder/<END>
Connect to host 'hostname' as user 'username' by forcing host key confirmation
ssh -o UserKnownHostsFile=/dev/null username@hostname
['ssh']
Output a Bash command to accomplish the following task. Task: Connect to host 'hostname' as user 'username' by forcing host key confirmation Bash Command:<START>ssh -o UserKnownHostsFile=/dev/null username@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: Connect to host 'hostname' as user 'username' by forcing host key confirmation Bash Command:<START>ssh -o UserKnownHostsFile=/dev/null username@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: Connect to host 'hostname' as user 'username' by forcing host key confirmation Bash Command:<START>ssh -o UserKnownHostsFile=/dev/null username@hostname<END>
Connect to port 1234 of specified IP address or hostname as ssh user "user", and copy all visible files in /var/www/mywebsite/dumps/ on this host to local directory /myNewPathOnCurrentLocalMachine - this directory must already exist on local host.
scp -P 1234 user@[ip address or host name]:/var/www/mywebsite/dumps/* /var/www/myNewPathOnCurrentLocalMachine
['scp']
Output a Bash command to accomplish the following task. Task: Connect to port 1234 of specified IP address or hostname as ssh user "user", and copy all visible files in /var/www/mywebsite/dumps/ on this host to local directory /myNewPathOnCurrentLocalMachine - this directory must already exist on local host. Bash Command:<START>scp -P 1234 user@[ip address or host name]:/var/www/mywebsite/dumps/* /var/www/myNewPathOnCurrentLocalMachine<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # scp\n\n> Secure copy.\n> Copy files between hosts using Secure Copy Protocol over SSH.\n> More information: <https://man.openbsd.org/scp>.\n\n- Copy a local file to a remote host:\n\n`scp {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific port when connecting to the remote host:\n\n`scp -P {{port}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Copy a file from a remote host to a local directory:\n\n`scp {{remote_host}}:{{path/to/remote_file}} {{path/to/local_directory}}`\n\n- Recursively copy the contents of a directory from a remote host to a local directory:\n\n`scp -r {{remote_host}}:{{path/to/remote_directory}} {{path/to/local_directory}}`\n\n- Copy a file between two remote hosts transferring through the local host:\n\n`scp -3 {{host1}}:{{path/to/remote_file}} {{host2}}:{{path/to/remote_directory}}`\n\n- Use a specific username when connecting to the remote host:\n\n`scp {{path/to/local_file}} {{remote_username}}@{{remote_host}}:{{path/to/remote_directory}}`\n\n- Use a specific SSH private key for authentication with the remote host:\n\n`scp -i {{~/.ssh/private_key}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific proxy when connecting to the remote host:\n\n`scp -J {{proxy_username}}@{{proxy_host}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n Task: Connect to port 1234 of specified IP address or hostname as ssh user "user", and copy all visible files in /var/www/mywebsite/dumps/ on this host to local directory /myNewPathOnCurrentLocalMachine - this directory must already exist on local host. Bash Command:<START>scp -P 1234 user@[ip address or host name]:/var/www/mywebsite/dumps/* /var/www/myNewPathOnCurrentLocalMachine<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: scp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training scp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXIT STATUS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | COLOPHON SCP(1) General Commands Manual SCP(1) NAME top scp OpenSSH secure file copy SYNOPSIS top scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] [-X sftp_option] source ... target DESCRIPTION top copies files between hosts on a network. uses the SFTP protocol over a ssh(1) connection for data transfer, and uses the same authentication and provides the same security as a login session. will ask for passwords or passphrases if they are needed for authentication. The source and target may be specified as a local pathname, a remote host with optional path in the form [user@]host:[path], or a URI in the form scp://[user@]host[:port][/path]. Local file names can be made explicit using absolute or relative pathnames to avoid treating file names containing : as host specifiers. When copying between two remote hosts, if the URI format is used, a port cannot be specified on the target if the -R option is used. The options are as follows: -3 Copies between two remote hosts are transferred through the local host. Without this option the data is copied directly between the two remote hosts. Note that, when using the legacy SCP protocol (via the -O flag), this option selects batch mode for the second host as cannot ask for passwords or passphrases for both hosts. This mode is the default. -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Allows forwarding of ssh-agent(1) to the remote system. The default is not to forward an authentication agent. -B Selects batch mode (prevents asking for passwords or passphrases). -C Compression enable. Passes the -C flag to ssh(1) to enable compression. -c cipher Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1). -D sftp_server_path Connect directly to a local SFTP server program rather than a remote one via ssh(1). This option may be useful in debugging the client and server. -F ssh_config Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh(1). -i identity_file Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh(1). -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. This option is directly passed to ssh(1). -l limit Limits the used bandwidth, specified in Kbit/s. -O Use the legacy SCP protocol for file transfers instead of the SFTP protocol. Forcing the use of the SCP protocol may be necessary for servers that do not implement SFTP, for backwards-compatibility for particular filename wildcard patterns and for expanding paths with a ~ prefix for older SFTP servers. -o ssh_option Can be used to pass options to ssh in the format used in ssh_config(5). This is useful for specifying options for which there is no separate scp command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddressFamily BatchMode BindAddress BindInterface CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LogLevel MACs NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SetEnv StrictHostKeyChecking TCPKeepAlive UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS -P port Specifies the port to connect to on the remote host. Note that this option is written with a capital P, because -p is already reserved for preserving the times and mode bits of the file. -p Preserves modification times, access times, and file mode bits from the source file. -q Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1). -R Copies between two remote hosts are performed by connecting to the origin host and executing there. This requires that running on the origin host can authenticate to the destination host without requiring a password. -r Recursively copy entire directories. Note that follows symbolic links encountered in the tree traversal. -S program Name of program to use for the encrypted connection. The program must understand ssh(1) options. -T Disable strict filename checking. By default when copying files from a remote host to a local directory checks that the received filenames match those requested on the command-line to prevent the remote end from sending unexpected or unwanted files. Because of differences in how various operating systems and shells interpret filename wildcards, these checks may cause wanted files to be rejected. This option disables these checks at the expense of fully trusting that the server will not send unexpected filenames. -v Verbose mode. Causes and ssh(1) to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems. -X sftp_option Specify an option that controls aspects of SFTP protocol behaviour. The valid options are: nrequests=value Controls how many concurrent SFTP read or write requests may be in progress at any point in time during a download or upload. By default 64 requests may be active concurrently. buffer=value Controls the maximum buffer size for a single SFTP read/write operation used during download or upload. By default a 32KB buffer is used. EXIT STATUS top The scp utility exits 0 on success, and >0 if an error occurs. SEE ALSO top sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh_config(5), sftp-server(8), sshd(8) HISTORY top is based on the rcp program in BSD source code from the Regents of the University of California. Since OpenSSH 9.0, has used the SFTP protocol for transfers by default. AUTHORS top Timo Rinne <tri@iki.fi> Tatu Ylonen <ylo@cs.hut.fi> CAVEATS top The legacy SCP protocol (selected by the -O flag) requires execution of the remote user's shell to perform glob(3) pattern matching. This requires careful quoting of any characters that have special meaning to the remote shell, such as quote characters. 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 December 16, 2022 SCP(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: Connect to port 1234 of specified IP address or hostname as ssh user "user", and copy all visible files in /var/www/mywebsite/dumps/ on this host to local directory /myNewPathOnCurrentLocalMachine - this directory must already exist on local host. Bash Command:<START>scp -P 1234 user@[ip address or host name]:/var/www/mywebsite/dumps/* /var/www/myNewPathOnCurrentLocalMachine<END>
Connect to port 2222 of example.com as ssh user "user", and copy local file "/absolute_path/source-folder/some-file" to remote directory "/absolute_path/destination-folder"
scp -P 2222 /absolute_path/source-folder/some-file user@example.com:/absolute_path/destination-folder
['scp']
Output a Bash command to accomplish the following task. Task: Connect to port 2222 of example.com as ssh user "user", and copy local file "/absolute_path/source-folder/some-file" to remote directory "/absolute_path/destination-folder" Bash Command:<START>scp -P 2222 /absolute_path/source-folder/some-file user@example.com:/absolute_path/destination-folder<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # scp\n\n> Secure copy.\n> Copy files between hosts using Secure Copy Protocol over SSH.\n> More information: <https://man.openbsd.org/scp>.\n\n- Copy a local file to a remote host:\n\n`scp {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific port when connecting to the remote host:\n\n`scp -P {{port}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Copy a file from a remote host to a local directory:\n\n`scp {{remote_host}}:{{path/to/remote_file}} {{path/to/local_directory}}`\n\n- Recursively copy the contents of a directory from a remote host to a local directory:\n\n`scp -r {{remote_host}}:{{path/to/remote_directory}} {{path/to/local_directory}}`\n\n- Copy a file between two remote hosts transferring through the local host:\n\n`scp -3 {{host1}}:{{path/to/remote_file}} {{host2}}:{{path/to/remote_directory}}`\n\n- Use a specific username when connecting to the remote host:\n\n`scp {{path/to/local_file}} {{remote_username}}@{{remote_host}}:{{path/to/remote_directory}}`\n\n- Use a specific SSH private key for authentication with the remote host:\n\n`scp -i {{~/.ssh/private_key}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific proxy when connecting to the remote host:\n\n`scp -J {{proxy_username}}@{{proxy_host}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n Task: Connect to port 2222 of example.com as ssh user "user", and copy local file "/absolute_path/source-folder/some-file" to remote directory "/absolute_path/destination-folder" Bash Command:<START>scp -P 2222 /absolute_path/source-folder/some-file user@example.com:/absolute_path/destination-folder<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: scp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training scp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXIT STATUS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | COLOPHON SCP(1) General Commands Manual SCP(1) NAME top scp OpenSSH secure file copy SYNOPSIS top scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] [-X sftp_option] source ... target DESCRIPTION top copies files between hosts on a network. uses the SFTP protocol over a ssh(1) connection for data transfer, and uses the same authentication and provides the same security as a login session. will ask for passwords or passphrases if they are needed for authentication. The source and target may be specified as a local pathname, a remote host with optional path in the form [user@]host:[path], or a URI in the form scp://[user@]host[:port][/path]. Local file names can be made explicit using absolute or relative pathnames to avoid treating file names containing : as host specifiers. When copying between two remote hosts, if the URI format is used, a port cannot be specified on the target if the -R option is used. The options are as follows: -3 Copies between two remote hosts are transferred through the local host. Without this option the data is copied directly between the two remote hosts. Note that, when using the legacy SCP protocol (via the -O flag), this option selects batch mode for the second host as cannot ask for passwords or passphrases for both hosts. This mode is the default. -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Allows forwarding of ssh-agent(1) to the remote system. The default is not to forward an authentication agent. -B Selects batch mode (prevents asking for passwords or passphrases). -C Compression enable. Passes the -C flag to ssh(1) to enable compression. -c cipher Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1). -D sftp_server_path Connect directly to a local SFTP server program rather than a remote one via ssh(1). This option may be useful in debugging the client and server. -F ssh_config Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh(1). -i identity_file Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh(1). -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. This option is directly passed to ssh(1). -l limit Limits the used bandwidth, specified in Kbit/s. -O Use the legacy SCP protocol for file transfers instead of the SFTP protocol. Forcing the use of the SCP protocol may be necessary for servers that do not implement SFTP, for backwards-compatibility for particular filename wildcard patterns and for expanding paths with a ~ prefix for older SFTP servers. -o ssh_option Can be used to pass options to ssh in the format used in ssh_config(5). This is useful for specifying options for which there is no separate scp command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddressFamily BatchMode BindAddress BindInterface CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LogLevel MACs NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SetEnv StrictHostKeyChecking TCPKeepAlive UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS -P port Specifies the port to connect to on the remote host. Note that this option is written with a capital P, because -p is already reserved for preserving the times and mode bits of the file. -p Preserves modification times, access times, and file mode bits from the source file. -q Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1). -R Copies between two remote hosts are performed by connecting to the origin host and executing there. This requires that running on the origin host can authenticate to the destination host without requiring a password. -r Recursively copy entire directories. Note that follows symbolic links encountered in the tree traversal. -S program Name of program to use for the encrypted connection. The program must understand ssh(1) options. -T Disable strict filename checking. By default when copying files from a remote host to a local directory checks that the received filenames match those requested on the command-line to prevent the remote end from sending unexpected or unwanted files. Because of differences in how various operating systems and shells interpret filename wildcards, these checks may cause wanted files to be rejected. This option disables these checks at the expense of fully trusting that the server will not send unexpected filenames. -v Verbose mode. Causes and ssh(1) to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems. -X sftp_option Specify an option that controls aspects of SFTP protocol behaviour. The valid options are: nrequests=value Controls how many concurrent SFTP read or write requests may be in progress at any point in time during a download or upload. By default 64 requests may be active concurrently. buffer=value Controls the maximum buffer size for a single SFTP read/write operation used during download or upload. By default a 32KB buffer is used. EXIT STATUS top The scp utility exits 0 on success, and >0 if an error occurs. SEE ALSO top sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh_config(5), sftp-server(8), sshd(8) HISTORY top is based on the rcp program in BSD source code from the Regents of the University of California. Since OpenSSH 9.0, has used the SFTP protocol for transfers by default. AUTHORS top Timo Rinne <tri@iki.fi> Tatu Ylonen <ylo@cs.hut.fi> CAVEATS top The legacy SCP protocol (selected by the -O flag) requires execution of the remote user's shell to perform glob(3) pattern matching. This requires careful quoting of any characters that have special meaning to the remote shell, such as quote characters. 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 December 16, 2022 SCP(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: Connect to port 2222 of example.com as ssh user "user", and copy local file "/absolute_path/source-folder/some-file" to remote directory "/absolute_path/destination-folder" Bash Command:<START>scp -P 2222 /absolute_path/source-folder/some-file user@example.com:/absolute_path/destination-folder<END>
Connect via ssh to "your.server.example.com" and recursively copy directory "/path/to/foo" on this host to direcotry "/home/user/Desktop" on local host, using "blowfish" cipher algorithm.
scp -c blowfish -r user@your.server.example.com:/path/to/foo /home/user/Desktop/
['scp']
Output a Bash command to accomplish the following task. Task: Connect via ssh to "your.server.example.com" and recursively copy directory "/path/to/foo" on this host to direcotry "/home/user/Desktop" on local host, using "blowfish" cipher algorithm. Bash Command:<START>scp -c blowfish -r user@your.server.example.com:/path/to/foo /home/user/Desktop/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # scp\n\n> Secure copy.\n> Copy files between hosts using Secure Copy Protocol over SSH.\n> More information: <https://man.openbsd.org/scp>.\n\n- Copy a local file to a remote host:\n\n`scp {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific port when connecting to the remote host:\n\n`scp -P {{port}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Copy a file from a remote host to a local directory:\n\n`scp {{remote_host}}:{{path/to/remote_file}} {{path/to/local_directory}}`\n\n- Recursively copy the contents of a directory from a remote host to a local directory:\n\n`scp -r {{remote_host}}:{{path/to/remote_directory}} {{path/to/local_directory}}`\n\n- Copy a file between two remote hosts transferring through the local host:\n\n`scp -3 {{host1}}:{{path/to/remote_file}} {{host2}}:{{path/to/remote_directory}}`\n\n- Use a specific username when connecting to the remote host:\n\n`scp {{path/to/local_file}} {{remote_username}}@{{remote_host}}:{{path/to/remote_directory}}`\n\n- Use a specific SSH private key for authentication with the remote host:\n\n`scp -i {{~/.ssh/private_key}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n\n- Use a specific proxy when connecting to the remote host:\n\n`scp -J {{proxy_username}}@{{proxy_host}} {{path/to/local_file}} {{remote_host}}:{{path/to/remote_file}}`\n Task: Connect via ssh to "your.server.example.com" and recursively copy directory "/path/to/foo" on this host to direcotry "/home/user/Desktop" on local host, using "blowfish" cipher algorithm. Bash Command:<START>scp -c blowfish -r user@your.server.example.com:/path/to/foo /home/user/Desktop/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: scp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training scp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXIT STATUS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | COLOPHON SCP(1) General Commands Manual SCP(1) NAME top scp OpenSSH secure file copy SYNOPSIS top scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] [-X sftp_option] source ... target DESCRIPTION top copies files between hosts on a network. uses the SFTP protocol over a ssh(1) connection for data transfer, and uses the same authentication and provides the same security as a login session. will ask for passwords or passphrases if they are needed for authentication. The source and target may be specified as a local pathname, a remote host with optional path in the form [user@]host:[path], or a URI in the form scp://[user@]host[:port][/path]. Local file names can be made explicit using absolute or relative pathnames to avoid treating file names containing : as host specifiers. When copying between two remote hosts, if the URI format is used, a port cannot be specified on the target if the -R option is used. The options are as follows: -3 Copies between two remote hosts are transferred through the local host. Without this option the data is copied directly between the two remote hosts. Note that, when using the legacy SCP protocol (via the -O flag), this option selects batch mode for the second host as cannot ask for passwords or passphrases for both hosts. This mode is the default. -4 Forces to use IPv4 addresses only. -6 Forces to use IPv6 addresses only. -A Allows forwarding of ssh-agent(1) to the remote system. The default is not to forward an authentication agent. -B Selects batch mode (prevents asking for passwords or passphrases). -C Compression enable. Passes the -C flag to ssh(1) to enable compression. -c cipher Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1). -D sftp_server_path Connect directly to a local SFTP server program rather than a remote one via ssh(1). This option may be useful in debugging the client and server. -F ssh_config Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh(1). -i identity_file Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh(1). -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. This option is directly passed to ssh(1). -l limit Limits the used bandwidth, specified in Kbit/s. -O Use the legacy SCP protocol for file transfers instead of the SFTP protocol. Forcing the use of the SCP protocol may be necessary for servers that do not implement SFTP, for backwards-compatibility for particular filename wildcard patterns and for expanding paths with a ~ prefix for older SFTP servers. -o ssh_option Can be used to pass options to ssh in the format used in ssh_config(5). This is useful for specifying options for which there is no separate scp command-line flag. For full details of the options listed below, and their possible values, see ssh_config(5). AddressFamily BatchMode BindAddress BindInterface CanonicalDomains CanonicalizeFallbackLocal CanonicalizeHostname CanonicalizeMaxDots CanonicalizePermittedCNAMEs CASignatureAlgorithms CertificateFile CheckHostIP Ciphers Compression ConnectionAttempts ConnectTimeout ControlMaster ControlPath ControlPersist GlobalKnownHostsFile GSSAPIAuthentication GSSAPIDelegateCredentials HashKnownHosts Host HostbasedAcceptedAlgorithms HostbasedAuthentication HostKeyAlgorithms HostKeyAlias Hostname IdentitiesOnly IdentityAgent IdentityFile IPQoS KbdInteractiveAuthentication KbdInteractiveDevices KexAlgorithms KnownHostsCommand LogLevel MACs NoHostAuthenticationForLocalhost NumberOfPasswordPrompts PasswordAuthentication PKCS11Provider Port PreferredAuthentications ProxyCommand ProxyJump PubkeyAcceptedAlgorithms PubkeyAuthentication RekeyLimit RequiredRSASize SendEnv ServerAliveInterval ServerAliveCountMax SetEnv StrictHostKeyChecking TCPKeepAlive UpdateHostKeys User UserKnownHostsFile VerifyHostKeyDNS -P port Specifies the port to connect to on the remote host. Note that this option is written with a capital P, because -p is already reserved for preserving the times and mode bits of the file. -p Preserves modification times, access times, and file mode bits from the source file. -q Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1). -R Copies between two remote hosts are performed by connecting to the origin host and executing there. This requires that running on the origin host can authenticate to the destination host without requiring a password. -r Recursively copy entire directories. Note that follows symbolic links encountered in the tree traversal. -S program Name of program to use for the encrypted connection. The program must understand ssh(1) options. -T Disable strict filename checking. By default when copying files from a remote host to a local directory checks that the received filenames match those requested on the command-line to prevent the remote end from sending unexpected or unwanted files. Because of differences in how various operating systems and shells interpret filename wildcards, these checks may cause wanted files to be rejected. This option disables these checks at the expense of fully trusting that the server will not send unexpected filenames. -v Verbose mode. Causes and ssh(1) to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems. -X sftp_option Specify an option that controls aspects of SFTP protocol behaviour. The valid options are: nrequests=value Controls how many concurrent SFTP read or write requests may be in progress at any point in time during a download or upload. By default 64 requests may be active concurrently. buffer=value Controls the maximum buffer size for a single SFTP read/write operation used during download or upload. By default a 32KB buffer is used. EXIT STATUS top The scp utility exits 0 on success, and >0 if an error occurs. SEE ALSO top sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh_config(5), sftp-server(8), sshd(8) HISTORY top is based on the rcp program in BSD source code from the Regents of the University of California. Since OpenSSH 9.0, has used the SFTP protocol for transfers by default. AUTHORS top Timo Rinne <tri@iki.fi> Tatu Ylonen <ylo@cs.hut.fi> CAVEATS top The legacy SCP protocol (selected by the -O flag) requires execution of the remote user's shell to perform glob(3) pattern matching. This requires careful quoting of any characters that have special meaning to the remote shell, such as quote characters. 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 December 16, 2022 SCP(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: Connect via ssh to "your.server.example.com" and recursively copy directory "/path/to/foo" on this host to direcotry "/home/user/Desktop" on local host, using "blowfish" cipher algorithm. Bash Command:<START>scp -c blowfish -r user@your.server.example.com:/path/to/foo /home/user/Desktop/<END>
Continuously answer "y" to any prompt from "mv ..."
yes | mv ...
['yes', 'mv']
Output a Bash command to accomplish the following task. Task: Continuously answer "y" to any prompt from "mv ..." Bash Command:<START>yes | mv ...<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # yes\n\n> Output something repeatedly.\n> This command is commonly used to answer yes to every prompt by install commands (such as apt-get).\n> More information: <https://www.gnu.org/software/coreutils/yes>.\n\n- Repeatedly output "message":\n\n`yes {{message}}`\n\n- Repeatedly output "y":\n\n`yes`\n\n- Accept everything prompted by the `apt-get` command:\n\n`yes | sudo apt-get install {{program}}`\n\n- Repeatedly output a newline to always accept the default option of a prompt:\n\n`yes ''`\n # mv\n\n> Move or rename files and directories.\n> More information: <https://www.gnu.org/software/coreutils/mv>.\n\n- Rename a file or directory when the target is not an existing directory:\n\n`mv {{path/to/source}} {{path/to/target}}`\n\n- Move a file or directory into an existing directory:\n\n`mv {{path/to/source}} {{path/to/existing_directory}}`\n\n- Move multiple files into an existing directory, keeping the filenames unchanged:\n\n`mv {{path/to/source1 path/to/source2 ...}} {{path/to/existing_directory}}`\n\n- Do not prompt for confirmation before overwriting existing files:\n\n`mv -f {{path/to/source}} {{path/to/target}}`\n\n- Prompt for confirmation before overwriting existing files, regardless of file permissions:\n\n`mv -i {{path/to/source}} {{path/to/target}}`\n\n- Do not overwrite existing files at the target:\n\n`mv -n {{path/to/source}} {{path/to/target}}`\n\n- Move files in verbose mode, showing files after they are moved:\n\n`mv -v {{path/to/source}} {{path/to/target}}`\n Task: Continuously answer "y" to any prompt from "mv ..." Bash Command:<START>yes | mv ...<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: yes(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training yes(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON YES(1) User Commands YES(1) NAME top yes - output a string repeatedly until killed SYNOPSIS top yes [STRING]... yes OPTION DESCRIPTION top Repeatedly output a line with all specified STRING(s), or 'y'. --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 Full documentation <https://www.gnu.org/software/coreutils/yes> or available locally via: info '(coreutils) yes 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 YES(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. mv(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training mv(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON MV(1) User Commands MV(1) NAME top mv - move (rename) files SYNOPSIS top mv [OPTION]... [-T] SOURCE DEST mv [OPTION]... SOURCE... DIRECTORY mv [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --debug explain how a file is copied. Implies -v -f, --force do not prompt before overwriting -i, --interactive prompt before overwrite -n, --no-clobber do not overwrite an existing file If you specify more than one of -i, -f, -n, only the final one takes effect. --no-copy do not copy if renaming fails --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -Z, --context set SELinux security context of destination file to default type --help display this help and exit --version output version information and exit UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups AUTHOR top Written by Mike Parker, 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 rename(2) Full documentation <https://www.gnu.org/software/coreutils/mv> or available locally via: info '(coreutils) mv 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 MV(1) Pages that refer to this page: rename(1), sshfs(1), rename(2), inotify(7), symlink(7), 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: Continuously answer "y" to any prompt from "mv ..." Bash Command:<START>yes | mv ...<END>
Continuously convert "20131202" into "2013 12 02" and print the result
yes a=\"20131202\" | sed -e :a -e 's/...\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)./\1 \2 \3/'
['sed', 'yes']
Output a Bash command to accomplish the following task. Task: Continuously convert "20131202" into "2013 12 02" and print the result Bash Command:<START>yes a=\"20131202\" | sed -e :a -e 's/...\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)./\1 \2 \3/'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # yes\n\n> Output something repeatedly.\n> This command is commonly used to answer yes to every prompt by install commands (such as apt-get).\n> More information: <https://www.gnu.org/software/coreutils/yes>.\n\n- Repeatedly output "message":\n\n`yes {{message}}`\n\n- Repeatedly output "y":\n\n`yes`\n\n- Accept everything prompted by the `apt-get` command:\n\n`yes | sudo apt-get install {{program}}`\n\n- Repeatedly output a newline to always accept the default option of a prompt:\n\n`yes ''`\n Task: Continuously convert "20131202" into "2013 12 02" and print the result Bash Command:<START>yes a=\"20131202\" | sed -e :a -e 's/...\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)./\1 \2 \3/'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. yes(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training yes(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON YES(1) User Commands YES(1) NAME top yes - output a string repeatedly until killed SYNOPSIS top yes [STRING]... yes OPTION DESCRIPTION top Repeatedly output a line with all specified STRING(s), or 'y'. --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 Full documentation <https://www.gnu.org/software/coreutils/yes> or available locally via: info '(coreutils) yes 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 YES(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: Continuously convert "20131202" into "2013 12 02" and print the result Bash Command:<START>yes a=\"20131202\" | sed -e :a -e 's/...\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)./\1 \2 \3/'<END>
Continuously print the seconds since Unix epoch and the ping time to "google.com"
ping google.com | awk -F'[ =]' 'NR>1{print system("echo -n $(date +%s)"), $11}'
['awk', 'ping']
Output a Bash command to accomplish the following task. Task: Continuously print the seconds since Unix epoch and the ping time to "google.com" Bash Command:<START>ping google.com | awk -F'[ =]' 'NR>1{print system("echo -n $(date +%s)"), $11}'<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 # 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: Continuously print the seconds since Unix epoch and the ping time to "google.com" Bash Command:<START>ping google.com | awk -F'[ =]' 'NR>1{print system("echo -n $(date +%s)"), $11}'<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. 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: Continuously print the seconds since Unix epoch and the ping time to "google.com" Bash Command:<START>ping google.com | awk -F'[ =]' 'NR>1{print system("echo -n $(date +%s)"), $11}'<END>
Continuously send "y" as input to "cat" which outputs to "more"
yes | cat | more
['yes', 'cat', 'more']
Output a Bash command to accomplish the following task. Task: Continuously send "y" as input to "cat" which outputs to "more" Bash Command:<START>yes | cat | more<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # yes\n\n> Output something repeatedly.\n> This command is commonly used to answer yes to every prompt by install commands (such as apt-get).\n> More information: <https://www.gnu.org/software/coreutils/yes>.\n\n- Repeatedly output "message":\n\n`yes {{message}}`\n\n- Repeatedly output "y":\n\n`yes`\n\n- Accept everything prompted by the `apt-get` command:\n\n`yes | sudo apt-get install {{program}}`\n\n- Repeatedly output a newline to always accept the default option of a prompt:\n\n`yes ''`\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 # more\n\n> Interactively display a file, allowing scrolling and searching.\n> See also: `less`.\n> More information: <https://manned.org/more>.\n\n- Open a file:\n\n`more {{path/to/file}}`\n\n- Display a specific line:\n\n`more +{{line_number}} {{path/to/file}}`\n\n- Go to the next page:\n\n`<Space>`\n\n- Search for a string (press `n` to go to the next match):\n\n`/{{something}}`\n\n- Exit:\n\n`q`\n\n- Display help about interactive commands:\n\n`h`\n Task: Continuously send "y" as input to "cat" which outputs to "more" Bash Command:<START>yes | cat | more<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: yes(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training yes(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON YES(1) User Commands YES(1) NAME top yes - output a string repeatedly until killed SYNOPSIS top yes [STRING]... yes OPTION DESCRIPTION top Repeatedly output a line with all specified STRING(s), or 'y'. --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 Full documentation <https://www.gnu.org/software/coreutils/yes> or available locally via: info '(coreutils) yes 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 YES(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. 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. more(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training more(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | COMMANDS | ENVIRONMENT | HISTORY | AUTHORS | SEE ALSO | REPORTING BUGS | AVAILABILITY MORE(1) User Commands MORE(1) NAME top more - display the contents of a file in a terminal SYNOPSIS top more [options] file ... DESCRIPTION top more is a filter for paging through text one screenful at a time. This version is especially primitive. Users should realize that less(1) provides more(1) emulation plus extensive enhancements. OPTIONS top Options are also taken from the environment variable MORE (make sure to precede them with a dash (-)) but command-line options will override those. -d, --silent Prompt with "[Press space to continue, 'q' to quit.]", and display "[Press 'h' for instructions.]" instead of ringing the bell when an illegal key is pressed. -l, --logical Do not pause after any line containing a ^L (form feed). -e, --exit-on-eof Exit on End-Of-File, enabled by default if POSIXLY_CORRECT environment variable is not set or if not executed on terminal. -f, --no-pause Count logical lines, rather than screen lines (i.e., long lines are not folded). -p, --print-over Do not scroll. Instead, clear the whole screen and then display the text. Notice that this option is switched on automatically if the executable is named page. -c, --clean-print Do not scroll. Instead, paint each screen from the top, clearing the remainder of each line as it is displayed. -s, --squeeze Squeeze multiple blank lines into one. -u, --plain Suppress underlining. This option is silently ignored as backwards compatibility. -n, --lines number Specify the number of lines per screenful. The number argument is a positive decimal integer. The --lines option shall override any values obtained from any other source, such as number of lines reported by terminal. -number A numeric option means the same as --lines option argument. +number Start displaying each file at line number. +/string The string to be searched in each file before starting to display it. -h, --help Display help text and exit. -V, --version Print version and exit. COMMANDS top Interactive commands for more are based on vi(1). Some commands may be preceded by a decimal number, called k in the descriptions below. In the following descriptions, ^X means control-X. h or ? Help; display a summary of these commands. If you forget all other commands, remember this one. SPACE Display next k lines of text. Defaults to current screen size. z Display next k lines of text. Defaults to current screen size. Argument becomes new default. RETURN Display next k lines of text. Defaults to 1. Argument becomes new default. d or ^D Scroll k lines. Default is current scroll size, initially 11. Argument becomes new default. q or Q or INTERRUPT Exit. s Skip forward k lines of text. Defaults to 1. f Skip forward k screenfuls of text. Defaults to 1. b or ^B Skip backwards k screenfuls of text. Defaults to 1. Only works with files, not pipes. ' Go to the place where the last search started. = Display current line number. /pattern Search for kth occurrence of regular expression. Defaults to 1. n Search for kth occurrence of last regular expression. Defaults to 1. !command or :!command Execute command in a subshell. v Start up an editor at current line. The editor is taken from the environment variable VISUAL if defined, or EDITOR if VISUAL is not defined, or defaults to vi(1) if neither VISUAL nor EDITOR is defined. ^L Redraw screen. :n Go to kth next file. Defaults to 1. :p Go to kth previous file. Defaults to 1. :f Display current file name and line number. . Repeat previous command. ENVIRONMENT top The more command respects the following environment variables, if they exist: MORE This variable may be set with favored options to more. SHELL Current shell in use (normally set by the shell at login time). TERM The terminal type used by more to get the terminal characteristics necessary to manipulate the screen. VISUAL The editor the user prefers. Invoked when command key v is pressed. EDITOR The editor of choice when VISUAL is not specified. POSIXLY_CORRECT Disable exit-on-eof (see option -e for more details). HISTORY top The more command appeared in 3.0BSD. This man page documents more version 5.19 (Berkeley 6/29/88), which is currently in use in the Linux community. Documentation was produced using several other versions of the man page, and extensive inspection of the source code. AUTHORS top Eric Shienbrood, UC Berkeley. Modified by Geoff Peck, UCB to add underlining, single spacing. Modified by John Foderaro, UCB to add -c and MORE environment variable. SEE ALSO top less(1), vi(1) REPORTING BUGS top For bug reports, use the issue tracker at https://github.com/util-linux/util-linux/issues. AVAILABILITY top The more 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 MORE(1) Pages that refer to this page: colcrt(1), homectl(1), journalctl(1), less(1), localectl(1), loginctl(1), machinectl(1), more(1), portablectl(1), systemctl(1), systemd(1), systemd-analyze(1), systemd-inhibit(1), systemd-nspawn(1), systemd-vmspawn(1), timedatectl(1), userdbctl(1), environ(7), systemd-tmpfiles(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: Continuously send "y" as input to "cat" which outputs to "more" Bash Command:<START>yes | cat | more<END>
Continuously send "y" to all prompts of command "rm"
yes | rm
['yes', 'rm']
Output a Bash command to accomplish the following task. Task: Continuously send "y" to all prompts of command "rm" Bash Command:<START>yes | rm<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # yes\n\n> Output something repeatedly.\n> This command is commonly used to answer yes to every prompt by install commands (such as apt-get).\n> More information: <https://www.gnu.org/software/coreutils/yes>.\n\n- Repeatedly output "message":\n\n`yes {{message}}`\n\n- Repeatedly output "y":\n\n`yes`\n\n- Accept everything prompted by the `apt-get` command:\n\n`yes | sudo apt-get install {{program}}`\n\n- Repeatedly output a newline to always accept the default option of a prompt:\n\n`yes ''`\n # rm\n\n> Remove files or directories.\n> See also: `rmdir`.\n> More information: <https://www.gnu.org/software/coreutils/rm>.\n\n- Remove specific files:\n\n`rm {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files ignoring nonexistent ones:\n\n`rm --force {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files interactively prompting before each removal:\n\n`rm --interactive {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files printing info about each removal:\n\n`rm --verbose {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files and directories recursively:\n\n`rm --recursive {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n Task: Continuously send "y" to all prompts of command "rm" Bash Command:<START>yes | rm<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: yes(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training yes(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON YES(1) User Commands YES(1) NAME top yes - output a string repeatedly until killed SYNOPSIS top yes [STRING]... yes OPTION DESCRIPTION top Repeatedly output a line with all specified STRING(s), or 'y'. --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 Full documentation <https://www.gnu.org/software/coreutils/yes> or available locally via: info '(coreutils) yes 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 YES(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. rm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON RM(1) User Commands RM(1) NAME top rm - remove files or directories SYNOPSIS top rm [OPTION]... [FILE]... DESCRIPTION top This manual page documents the GNU version of rm. rm removes each specified file. By default, it does not remove directories. If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted. Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped. OPTIONS top Remove (unlink) the FILE(s). -f, --force ignore nonexistent files and arguments, never prompt -i prompt before every removal -I prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes --interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always --one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument --no-preserve-root do not treat '/' specially --preserve-root[=all] do not remove '/' (default); with 'all', reject any command line argument on a separate device from its parent -r, -R, --recursive remove directories and their contents recursively -d, --dir remove empty directories -v, --verbose explain what is being done --help display this help and exit --version output version information and exit By default, rm does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents. To remove a file whose name starts with a '-', for example '-foo', use one of these commands: rm -- -foo rm ./-foo Note that if you use rm to remove a file, it might be possible to recover some of its contents, given sufficient expertise and/or time. For greater assurance that the contents are truly unrecoverable, consider using shred(1). AUTHOR top Written by Paul Rubin, David MacKenzie, Richard M. Stallman, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top unlink(1), unlink(2), chattr(1), shred(1) Full documentation <https://www.gnu.org/software/coreutils/rm> or available locally via: info '(coreutils) rm invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 RM(1) Pages that refer to this page: rmdir(2), unlink(2), remove(3), mq_overview(7), symlink(7), debugfs(8), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Continuously send "y" to all prompts of command "rm" Bash Command:<START>yes | rm<END>
Convert "1199092913" to dotted decimal IPv4 address
ping -c1 1199092913 | head -n1 | grep -Eow "[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+"
['head', 'grep', 'ping']
Output a Bash command to accomplish the following task. Task: Convert "1199092913" to dotted decimal IPv4 address Bash Command:<START>ping -c1 1199092913 | head -n1 | grep -Eow "[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # 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 # 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: Convert "1199092913" to dotted decimal IPv4 address Bash Command:<START>ping -c1 1199092913 | head -n1 | grep -Eow "[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. 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. 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: Convert "1199092913" to dotted decimal IPv4 address Bash Command:<START>ping -c1 1199092913 | head -n1 | grep -Eow "[0-9]+[.][0-9]+[.][0-9]+[.][0-9]+"<END>
Convert "595a" into characters and then print the hexadecimal and printable characters of each byte
echo 595a | awk -niord '$0=chr("0x"RT)' RS=.. ORS= | od -tx1c
['od', 'awk', 'echo']
Output a Bash command to accomplish the following task. Task: Convert "595a" into characters and then print the hexadecimal and printable characters of each byte Bash Command:<START>echo 595a | awk -niord '$0=chr("0x"RT)' RS=.. ORS= | od -tx1c<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # od\n\n> Display file contents in octal, decimal or hexadecimal format.\n> Optionally display the byte offsets and/or printable representation for each line.\n> More information: <https://www.gnu.org/software/coreutils/od>.\n\n- Display file using default settings: octal format, 8 bytes per line, byte offsets in octal, and duplicate lines replaced with `*`:\n\n`od {{path/to/file}}`\n\n- Display file in verbose mode, i.e. without replacing duplicate lines with `*`:\n\n`od -v {{path/to/file}}`\n\n- Display file in hexadecimal format (2-byte units), with byte offsets in decimal format:\n\n`od --format={{x}} --address-radix={{d}} -v {{path/to/file}}`\n\n- Display file in hexadecimal format (1-byte units), and 4 bytes per line:\n\n`od --format={{x1}} --width={{4}} -v {{path/to/file}}`\n\n- Display file in hexadecimal format along with its character representation, and do not print byte offsets:\n\n`od --format={{xz}} --address-radix={{n}} -v {{path/to/file}}`\n\n- Read only 100 bytes of a file starting from the 500th byte:\n\n`od --read-bytes {{100}} --skip-bytes={{500}} -v {{path/to/file}}`\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 # 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: Convert "595a" into characters and then print the hexadecimal and printable characters of each byte Bash Command:<START>echo 595a | awk -niord '$0=chr("0x"RT)' RS=.. ORS= | od -tx1c<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: od(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training od(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON OD(1) User Commands OD(1) NAME top od - dump files in octal and other formats SYNOPSIS top od [OPTION]... [FILE]... od [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]] od --traditional [OPTION]... [FILE] [[+]OFFSET[.][b] [+][LABEL][.][b]] DESCRIPTION top Write an unambiguous representation, octal bytes by default, of FILE to standard output. With more than one FILE argument, concatenate them in the listed order to form the input. With no FILE, or when FILE is -, read standard input. If first and second call formats both apply, the second format is assumed if the last operand begins with + or (if there are 2 operands) a digit. An OFFSET operand means -j OFFSET. LABEL is the pseudo-address at first byte printed, incremented when dump is progressing. For OFFSET and LABEL, a 0x or 0X prefix indicates hexadecimal; suffixes may be . for octal and b for multiply by 512. Mandatory arguments to long options are mandatory for short options too. -A, --address-radix=RADIX output format for file offsets; RADIX is one of [doxn], for Decimal, Octal, Hex or None --endian={big|little} swap input bytes according the specified order -j, --skip-bytes=BYTES skip BYTES input bytes first -N, --read-bytes=BYTES limit dump to BYTES input bytes -S BYTES, --strings[=BYTES] show only NUL terminated strings of at least BYTES (3) printable characters -t, --format=TYPE select output format or formats -v, --output-duplicates do not use * to mark line suppression -w[BYTES], --width[=BYTES] output BYTES bytes per output line; 32 is implied when BYTES is not specified --traditional accept arguments in third form above --help display this help and exit --version output version information and exit Traditional format specifications may be intermixed; they accumulate: -a same as -t a, select named characters, ignoring high-order bit -b same as -t o1, select octal bytes -c same as -t c, select printable characters or backslash escapes -d same as -t u2, select unsigned decimal 2-byte units -f same as -t fF, select floats -i same as -t dI, select decimal ints -l same as -t dL, select decimal longs -o same as -t o2, select octal 2-byte units -s same as -t d2, select decimal 2-byte units -x same as -t x2, select hexadecimal 2-byte units TYPE is made up of one or more of these specifications: a named character, ignoring high-order bit c printable character or backslash escape d[SIZE] signed decimal, SIZE bytes per integer f[SIZE] floating point, SIZE bytes per float o[SIZE] octal, SIZE bytes per integer u[SIZE] unsigned decimal, SIZE bytes per integer x[SIZE] hexadecimal, SIZE bytes per integer SIZE is a number. For TYPE in [doux], SIZE may also be C for sizeof(char), S for sizeof(short), I for sizeof(int) or L for sizeof(long). If TYPE is f, SIZE may also be F for sizeof(float), D for sizeof(double) or L for sizeof(long double). Adding a z suffix to any type displays printable characters at the end of each output line. BYTES is hex with 0x or 0X prefix, and may have a multiplier suffix: b 512 KB 1000 K 1024 MB 1000*1000 M 1024*1024 and so on for G, T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. EXAMPLES top od -A x -t x1z -v Display hexdump format output od -A o -t oS -w16 The default output format used by od 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 Full documentation <https://www.gnu.org/software/coreutils/od> or available locally via: info '(coreutils) od 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 OD(1) Pages that refer to this page: scr_dump(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. 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. 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: Convert "595a" into characters and then print the hexadecimal and printable characters of each byte Bash Command:<START>echo 595a | awk -niord '$0=chr("0x"RT)' RS=.. ORS= | od -tx1c<END>
Convert ";" separated list "luke;yoda;leila" to new line separated list
echo "luke;yoda;leila" | tr ";" "\n"
['tr', 'echo']
Output a Bash command to accomplish the following task. Task: Convert ";" separated list "luke;yoda;leila" to new line separated list Bash Command:<START>echo "luke;yoda;leila" | tr ";" "\n"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # tr\n\n> Translate characters: run replacements based on single characters and character sets.\n> More information: <https://www.gnu.org/software/coreutils/tr>.\n\n- Replace all occurrences of a character in a file, and print the result:\n\n`tr {{find_character}} {{replace_character}} < {{path/to/file}}`\n\n- Replace all occurrences of a character from another command's output:\n\n`echo {{text}} | tr {{find_character}} {{replace_character}}`\n\n- Map each character of the first set to the corresponding character of the second set:\n\n`tr '{{abcd}}' '{{jkmn}}' < {{path/to/file}}`\n\n- Delete all occurrences of the specified set of characters from the input:\n\n`tr -d '{{input_characters}}' < {{path/to/file}}`\n\n- Compress a series of identical characters to a single character:\n\n`tr -s '{{input_characters}}' < {{path/to/file}}`\n\n- Translate the contents of a file to upper-case:\n\n`tr "[:lower:]" "[:upper:]" < {{path/to/file}}`\n\n- Strip out non-printable characters from a file:\n\n`tr -cd "[:print:]" < {{path/to/file}}`\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: Convert ";" separated list "luke;yoda;leila" to new line separated list Bash Command:<START>echo "luke;yoda;leila" | tr ";" "\n"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: tr(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tr(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | BUGS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TR(1) User Commands TR(1) NAME top tr - translate or delete characters SYNOPSIS top tr [OPTION]... STRING1 [STRING2] DESCRIPTION top Translate, squeeze, and/or delete characters from standard input, writing to standard output. STRING1 and STRING2 specify arrays of characters ARRAY1 and ARRAY2 that control the action. -c, -C, --complement use the complement of ARRAY1 -d, --delete delete characters in ARRAY1, do not translate -s, --squeeze-repeats replace each sequence of a repeated character that is listed in the last specified ARRAY, with a single occurrence of that character -t, --truncate-set1 first truncate ARRAY1 to length of ARRAY2 --help display this help and exit --version output version information and exit ARRAYs are specified as strings of characters. Most represent themselves. Interpreted sequences are: \NNN character with octal value NNN (1 to 3 octal digits) \\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab \v vertical tab CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in ARRAY2, copies of CHAR until length of ARRAY1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [:alnum:] all letters and digits [:alpha:] all letters [:blank:] all horizontal whitespace [:cntrl:] all control characters [:digit:] all digits [:graph:] all printable characters, not including space [:lower:] all lower case letters [:print:] all printable characters, including space [:punct:] all punctuation characters [:space:] all horizontal or vertical whitespace [:upper:] all upper case letters [:xdigit:] all hexadecimal digits [=CHAR=] all characters which are equivalent to CHAR Translation occurs if -d is not given and both STRING1 and STRING2 appear. -t is only significant when translating. ARRAY2 is extended to length of ARRAY1 by repeating its last character as necessary. Excess characters of ARRAY2 are ignored. Character classes expand in unspecified order; while translating, [:lower:] and [:upper:] may be used in pairs to specify case conversion. Squeezing occurs after translation or deletion. BUGS top Full support is available only for safe single-byte locales, in which every possible input byte represents a single character. The C locale is safe in GNU systems, so you can avoid this issue in the shell by running LC_ALL=C tr instead of plain tr. 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 Full documentation <https://www.gnu.org/software/coreutils/tr> or available locally via: info '(coreutils) tr 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 TR(1) Pages that refer to this page: sed(1), 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. 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: Convert ";" separated list "luke;yoda;leila" to new line separated list Bash Command:<START>echo "luke;yoda;leila" | tr ";" "\n"<END>
Convert "abc" to a string of hexadecimal bytes
echo abc | od -A n -v -t x1 | tr -d ' \n'
['tr', 'od', 'echo']
Output a Bash command to accomplish the following task. Task: Convert "abc" to a string of hexadecimal bytes Bash Command:<START>echo abc | od -A n -v -t x1 | tr -d ' \n'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # tr\n\n> Translate characters: run replacements based on single characters and character sets.\n> More information: <https://www.gnu.org/software/coreutils/tr>.\n\n- Replace all occurrences of a character in a file, and print the result:\n\n`tr {{find_character}} {{replace_character}} < {{path/to/file}}`\n\n- Replace all occurrences of a character from another command's output:\n\n`echo {{text}} | tr {{find_character}} {{replace_character}}`\n\n- Map each character of the first set to the corresponding character of the second set:\n\n`tr '{{abcd}}' '{{jkmn}}' < {{path/to/file}}`\n\n- Delete all occurrences of the specified set of characters from the input:\n\n`tr -d '{{input_characters}}' < {{path/to/file}}`\n\n- Compress a series of identical characters to a single character:\n\n`tr -s '{{input_characters}}' < {{path/to/file}}`\n\n- Translate the contents of a file to upper-case:\n\n`tr "[:lower:]" "[:upper:]" < {{path/to/file}}`\n\n- Strip out non-printable characters from a file:\n\n`tr -cd "[:print:]" < {{path/to/file}}`\n # od\n\n> Display file contents in octal, decimal or hexadecimal format.\n> Optionally display the byte offsets and/or printable representation for each line.\n> More information: <https://www.gnu.org/software/coreutils/od>.\n\n- Display file using default settings: octal format, 8 bytes per line, byte offsets in octal, and duplicate lines replaced with `*`:\n\n`od {{path/to/file}}`\n\n- Display file in verbose mode, i.e. without replacing duplicate lines with `*`:\n\n`od -v {{path/to/file}}`\n\n- Display file in hexadecimal format (2-byte units), with byte offsets in decimal format:\n\n`od --format={{x}} --address-radix={{d}} -v {{path/to/file}}`\n\n- Display file in hexadecimal format (1-byte units), and 4 bytes per line:\n\n`od --format={{x1}} --width={{4}} -v {{path/to/file}}`\n\n- Display file in hexadecimal format along with its character representation, and do not print byte offsets:\n\n`od --format={{xz}} --address-radix={{n}} -v {{path/to/file}}`\n\n- Read only 100 bytes of a file starting from the 500th byte:\n\n`od --read-bytes {{100}} --skip-bytes={{500}} -v {{path/to/file}}`\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: Convert "abc" to a string of hexadecimal bytes Bash Command:<START>echo abc | od -A n -v -t x1 | tr -d ' \n'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: tr(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tr(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | BUGS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TR(1) User Commands TR(1) NAME top tr - translate or delete characters SYNOPSIS top tr [OPTION]... STRING1 [STRING2] DESCRIPTION top Translate, squeeze, and/or delete characters from standard input, writing to standard output. STRING1 and STRING2 specify arrays of characters ARRAY1 and ARRAY2 that control the action. -c, -C, --complement use the complement of ARRAY1 -d, --delete delete characters in ARRAY1, do not translate -s, --squeeze-repeats replace each sequence of a repeated character that is listed in the last specified ARRAY, with a single occurrence of that character -t, --truncate-set1 first truncate ARRAY1 to length of ARRAY2 --help display this help and exit --version output version information and exit ARRAYs are specified as strings of characters. Most represent themselves. Interpreted sequences are: \NNN character with octal value NNN (1 to 3 octal digits) \\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab \v vertical tab CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in ARRAY2, copies of CHAR until length of ARRAY1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [:alnum:] all letters and digits [:alpha:] all letters [:blank:] all horizontal whitespace [:cntrl:] all control characters [:digit:] all digits [:graph:] all printable characters, not including space [:lower:] all lower case letters [:print:] all printable characters, including space [:punct:] all punctuation characters [:space:] all horizontal or vertical whitespace [:upper:] all upper case letters [:xdigit:] all hexadecimal digits [=CHAR=] all characters which are equivalent to CHAR Translation occurs if -d is not given and both STRING1 and STRING2 appear. -t is only significant when translating. ARRAY2 is extended to length of ARRAY1 by repeating its last character as necessary. Excess characters of ARRAY2 are ignored. Character classes expand in unspecified order; while translating, [:lower:] and [:upper:] may be used in pairs to specify case conversion. Squeezing occurs after translation or deletion. BUGS top Full support is available only for safe single-byte locales, in which every possible input byte represents a single character. The C locale is safe in GNU systems, so you can avoid this issue in the shell by running LC_ALL=C tr instead of plain tr. 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 Full documentation <https://www.gnu.org/software/coreutils/tr> or available locally via: info '(coreutils) tr 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 TR(1) Pages that refer to this page: sed(1), 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. od(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training od(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON OD(1) User Commands OD(1) NAME top od - dump files in octal and other formats SYNOPSIS top od [OPTION]... [FILE]... od [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]] od --traditional [OPTION]... [FILE] [[+]OFFSET[.][b] [+][LABEL][.][b]] DESCRIPTION top Write an unambiguous representation, octal bytes by default, of FILE to standard output. With more than one FILE argument, concatenate them in the listed order to form the input. With no FILE, or when FILE is -, read standard input. If first and second call formats both apply, the second format is assumed if the last operand begins with + or (if there are 2 operands) a digit. An OFFSET operand means -j OFFSET. LABEL is the pseudo-address at first byte printed, incremented when dump is progressing. For OFFSET and LABEL, a 0x or 0X prefix indicates hexadecimal; suffixes may be . for octal and b for multiply by 512. Mandatory arguments to long options are mandatory for short options too. -A, --address-radix=RADIX output format for file offsets; RADIX is one of [doxn], for Decimal, Octal, Hex or None --endian={big|little} swap input bytes according the specified order -j, --skip-bytes=BYTES skip BYTES input bytes first -N, --read-bytes=BYTES limit dump to BYTES input bytes -S BYTES, --strings[=BYTES] show only NUL terminated strings of at least BYTES (3) printable characters -t, --format=TYPE select output format or formats -v, --output-duplicates do not use * to mark line suppression -w[BYTES], --width[=BYTES] output BYTES bytes per output line; 32 is implied when BYTES is not specified --traditional accept arguments in third form above --help display this help and exit --version output version information and exit Traditional format specifications may be intermixed; they accumulate: -a same as -t a, select named characters, ignoring high-order bit -b same as -t o1, select octal bytes -c same as -t c, select printable characters or backslash escapes -d same as -t u2, select unsigned decimal 2-byte units -f same as -t fF, select floats -i same as -t dI, select decimal ints -l same as -t dL, select decimal longs -o same as -t o2, select octal 2-byte units -s same as -t d2, select decimal 2-byte units -x same as -t x2, select hexadecimal 2-byte units TYPE is made up of one or more of these specifications: a named character, ignoring high-order bit c printable character or backslash escape d[SIZE] signed decimal, SIZE bytes per integer f[SIZE] floating point, SIZE bytes per float o[SIZE] octal, SIZE bytes per integer u[SIZE] unsigned decimal, SIZE bytes per integer x[SIZE] hexadecimal, SIZE bytes per integer SIZE is a number. For TYPE in [doux], SIZE may also be C for sizeof(char), S for sizeof(short), I for sizeof(int) or L for sizeof(long). If TYPE is f, SIZE may also be F for sizeof(float), D for sizeof(double) or L for sizeof(long double). Adding a z suffix to any type displays printable characters at the end of each output line. BYTES is hex with 0x or 0X prefix, and may have a multiplier suffix: b 512 KB 1000 K 1024 MB 1000*1000 M 1024*1024 and so on for G, T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. EXAMPLES top od -A x -t x1z -v Display hexdump format output od -A o -t oS -w16 The default output format used by od 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 Full documentation <https://www.gnu.org/software/coreutils/od> or available locally via: info '(coreutils) od 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 OD(1) Pages that refer to this page: scr_dump(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. 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: Convert "abc" to a string of hexadecimal bytes Bash Command:<START>echo abc | od -A n -v -t x1 | tr -d ' \n'<END>
Convert *.au files to *.wav files using `sox'
find -type f -name '*.au' | awk '{printf "sox %s %s\n",$0,$0".wav" }' | bash
['find', 'bash', 'awk']
Output a Bash command to accomplish the following task. Task: Convert *.au files to *.wav files using `sox' Bash Command:<START>find -type f -name '*.au' | awk '{printf "sox %s %s\n",$0,$0".wav" }' | bash<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 # bash\n\n> Bourne-Again SHell, an `sh`-compatible command-line interpreter.\n> See also: `zsh`, `histexpand` (history expansion).\n> More information: <https://www.gnu.org/software/bash/>.\n\n- Start an interactive shell session:\n\n`bash`\n\n- Start an interactive shell session without loading startup configs:\n\n`bash --norc`\n\n- Execute specific [c]ommands:\n\n`bash -c "{{echo 'bash is executed'}}"`\n\n- Execute a specific script:\n\n`bash {{path/to/script.sh}}`\n\n- E[x]ecute a specific script, printing each command before executing it:\n\n`bash -x {{path/to/script.sh}}`\n\n- Execute a specific script and stop at the first [e]rror:\n\n`bash -e {{path/to/script.sh}}`\n\n- Execute specific commands from `stdin`:\n\n`{{echo "echo 'bash is executed'"}} | bash`\n\n- Start a [r]estricted shell session:\n\n`bash -r`\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 Task: Convert *.au files to *.wav files using `sox' Bash Command:<START>find -type f -name '*.au' | awk '{printf "sox %s %s\n",$0,$0".wav" }' | bash<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. bash(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training bash(1) Linux manual page NAME | SYNOPSIS | COPYRIGHT | DESCRIPTION | OPTIONS | ARGUMENTS | INVOCATION | DEFINITIONS | RESERVED WORDS | SHELL GRAMMAR | COMMENTS | QUOTING | PARAMETERS | EXPANSION | REDIRECTION | ALIASES | FUNCTIONS | ARITHMETIC EVALUATION | CONDITIONAL EXPRESSIONS | SIMPLE COMMAND EXPANSION | COMMAND EXECUTION | COMMAND EXECUTION ENVIRONMENT | ENVIRONMENT | EXIT STATUS | SIGNALS | JOB CONTROL | PROMPTING | READLINE | HISTORY | HISTORY EXPANSION | SHELL BUILTIN COMMANDS | SHELL COMPATIBILITY MODE | RESTRICTED SHELL | SEE ALSO | FILES | AUTHORS | BUG REPORTS | BUGS | COLOPHON BASH(1) General Commands Manual BASH(1) NAME top bash - GNU Bourne-Again SHell SYNOPSIS top bash [options] [command_string | file] COPYRIGHT top Bash is Copyright (C) 1989-2022 by the Free Software Foundation, Inc. DESCRIPTION top Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and csh). Bash is intended to be a conformant implementation of the Shell and Utilities portion of the IEEE POSIX specification (IEEE Standard 1003.1). Bash can be configured to be POSIX-conformant by default. OPTIONS top All of the single-character shell options documented in the description of the set builtin command, including -o, can be used as options when the shell is invoked. In addition, bash interprets the following options when it is invoked: -c If the -c option is present, then commands are read from the first non-option argument command_string. If there are arguments after the command_string, the first argument is assigned to $0 and any remaining arguments are assigned to the positional parameters. The assignment to $0 sets the name of the shell, which is used in warning and error messages. -i If the -i option is present, the shell is interactive. -l Make bash act as if it had been invoked as a login shell (see INVOCATION below). -r If the -r option is present, the shell becomes restricted (see RESTRICTED SHELL below). -s If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell or when reading input through a pipe. -D A list of all double-quoted strings preceded by $ is printed on the standard output. These are the strings that are subject to language translation when the current locale is not C or POSIX. This implies the -n option; no commands will be executed. [-+]O [shopt_option] shopt_option is one of the shell options accepted by the shopt builtin (see SHELL BUILTIN COMMANDS below). If shopt_option is present, -O sets the value of that option; +O unsets it. If shopt_option is not supplied, the names and values of the shell options accepted by shopt are printed on the standard output. If the invocation option is +O, the output is displayed in a format that may be reused as input. -- A -- signals the end of options and disables further option processing. Any arguments after the -- are treated as filenames and arguments. An argument of - is equivalent to --. Bash also interprets a number of multi-character options. These options must appear on the command line before the single- character options to be recognized. --debugger Arrange for the debugger profile to be executed before the shell starts. Turns on extended debugging mode (see the description of the extdebug option to the shopt builtin below). --dump-po-strings Equivalent to -D, but the output is in the GNU gettext po (portable object) file format. --dump-strings Equivalent to -D. --help Display a usage message on standard output and exit successfully. --init-file file --rcfile file Execute commands from file instead of the standard personal initialization file ~/.bashrc if the shell is interactive (see INVOCATION below). --login Equivalent to -l. --noediting Do not use the GNU readline library to read command lines when the shell is interactive. --noprofile Do not read either the system-wide startup file /etc/profile or any of the personal initialization files ~/.bash_profile, ~/.bash_login, or ~/.profile. By default, bash reads these files when it is invoked as a login shell (see INVOCATION below). --norc Do not read and execute the personal initialization file ~/.bashrc if the shell is interactive. This option is on by default if the shell is invoked as sh. --posix Change the behavior of bash where the default operation differs from the POSIX standard to match the standard (posix mode). See SEE ALSO below for a reference to a document that details how posix mode affects bash's behavior. --restricted The shell becomes restricted (see RESTRICTED SHELL below). --verbose Equivalent to -v. --version Show version information for this instance of bash on the standard output and exit successfully. ARGUMENTS top If arguments remain after option processing, and neither the -c nor the -s option has been supplied, the first argument is assumed to be the name of a file containing shell commands. If bash is invoked in this fashion, $0 is set to the name of the file, and the positional parameters are set to the remaining arguments. Bash reads and executes commands from this file, then exits. Bash's exit status is the exit status of the last command executed in the script. If no commands are executed, the exit status is 0. An attempt is first made to open the file in the current directory, and, if no file is found, then the shell searches the directories in PATH for the script. INVOCATION top A login shell is one whose first character of argument zero is a -, or one started with the --login option. An interactive shell is one started without non-option arguments (unless -s is specified) and without the -c option, whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state. The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports an error. Tildes are expanded in filenames as described below under Tilde Expansion in the EXPANSION section. When bash is invoked as an interactive login shell, or as a non- interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior. When an interactive login shell exits, or a non-interactive login shell executes the exit builtin command, bash reads and executes commands from the file ~/.bash_logout, if it exists. When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc. When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed: if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi but the value of the PATH variable is not used to search for the filename. If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well. When invoked as an interactive login shell, or a non-interactive shell with the --login option, it first attempts to read and execute commands from /etc/profile and ~/.profile, in that order. The --noprofile option may be used to inhibit this behavior. When invoked as an interactive shell with the name sh, bash looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. Since a shell invoked as sh does not attempt to read and execute commands from any other startup files, the --rcfile option has no effect. A non-interactive shell invoked with the name sh does not attempt to read any other startup files. When invoked as sh, bash enters posix mode after the startup files are read. When bash is started in posix mode, as with the --posix command line option, it follows the POSIX standard for startup files. In this mode, interactive shells expand the ENV variable and commands are read and executed from the file whose name is the expanded value. No other startup files are read. Bash attempts to determine when it is being run with its standard input connected to a network connection, as when executed by the historical remote shell daemon, usually rshd, or the secure shell daemon sshd. If bash determines it is being run non- interactively in this fashion, it reads and executes commands from ~/.bashrc, if that file exists and is readable. It will not do this if invoked as sh. The --norc option may be used to inhibit this behavior, and the --rcfile option may be used to force another file to be read, but neither rshd nor sshd generally invoke the shell with those options or allow them to be specified. If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, no startup files are read, shell functions are not inherited from the environment, the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear in the environment, are ignored, and the effective user id is set to the real user id. If the -p option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset. DEFINITIONS top The following definitions are used throughout the rest of this document. blank A space or tab. word A sequence of characters considered as a single unit by the shell. Also known as a token. name A word consisting only of alphanumeric characters and underscores, and beginning with an alphabetic character or an underscore. Also referred to as an identifier. metacharacter A character that, when unquoted, separates words. One of the following: | & ; ( ) < > space tab newline control operator A token that performs a control function. It is one of the following symbols: || & && ; ;; ;& ;;& ( ) | |& <newline> RESERVED WORDS top Reserved words are words that have a special meaning to the shell. The following words are recognized as reserved when unquoted and either the first word of a command (see SHELL GRAMMAR below), the third word of a case or select command (only in is valid), or the third word of a for command (only in and do are valid): ! case coproc do done elif else esac fi for function if in select then until while { } time [[ ]] SHELL GRAMMAR top This section describes the syntax of the various forms of shell commands. Simple Commands A simple command is a sequence of optional variable assignments followed by blank-separated words and redirections, and terminated by a control operator. The first word specifies the command to be executed, and is passed as argument zero. The remaining words are passed as arguments to the invoked command. The return value of a simple command is its exit status, or 128+n if the command is terminated by signal n. Pipelines A pipeline is a sequence of one or more commands separated by one of the control operators | or |&. The format for a pipeline is: [time [-p]] [ ! ] command1 [ [||&] command2 ... ] The standard output of command1 is connected via a pipe to the standard input of command2. This connection is performed before any redirections specified by the command1(see REDIRECTION below). If |& is used, command1's standard error, in addition to its standard output, is connected to command2's standard input through the pipe; it is shorthand for 2>&1 |. This implicit redirection of the standard error to the standard output is performed after any redirections specified by command1. The return status of a pipeline is the exit status of the last command, unless the pipefail option is enabled. If pipefail is enabled, the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word ! precedes a pipeline, the exit status of that pipeline is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value. If the time reserved word precedes a pipeline, the elapsed as well as user and system time consumed by its execution are reported when the pipeline terminates. The -p option changes the output format to that specified by POSIX. When the shell is in posix mode, it does not recognize time as a reserved word if the next token begins with a `-'. The TIMEFORMAT variable may be set to a format string that specifies how the timing information should be displayed; see the description of TIMEFORMAT under Shell Variables below. When the shell is in posix mode, time may be followed by a newline. In this case, the shell displays the total user and system time consumed by the shell and its children. The TIMEFORMAT variable may be used to specify the format of the time information. Each command in a multi-command pipeline, where pipes are created, is executed in a subshell, which is a separate process. See COMMAND EXECUTION ENVIRONMENT for a description of subshells and a subshell environment. If the lastpipe option is enabled using the shopt builtin (see the description of shopt below), the last element of a pipeline may be run by the shell process when job control is not active. Lists A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or <newline>. Of these list operators, && and || have equal precedence, followed by ; and &, which have equal precedence. A sequence of one or more newlines may appear in a list instead of a semicolon to delimit commands. If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. These are referred to as asynchronous commands. Commands separated by a ; are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed. AND and OR lists are sequences of one or more pipelines separated by the && and || control operators, respectively. AND and OR lists are executed with left associativity. An AND list has the form command1 && command2 command2 is executed if, and only if, command1 returns an exit status of zero (success). An OR list has the form command1 || command2 command2 is executed if, and only if, command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list. Compound Commands A compound command is one of the following. In most cases a list in a command's description may be separated from the rest of the command by one or more newlines, and may be followed by a newline in place of a semicolon. (list) list is executed in a subshell (see COMMAND EXECUTION ENVIRONMENT below for a description of a subshell environment). Variable assignments and builtin commands that affect the shell's environment do not remain in effect after the command completes. The return status is the exit status of list. { list; } list is simply executed in the current shell environment. list must be terminated with a newline or semicolon. This is known as a group command. The return status is the exit status of list. Note that unlike the metacharacters ( and ), { and } are reserved words and must occur where a reserved word is permitted to be recognized. Since they do not cause a word break, they must be separated from list by whitespace or another shell metacharacter. ((expression)) The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. The expression undergoes the same expansions as if it were within double quotes, but double quote characters in expression are not treated specially and are removed. [[ expression ]] Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the primaries described below under CONDITIONAL EXPRESSIONS. The words between the [[ and ]] do not undergo word splitting and pathname expansion. The shell performs tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal on those words (the expansions that would occur if the words were enclosed in double quotes). Conditional operators such as -f must be unquoted to be recognized as primaries. When used with [[, the < and > operators sort lexicographically using the current locale. When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below under Pattern Matching, as if the extglob shell option were enabled. The = operator is equivalent to ==. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (==) or does not match (!=) the pattern, and 1 otherwise. Any part of the pattern may be quoted to force the quoted portion to be matched as a string. An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered a POSIX extended regular expression and matched accordingly (using the POSIX regcomp and regexec interfaces usually described in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. If any part of the pattern is quoted, the quoted portion is matched literally. This means every character in the quoted portion matches itself, instead of having any special pattern matching meaning. If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched literally. Treat bracket expressions in regular expressions carefully, since normal quoting and pattern characters lose their meanings between brackets. The pattern will match if it matches any part of the string. Anchor the pattern using the ^ and $ regular expression operators to force it to match the entire string. The array variable BASH_REMATCH records which parts of the string matched the pattern. The element of BASH_REMATCH with index 0 contains the portion of the string matching the entire regular expression. Substrings matched by parenthesized subexpressions within the regular expression are saved in the remaining BASH_REMATCH indices. The element of BASH_REMATCH with index n is the portion of the string matching the nth parenthesized subexpression. Bash sets BASH_REMATCH in the global scope; declaring it as a local variable will lead to unexpected results. Expressions may be combined using the following operators, listed in decreasing order of precedence: ( expression ) Returns the value of expression. This may be used to override the normal precedence of operators. ! expression True if expression is false. expression1 && expression2 True if both expression1 and expression2 are true. expression1 || expression2 True if either expression1 or expression2 is true. The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression. for name [ [ in [ word ... ] ] ; ] do list ; done The list of words following in is expanded, generating a list of items. The variable name is set to each element of this list in turn, and list is executed each time. If the in word is omitted, the for command executes list once for each positional parameter that is set (see PARAMETERS below). The return status is the exit status of the last command that executes. If the expansion of the items following in results in an empty list, no commands are executed, and the return status is 0. for (( expr1 ; expr2 ; expr3 )) ; do list ; done First, the arithmetic expression expr1 is evaluated according to the rules described below under ARITHMETIC EVALUATION. The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero. Each time expr2 evaluates to a non-zero value, list is executed and the arithmetic expression expr3 is evaluated. If any expression is omitted, it behaves as if it evaluates to 1. The return value is the exit status of the last command in list that is executed, or false if any of the expressions is invalid. select name [ in word ] ; do list ; done The list of words following in is expanded, generating a list of items, and the set of expanded words is printed on the standard error, each preceded by a number. If the in word is omitted, the positional parameters are printed (see PARAMETERS below). select then displays the PS3 prompt and reads a line from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the select command completes and returns 1. Any other value read causes name to be set to null. The line read is saved in the variable REPLY. The list is executed after each selection until a break command is executed. The exit status of select is the exit status of the last command executed in list, or zero if no commands were executed. case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac A case command first expands word, and tries to match it against each pattern in turn, using the matching rules described under Pattern Matching below. The word is expanded using tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution and quote removal. Each pattern examined is expanded using tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. When a match is found, the corresponding list is executed. If the ;; operator is used, no subsequent matches are attempted after the first pattern match. Using ;& in place of ;; causes execution to continue with the list associated with the next set of patterns. Using ;;& in place of ;; causes the shell to test the next pattern list in the statement, if any, and execute any associated list on a successful match, continuing the case statement execution as if the pattern list had not matched. The exit status is zero if no pattern matches. Otherwise, it is the exit status of the last command executed in list. if list; then list; [ elif list; then list; ] ... [ else list; ] fi The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true. while list-1; do list-2; done until list-1; do list-2; done The while command continuously executes the list list-2 as long as the last command in the list list-1 returns an exit status of zero. The until command is identical to the while command, except that the test is negated: list-2 is executed as long as the last command in list-1 returns a non-zero exit status. The exit status of the while and until commands is the exit status of the last command executed in list-2, or zero if none was executed. Coprocesses A coprocess is a shell command preceded by the coproc reserved word. A coprocess is executed asynchronously in a subshell, as if the command had been terminated with the & control operator, with a two-way pipe established between the executing shell and the coprocess. The syntax for a coprocess is: coproc [NAME] command [redirections] This creates a coprocess named NAME. command may be either a simple command or a compound command (see above). NAME is a shell variable name. If NAME is not supplied, the default name is COPROC. The recommended form to use for a coprocess is coproc NAME { command [redirections]; } This form is recommended because simple commands result in the coprocess always being named COPROC, and it is simpler to use and more complete than the other compound commands. If command is a compound command, NAME is optional. The word following coproc determines whether that word is interpreted as a variable name: it is interpreted as NAME if it is not a reserved word that introduces a compound command. If command is a simple command, NAME is not allowed; this is to avoid confusion between NAME and the first word of the simple command. When the coprocess is executed, the shell creates an array variable (see Arrays below) named NAME in the context of the executing shell. The standard output of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[0]. The standard input of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[1]. This pipe is established before any redirections specified by the command (see REDIRECTION below). The file descriptors can be utilized as arguments to shell commands and redirections using standard word expansions. Other than those created to execute command and process substitutions, the file descriptors are not available in subshells. The process ID of the shell spawned to execute the coprocess is available as the value of the variable NAME_PID. The wait builtin command may be used to wait for the coprocess to terminate. Since the coprocess is created as an asynchronous command, the coproc command always returns success. The return status of a coprocess is the exit status of command. Shell Function Definitions A shell function is an object that is called like a simple command and executes a compound command with a new set of positional parameters. Shell functions are declared as follows: fname () compound-command [redirection] function fname [()] compound-command [redirection] This defines a function named fname. The reserved word function is optional. If the function reserved word is supplied, the parentheses are optional. The body of the function is the compound command compound-command (see Compound Commands above). That command is usually a list of commands between { and }, but may be any command listed under Compound Commands above. If the function reserved word is used, but the parentheses are not supplied, the braces are recommended. compound-command is executed whenever fname is specified as the name of a simple command. When in posix mode, fname must be a valid shell name and may not be the name of one of the POSIX special builtins. In default mode, a function name can be any unquoted shell word that does not contain $. Any redirections (see REDIRECTION below) specified when a function is defined are performed when the function is executed. The exit status of a function definition is zero unless a syntax error occurs or a readonly function with the same name already exists. When executed, the exit status of a function is the exit status of the last command executed in the body. (See FUNCTIONS below.) COMMENTS top In a non-interactive shell, or an interactive shell in which the interactive_comments option to the shopt builtin is enabled (see SHELL BUILTIN COMMANDS below), a word beginning with # causes that word and all remaining characters on that line to be ignored. An interactive shell without the interactive_comments option enabled does not allow comments. The interactive_comments option is on by default in interactive shells. QUOTING top Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting can be used to disable special treatment for special characters, to prevent reserved words from being recognized as such, and to prevent parameter expansion. Each of the metacharacters listed above under DEFINITIONS has special meaning to the shell and must be quoted if it is to represent itself. When the command history expansion facilities are being used (see HISTORY EXPANSION below), the history expansion character, usually !, must be quoted to prevent history expansion. There are three quoting mechanisms: the escape character, single quotes, and double quotes. A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows, with the exception of <newline>. If a \<newline> pair appears, and the backslash is not itself quoted, the \<newline> is treated as a line continuation (that is, it is removed from the input stream and effectively ignored). Enclosing characters in single quotes preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. When the shell is in posix mode, the ! has no special meaning within double quotes, even when history expansion is enabled. The characters $ and ` retain their special meaning within double quotes. The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or <newline>. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed. The special parameters * and @ have special meaning when in double quotes (see PARAMETERS below). Character sequences of the form $'string' are treated as a special variant of single quotes. The sequence expands to string, with backslash-escaped characters in string replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows: \a alert (bell) \b backspace \e \E an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \' single quote \" double quote \? question mark \nnn the eight-bit character whose value is the octal value nnn (one to three octal digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \uHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits) \UHHHHHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits) \cx a control-x character The expanded result is single-quoted, as if the dollar sign had not been present. A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. The gettext infrastructure performs the lookup and translation, using the LC_MESSAGES, TEXTDOMAINDIR, and TEXTDOMAIN shell variables. If the current locale is C or POSIX, if there are no translations available, or if the string is not translated, the dollar sign is ignored. This is a form of double quoting, so the string remains double-quoted by default, whether or not it is translated and replaced. If the noexpand_translation option is enabled using the shopt builtin, translated strings are single-quoted instead of double-quoted. See the description of shopt below under SHELLBUILTINCOMMANDS. PARAMETERS top A parameter is an entity that stores values. It can be a name, a number, or one of the special characters listed below under Special Parameters. A variable is a parameter denoted by a name. A variable has a value and zero or more attributes. Attributes are assigned using the declare builtin command (see declare below in SHELL BUILTIN COMMANDS). A parameter is set if it has been assigned a value. The null string is a valid value. Once a variable is set, it may be unset only by using the unset builtin command (see SHELL BUILTIN COMMANDS below). A variable may be assigned to by a statement of the form name=[value] If value is not given, the variable is assigned the null string. All values undergo tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal (see EXPANSION below). If the variable has its integer attribute set, then value is evaluated as an arithmetic expression even if the $((...)) expansion is not used (see Arithmetic Expansion below). Word splitting and pathname expansion are not performed. Assignment statements may also appear as arguments to the alias, declare, typeset, export, readonly, and local builtin commands (declaration commands). When in posix mode, these builtins may appear in a command after one or more instances of the command builtin and retain these assignment statement properties. In the context where an assignment statement is assigning a value to a shell variable or array index, the += operator can be used to append to or add to the variable's previous value. This includes arguments to builtin commands such as declare that accept assignment statements (declaration commands). When += is applied to a variable for which the integer attribute has been set, value is evaluated as an arithmetic expression and added to the variable's current value, which is also evaluated. When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays) or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable's value. A variable can be assigned the nameref attribute using the -n option to the declare or local builtin commands (see the descriptions of declare and local below) to create a nameref, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable's value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to the function. For instance, if a variable name is passed to a shell function as its first argument, running declare -n ref=$1 inside the function creates a nameref variable ref whose value is the variable name passed as the first argument. References and assignments to ref, and changes to its attributes, are treated as references, assignments, and attribute modifications to the variable whose name was passed as $1. If the control variable in a for loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be established for each word in the list, in turn, when the loop is executed. Array variables cannot be given the nameref attribute. However, nameref variables can reference array variables and subscripted array variables. Namerefs can be unset using the -n option to the unset builtin. Otherwise, if unset is executed with the name of a nameref variable as an argument, the variable referenced by the nameref variable will be unset. Positional Parameters A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameters may not be assigned to with assignment statements. The positional parameters are temporarily replaced when a shell function is executed (see FUNCTIONS below). When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces (see EXPANSION below). Special Parameters The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. * Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word. In contexts where it is performed, those words are subject to further word splitting and pathname expansion. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators. @ Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parameter to a separate word; if not within double quotes, these words are subject to word splitting. In contexts where word splitting is not performed, this expands to a single word with each positional parameter separated by a space. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed). # Expands to the number of positional parameters in decimal. ? Expands to the exit status of the most recently executed foreground pipeline. - Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option). $ Expands to the process ID of the shell. In a subshell, it expands to the process ID of the current shell, not the subshell. ! Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin (see JOB CONTROL below). 0 Expands to the name of the shell or shell script. This is set at shell initialization. If bash is invoked with a file of commands, $0 is set to the name of that file. If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke bash, as given by argument zero. Shell Variables The following variables are set by the shell: _ At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file currently being checked. BASH Expands to the full filename used to invoke this instance of bash. BASHOPTS A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -s option to the shopt builtin command (see SHELL BUILTIN COMMANDS below). The options appearing in BASHOPTS are those reported as on by shopt. If this variable is in the environment when bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is read-only. BASHPID Expands to the process ID of the current bash process. This differs from $$ under certain circumstances, such as subshells that do not require bash to be re-initialized. Assignments to BASHPID have no effect. If BASHPID is unset, it loses its special properties, even if it is subsequently reset. BASH_ALIASES An associative array variable whose members correspond to the internal list of aliases as maintained by the alias builtin. Elements added to this array appear in the alias list; however, unsetting array elements currently does not cause aliases to be removed from the alias list. If BASH_ALIASES is unset, it loses its special properties, even if it is subsequently reset. BASH_ARGC An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with . or source) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto BASH_ARGC. The shell sets BASH_ARGC only when in extended debugging mode (see the description of the extdebug option to the shopt builtin below). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values. BASH_ARGV An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto BASH_ARGV. The shell sets BASH_ARGV only when in extended debugging mode (see the description of the extdebug option to the shopt builtin below). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values. BASH_ARGV0 When referenced, this variable expands to the name of the shell or shell script (identical to $0; see the description of special parameter 0 above). Assignment to BASH_ARGV0 causes the value assigned to also be assigned to $0. If BASH_ARGV0 is unset, it loses its special properties, even if it is subsequently reset. BASH_CMDS An associative array variable whose members correspond to the internal hash table of commands as maintained by the hash builtin. Elements added to this array appear in the hash table; however, unsetting array elements currently does not cause command names to be removed from the hash table. If BASH_CMDS is unset, it loses its special properties, even if it is subsequently reset. BASH_COMMAND The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If BASH_COMMAND is unset, it loses its special properties, even if it is subsequently reset. BASH_EXECUTION_STRING The command argument to the -c invocation option. BASH_LINENO An array variable whose members are the line numbers in source files where each corresponding member of FUNCNAME was invoked. ${BASH_LINENO[$i]} is the line number in the source file (${BASH_SOURCE[$i+1]}) where ${FUNCNAME[$i]} was called (or ${BASH_LINENO[$i-1]} if referenced within another shell function). Use LINENO to obtain the current line number. BASH_LOADABLES_PATH A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the enable command. BASH_REMATCH An array variable whose members are assigned by the =~ binary operator to the [[ conditional command. The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the nth parenthesized subexpression. BASH_SOURCE An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}. BASH_SUBSHELL Incremented by one within each subshell or subshell environment when the shell begins executing in that environment. The initial value is 0. If BASH_SUBSHELL is unset, it loses its special properties, even if it is subsequently reset. BASH_VERSINFO A readonly array variable whose members hold version information for this instance of bash. The values assigned to the array members are as follows: BASH_VERSINFO[0] The major version number (the release). BASH_VERSINFO[1] The minor version number (the version). BASH_VERSINFO[2] The patch level. BASH_VERSINFO[3] The build version. BASH_VERSINFO[4] The release status (e.g., beta1). BASH_VERSINFO[5] The value of MACHTYPE. BASH_VERSION Expands to a string describing the version of this instance of bash. COMP_CWORD An index into ${COMP_WORDS} of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion below). COMP_KEY The key (or final key of a key sequence) used to invoke the current completion function. COMP_LINE The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion below). COMP_POINT The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to ${#COMP_LINE}. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion below). COMP_TYPE Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: TAB, for normal completion, ?, for listing completions after successive tabs, !, for listing alternatives on partial word completion, @, to list completions if the word is not unmodified, or %, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see Programmable Completion below). COMP_WORDBREAKS The set of characters that the readline library treats as word separators when performing word completion. If COMP_WORDBREAKS is unset, it loses its special properties, even if it is subsequently reset. COMP_WORDS An array variable (see Arrays below) consisting of the individual words in the current command line. The line is split into words as readline would split it, using COMP_WORDBREAKS as described above. This variable is available only in shell functions invoked by the programmable completion facilities (see Programmable Completion below). COPROC An array variable (see Arrays below) created to hold the file descriptors for output from and input to an unnamed coprocess (see Coprocesses above). DIRSTACK An array variable (see Arrays below) containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the dirs builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the pushd and popd builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If DIRSTACK is unset, it loses its special properties, even if it is subsequently reset. EPOCHREALTIME Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see time(3)) as a floating point value with micro-second granularity. Assignments to EPOCHREALTIME are ignored. If EPOCHREALTIME is unset, it loses its special properties, even if it is subsequently reset. EPOCHSECONDS Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see time(3)). Assignments to EPOCHSECONDS are ignored. If EPOCHSECONDS is unset, it loses its special properties, even if it is subsequently reset. EUID Expands to the effective user ID of the current user, initialized at shell startup. This variable is readonly. FUNCNAME An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently- executing shell function. The bottom-most element (the one with the highest index) is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset. This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information. GROUPS An array variable containing the list of groups of which the current user is a member. Assignments to GROUPS have no effect. If GROUPS is unset, it loses its special properties, even if it is subsequently reset. HISTCMD The history number, or index in the history list, of the current command. Assignments to HISTCMD are ignored. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset. HOSTNAME Automatically set to the name of the current host. HOSTTYPE Automatically set to a string that uniquely describes the type of machine on which bash is executing. The default is system-dependent. LINENO Each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function. When not in a script or function, the value substituted is not guaranteed to be meaningful. If LINENO is unset, it loses its special properties, even if it is subsequently reset. MACHTYPE Automatically set to a string that fully describes the system type on which bash is executing, in the standard GNU cpu-company-system format. The default is system- dependent. MAPFILE An array variable (see Arrays below) created to hold the text read by the mapfile builtin when no variable name is supplied. OLDPWD The previous working directory as set by the cd command. OPTARG The value of the last option argument processed by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OPTIND The index of the next argument to be processed by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OSTYPE Automatically set to a string that describes the operating system on which bash is executing. The default is system- dependent. PIPESTATUS An array variable (see Arrays below) containing a list of exit status values from the processes in the most- recently-executed foreground pipeline (which may contain only a single command). PPID The process ID of the shell's parent. This variable is readonly. PWD The current working directory as set by the cd command. RANDOM Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to RANDOM initializes (seeds) the sequence of random numbers. If RANDOM is unset, it loses its special properties, even if it is subsequently reset. READLINE_ARGUMENT Any numeric argument given to a readline command that was defined using "bind -x" (see SHELL BUILTIN COMMANDS below) when it was invoked. READLINE_LINE The contents of the readline line buffer, for use with "bind -x" (see SHELL BUILTIN COMMANDS below). READLINE_MARK The position of the mark (saved insertion point) in the readline line buffer, for use with "bind -x" (see SHELL BUILTIN COMMANDS below). The characters between the insertion point and the mark are often called the region. READLINE_POINT The position of the insertion point in the readline line buffer, for use with "bind -x" (see SHELL BUILTIN COMMANDS below). REPLY Set to the line of input read by the read builtin command when no arguments are supplied. SECONDS Each time this parameter is referenced, it expands to the number of seconds since shell invocation. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. The number of seconds at shell invocation and the current time are always determined by querying the system clock. If SECONDS is unset, it loses its special properties, even if it is subsequently reset. SHELLOPTS A colon-separated list of enabled shell options. Each word in the list is a valid argument for the -o option to the set builtin command (see SHELL BUILTIN COMMANDS below). The options appearing in SHELLOPTS are those reported as on by set -o. If this variable is in the environment when bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is read-only. SHLVL Incremented by one each time an instance of bash is started. SRANDOM This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support /dev/urandom or arc4random, so each returned number has no relationship to the numbers preceding it. The random number generator cannot be seeded, so assignments to this variable have no effect. If SRANDOM is unset, it loses its special properties, even if it is subsequently reset. UID Expands to the user ID of the current user, initialized at shell startup. This variable is readonly. The following variables are used by the shell. In some cases, bash assigns a default value to a variable; these cases are noted below. BASH_COMPAT The value is used to set the shell's compatibility level. See SHELL COMPATIBILITY MODE below for a description of the various compatibility levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., 42) corresponding to the desired compatibility level. If BASH_COMPAT is unset or set to the empty string, the compatibility level is set to the default for the current version. If BASH_COMPAT is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid values correspond to the compatibility levels described below under SHELL COMPATIBILITY MODE. For example, 4.2 and 42 are valid values that correspond to the compat42 shopt option and set the compatibility level to 42. The current version is also a valid value. BASH_ENV If this parameter is set when bash is executing a shell script, its value is interpreted as a filename containing commands to initialize the shell, as in ~/.bashrc. The value of BASH_ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a filename. PATH is not used to search for the resultant filename. BASH_XTRACEFD If set to an integer corresponding to a valid file descriptor, bash will write the trace output generated when set -x is enabled to that file descriptor. The file descriptor is closed when BASH_XTRACEFD is unset or assigned a new value. Unsetting BASH_XTRACEFD or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting BASH_XTRACEFD to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed. CDPATH The search path for the cd command. This is a colon- separated list of directories in which the shell looks for destination directories specified by the cd command. A sample value is ".:~:/usr". CHILD_MAX Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX-mandated minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent. COLUMNS Used by the select compound command to determine the terminal width when printing selection lists. Automatically set if the checkwinsize option is enabled or in an interactive shell upon receipt of a SIGWINCH. COMPREPLY An array variable from which bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see Programmable Completion below). Each array element contains one possible completion. EMACS If bash finds this variable in the environment when the shell starts with value "t", it assumes that the shell is running in an Emacs shell buffer and disables line editing. ENV Expanded and executed similarly to BASH_ENV (see INVOCATION above) when an interactive shell is invoked in posix mode. EXECIGNORE A colon-separated list of shell patterns (see Pattern Matching) defining the list of filenames to be ignored by command search using PATH. Files whose full pathnames match one of these patterns are not considered executable files for the purposes of completion and command execution via PATH lookup. This does not affect the behavior of the [, test, and [[ commands. Full pathnames in the command hash table are not subject to EXECIGNORE. Use this variable to ignore shared library files that have the executable bit set, but are not executable files. The pattern matching honors the setting of the extglob shell option. FCEDIT The default editor for the fc builtin command. FIGNORE A colon-separated list of suffixes to ignore when performing filename completion (see READLINE below). A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is ".o:~". FUNCNEST If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort. GLOBIGNORE A colon-separated list of patterns defining the set of file names to be ignored by pathname expansion. If a file name matched by a pathname expansion pattern also matches one of the patterns in GLOBIGNORE, it is removed from the list of matches. HISTCONTROL A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL. HISTFILE The name of the file in which command history is saved (see HISTORY below). The default value is ~/.bash_history. If unset, the command history is not saved when a shell exits. HISTFILESIZE The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of HISTSIZE after reading any startup files. HISTIGNORE A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit `*' is appended). Each pattern is tested against the line after the checks specified by HISTCONTROL are applied. In addition to the normal shell pattern matching characters, `&' matches the previous history line. `&' may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTIGNORE. The pattern matching honors the setting of the extglob shell option. HISTSIZE The number of commands to remember in the command history (see HISTORY below). If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files. HISTTIMEFORMAT If this variable is set and not null, its value is used as a format string for strftime(3) to print the time stamp associated with each history entry displayed by the history builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines. HOME The home directory of the current user; the default argument for the cd builtin command. The value of this variable is also used when performing tilde expansion. HOSTFILE Contains the name of a file in the same format as /etc/hosts that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, bash adds the contents of the new file to the existing list. If HOSTFILE is set, but has no value, or does not name a readable file, bash attempts to read /etc/hosts to obtain the list of possible hostname completions. When HOSTFILE is unset, the hostname list is cleared. IFS The Internal Field Separator that is used for word splitting after expansion and to split lines into words with the read builtin command. The default value is ``<space><tab><newline>''. IGNOREEOF Controls the action of an interactive shell on receipt of an EOF character as the sole input. If set, the value is the number of consecutive EOF characters which must be typed as the first characters on an input line before bash exits. If the variable exists but does not have a numeric value, or has no value, the default value is 10. If it does not exist, EOF signifies the end of input to the shell. INPUTRC The filename for the readline startup file, overriding the default of ~/.inputrc (see READLINE below). INSIDE_EMACS If this variable appears in the environment when the shell starts, bash assumes that it is running inside an Emacs shell buffer and may disable line editing, depending on the value of TERM. LANG Used to determine the locale category for any category not specifically selected with a variable starting with LC_. LC_ALL This variable overrides the value of LANG and any other LC_ variable specifying a locale category. LC_COLLATE This variable determines the collation order used when sorting the results of pathname expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within pathname expansion and pattern matching. LC_CTYPE This variable determines the interpretation of characters and the behavior of character classes within pathname expansion and pattern matching. LC_MESSAGES This variable determines the locale used to translate double-quoted strings preceded by a $. LC_NUMERIC This variable determines the locale category used for number formatting. LC_TIME This variable determines the locale category used for data and time formatting. LINES Used by the select compound command to determine the column length for printing selection lists. Automatically set if the checkwinsize option is enabled or in an interactive shell upon receipt of a SIGWINCH. MAIL If this parameter is set to a file or directory name and the MAILPATH variable is not set, bash informs the user of the arrival of mail in the specified file or Maildir- format directory. MAILCHECK Specifies how often (in seconds) bash checks for mail. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking. MAILPATH A colon-separated list of filenames to be checked for mail. The message to be printed when mail arrives in a particular file may be specified by separating the filename from the message with a `?'. When used in the text of the message, $_ expands to the name of the current mailfile. Example: MAILPATH='/var/mail/bfox?"You have mail":~/shell-mail?"$_ has mail!"' Bash can be configured to supply a default value for this variable (there is no value by default), but the location of the user mail files that it uses is system dependent (e.g., /var/mail/$USER). OPTERR If set to the value 1, bash displays error messages generated by the getopts builtin command (see SHELL BUILTIN COMMANDS below). OPTERR is initialized to 1 each time the shell is invoked or a shell script is executed. PATH The search path for commands. It is a colon-separated list of directories in which the shell looks for commands (see COMMAND EXECUTION below). A zero-length (null) directory name in the value of PATH indicates the current directory. A null directory name may appear as two adjacent colons, or as an initial or trailing colon. The default path is system-dependent, and is set by the administrator who installs bash. A common value is ``/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin''. POSIXLY_CORRECT If this variable is in the environment when bash starts, the shell enters posix mode before reading the startup files, as if the --posix invocation option had been supplied. If it is set while the shell is running, bash enables posix mode, as if the command set -o posix had been executed. When the shell enters posix mode, it sets this variable if it was not already set. PROMPT_COMMAND If this variable is set, and is an array, the value of each set element is executed as a command prior to issuing each primary prompt. If this is set but not an array variable, its value is used as a command to execute instead. PROMPT_DIRTRIM If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see PROMPTING below). Characters removed are replaced with an ellipsis. PS0 The value of this parameter is expanded (see PROMPTING below) and displayed by interactive shells after reading a command and before the command is executed. PS1 The value of this parameter is expanded (see PROMPTING below) and used as the primary prompt string. The default value is ``\s-\v\$ ''. PS2 The value of this parameter is expanded as with PS1 and used as the secondary prompt string. The default is ``> ''. PS3 The value of this parameter is used as the prompt for the select command (see SHELL GRAMMAR above). PS4 The value of this parameter is expanded as with PS1 and the value is printed before each command bash displays during an execution trace. The first character of the expanded value of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is ``+ ''. SHELL This variable expands to the full pathname to the shell. If it is not set when the shell starts, bash assigns to it the full pathname of the current user's login shell. TIMEFORMAT The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the time reserved word should be displayed. The % character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions. %% A literal %. %[p][l]R The elapsed time in seconds. %[p][l]U The number of CPU seconds spent in user mode. %[p][l]S The number of CPU seconds spent in system mode. %P The CPU percentage, computed as (%U + %S) / %R. The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used. The optional l specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included. If this variable is not set, bash acts as if it had the value $'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS'. If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed. TMOUT If set to a value greater than zero, TMOUT is treated as the default timeout for the read builtin. The select command terminates if input does not arrive after TMOUT seconds when input is coming from a terminal. In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive. TMPDIR If set, bash uses its value as the name of a directory in which bash creates temporary files for the shell's use. auto_resume This variable controls how the shell interacts with the user and job control. If this variable is set, single word simple commands without redirections are treated as candidates for resumption of an existing stopped job. There is no ambiguity allowed; if there is more than one job beginning with the string typed, the job most recently accessed is selected. The name of a stopped job, in this context, is the command line used to start it. If set to the value exact, the string supplied must match the name of a stopped job exactly; if set to substring, the string supplied needs to match a substring of the name of a stopped job. The substring value provides functionality analogous to the %? job identifier (see JOB CONTROL below). If set to any other value, the supplied string must be a prefix of a stopped job's name; this provides functionality analogous to the %string job identifier. histchars The two or three characters which control history expansion and tokenization (see HISTORY EXPANSION below). The first character is the history expansion character, the character which signals the start of a history expansion, normally `!'. The second character is the quick substitution character, which is used as shorthand for re-running the previous command entered, substituting one string for another in the command. The default is `^'. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, normally `#'. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment. Arrays Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. Indexed arrays are referenced using integers (including arithmetic expressions) and are zero-based; associative arrays are referenced using arbitrary strings. Unless otherwise noted, indexed array indices must be non-negative integers. An indexed array is created automatically if any variable is assigned to using the syntax name[subscript]=value. The subscript is treated as an arithmetic expression that must evaluate to a number. To explicitly declare an indexed array, use declare -a name (see SHELL BUILTIN COMMANDS below). declare -a name[subscript] is also accepted; the subscript is ignored. Associative arrays are created using declare -A name. Attributes may be specified for an array variable using the declare and readonly builtins. Each attribute applies to all members of an array. Arrays are assigned to using compound assignments of the form name=(value1 ... valuen), where each value may be of the form [subscript]=string. Indexed array assignments do not require anything but string. Each value in the list is expanded using all the shell expansions described below under EXPANSION. When assigning to indexed arrays, if the optional brackets and subscript are supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero. When assigning to an associative array, the words in a compound assignment may be either assignment statements, for which the subscript is required, or a list of words that is interpreted as a sequence of alternating keys and values: name=( key1 value1 key2 value2 ...). These are treated identically to name=( [key1]=value1 [key2]=value2 ...). The first word in the list determines how the remaining words are interpreted; all assignments in a list must be of the same type. When using key/value pairs, the keys may not be missing or empty; a final missing value is treated like the empty string. This syntax is also accepted by the declare builtin. Individual array elements may be assigned to using the name[subscript]=value syntax introduced above. When assigning to an indexed array, if name is subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of name, so negative indices count back from the end of the array, and an index of -1 references the last element. The += operator will append to an array variable when assigning using the compound assignment syntax; see PARAMETERS above. Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with pathname expansion. If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word. When there are no array members, ${name[@]} expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. This is analogous to the expansion of the special parameters * and @ (see Special Parameters above). ${#name[subscript]} expands to the length of ${name[subscript]}. If subscript is * or @, the expansion is the number of elements in the array. If the subscript used to reference an element of an indexed array evaluates to a number less than zero, it is interpreted as relative to one greater than the maximum index of the array, so negative indices count back from the end of the array, and an index of -1 references the last element. Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0. Any reference to a variable using a valid subscript is legal, and bash will create an array if necessary. An array variable is considered set if a subscript has been assigned a value. The null string is a valid value. It is possible to obtain the keys (indices) of an array as well as the values. ${!name[@]} and ${!name[*]} expand to the indices assigned in array variable name. The treatment when in double quotes is similar to the expansion of the special parameters @ and * within double quotes. The unset builtin is used to destroy arrays. unset name[subscript] destroys the array element at index subscript, for both indexed and associative arrays. Negative subscripts to indexed arrays are interpreted as described above. Unsetting the last element of an array variable does not unset the variable. unset name, where name is an array, removes the entire array. unset name[subscript], where subscript is * or @, behaves differently depending on whether name is an indexed or associative array. If name is an associative array, this unsets the element with subscript * or @. If name is an indexed array, unset removes all of the elements but does not remove the array itself. When using a variable name with a subscript as an argument to a command, such as with unset, without using the word expansion syntax described above, the argument is subject to pathname expansion. If pathname expansion is not desired, the argument should be quoted. The declare, local, and readonly builtins each accept a -a option to specify an indexed array and a -A option to specify an associative array. If both options are supplied, -A takes precedence. The read builtin accepts a -a option to assign a list of words read from the standard input to an array. The set and declare builtins display array values in a way that allows them to be reused as assignments. EXPANSION top Expansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion. The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion. On systems that can support it, there is an additional expansion available: process substitution. This is performed at the same time as tilde, parameter, variable, and arithmetic expansion and command substitution. After these expansions are performed, quote characters present in the original word are removed unless they have been quoted themselves (quote removal). Only brace expansion, word splitting, and pathname expansion can increase the number of words of the expansion; other expansions expand a single word to a single word. The only exceptions to this are the expansions of "$@" and "${name[@]}", and, in most cases, $* and ${name[*]} as explained above (see PARAMETERS). Brace Expansion Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to pathname expansion, but the filenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right. Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved. For example, a{d,c,b}e expands into `ade ace abe'. A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single letters, and incr, an optional increment, is an integer. When integers are supplied, the expression expands to each number between x and y, inclusive. Supplied integers may be prefixed with 0 to force each term to have the same width. When either x or y begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary. When letters are supplied, the expression expands to each character lexicographically between x and y, inclusive, using the default C locale. Note that both x and y must be of the same type (integer or letter). When the increment is supplied, it is used as the difference between each term. The default increment is 1 or -1 as appropriate. Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression. Any incorrectly formed brace expansion is left unchanged. A { or , may be quoted with a backslash to prevent its being considered part of a brace expression. To avoid conflicts with parameter expansion, the string ${ is not considered eligible for brace expansion, and inhibits brace expansion until the closing }. This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above example: mkdir /usr/local/src/bash/{old,new,dist,bugs} or chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}} Brace expansion introduces a slight incompatibility with historical versions of sh. sh does not treat opening or closing braces specially when they appear as part of a word, and preserves them in the output. Bash removes braces from words as a consequence of brace expansion. For example, a word entered to sh as file{1,2} appears identically in the output. The same word is output as file1 file2 after expansion by bash. If strict compatibility with sh is desired, start bash with the +B option or disable brace expansion with the +B option to the set command (see SHELL BUILTIN COMMANDS below). Tilde Expansion If a word begins with an unquoted tilde character (`~'), all of the characters preceding the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible login name. If this login name is the null string, the tilde is replaced with the value of the shell parameter HOME. If HOME is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name. If the tilde-prefix is a `~+', the value of the shell variable PWD replaces the tilde-prefix. If the tilde-prefix is a `~-', the value of the shell variable OLDPWD, if it is set, is substituted. If the characters following the tilde in the tilde- prefix consist of a number N, optionally prefixed by a `+' or a `-', the tilde-prefix is replaced with the corresponding element from the directory stack, as it would be displayed by the dirs builtin invoked with the tilde-prefix as an argument. If the characters following the tilde in the tilde-prefix consist of a number without a leading `+' or `-', `+' is assumed. If the login name is invalid, or the tilde expansion fails, the word is unchanged. Each variable assignment is checked for unquoted tilde-prefixes immediately following a : or the first =. In these cases, tilde expansion is also performed. Consequently, one may use filenames with tildes in assignments to PATH, MAILPATH, and CDPATH, and the shell assigns the expanded value. Bash also performs tilde expansion on words satisfying the conditions of variable assignments (as described above under PARAMETERS) when they appear as arguments to simple commands. Bash does not do this, except for the declaration commands listed above, when in posix mode. Parameter Expansion The `$' character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name. When braces are used, the matching ending brace is the first `}' not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion. ${parameter} The value of parameter is substituted. The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character which is not to be interpreted as part of its name. The parameter is a shell parameter as described above PARAMETERS) or an array reference (Arrays). If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new parameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as indirect expansion. The value is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. If parameter is a nameref, this expands to the name of the parameter referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection. In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. When not performing substring expansion, using the forms documented below (e.g., :-), bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset. ${parameter:-word} Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted. ${parameter:=word} Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way. ${parameter:?word} Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted. ${parameter:+word} Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted. ${parameter:offset} ${parameter:offset:length} Substring Expansion. Expands to up to length characters of the value of parameter starting at the character specified by offset. If parameter is @ or *, an indexed array subscripted by @ or *, or an associative array name, the results differ as described below. If length is omitted, expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see ARITHMETIC EVALUATION below). If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the :- expansion. If parameter is @ or *, the result is length positional parameters beginning at offset. A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is an expansion error if length evaluates to a number less than zero. If parameter is an indexed array name subscripted by @ or *, the result is the length members of the array beginning with ${parameter[offset]}. A negative offset is taken relative to one greater than the maximum index of the specified array. It is an expansion error if length evaluates to a number less than zero. Substring expansion applied to an associative array produces undefined results. Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default. If offset is 0, and the positional parameters are used, $0 is prefixed to the list. ${!prefix*} ${!prefix@} Names matching prefix. Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable. When @ is used and the expansion appears within double quotes, each variable name expands to a separate word. ${!name[@]} ${!name[*]} List of array keys. If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When @ is used and the expansion appears within double quotes, each key expands to a separate word. ${#parameter} Parameter length. The length in characters of the value of parameter is substituted. If parameter is * or @, the value substituted is the number of positional parameters. If parameter is an array name subscripted by * or @, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element. ${parameter#word} ${parameter##word} Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pattern Matching below. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``#'' case) or the longest matching pattern (the ``##'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter%word} ${parameter%%word} Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion, and matched against the expanded value of parameter using the rules described under Pattern Matching below. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ``%'' case) or the longest matching pattern (the ``%%'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter/pattern/string} ${parameter//pattern/string} ${parameter/#pattern/string} ${parameter/%pattern/string} Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. string undergoes tilde expansion, parameter and variable expansion, arithmetic expansion, command and process substitution, and quote removal. The match is performed using the rules described under Pattern Matching below. In the first form above, only the first match is replaced. If there are two slashes separating parameter and pattern (the second form above), all matches of pattern are replaced with string. If pattern is preceded by # (the third form above), it must match at the beginning of the expanded value of parameter. If pattern is preceded by % (the fourth form above), it must match at the end of the expanded value of parameter. If the expansion of string is null, matches of pattern are deleted. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If the patsub_replacement shell option is enabled using shopt, any unquoted instances of & in string are replaced with the matching portion of pattern. Quoting any part of string inhibits replacement in the expansion of the quoted portion, including replacement strings stored in shell variables. Backslash will escape & in string; the backslash is removed in order to permit a literal & in the replacement string. Backslash can also be used to escape a backslash; \\ results in a literal backslash in the replacement. Users should take care if string is double-quoted to avoid unwanted interactions between the backslash and double-quoting, since backslash has special meaning within double quotes. Pattern substitution performs the check for unquoted & after expanding string; shell programmers should quote any occurrences of & they want to be taken literally in the replacement and ensure any instances of & they want to be replaced are unquoted. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter^pattern} ${parameter^^pattern} ${parameter,pattern} ${parameter,,pattern} Case modification. This expansion modifies the case of alphabetic characters in parameter. The pattern is expanded to produce a pattern just as in pathname expansion. Each character in the expanded value of parameter is tested against pattern, and, if it matches the pattern, its case is converted. The pattern should not attempt to match more than one character. The ^ operator converts lowercase letters matching pattern to uppercase; the , operator converts matching uppercase letters to lowercase. The ^^ and ,, expansions convert each matched character in the expanded value; the ^ and , expansions match and convert only the first character in the expanded value. If pattern is omitted, it is treated like a ?, which matches every character. If parameter is @ or *, the case modification operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the case modification operation is applied to each member of the array in turn, and the expansion is the resultant list. ${parameter@operator} Parameter transformation. The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter: U The expansion is a string that is the value of parameter with lowercase alphabetic characters converted to uppercase. u The expansion is a string that is the value of parameter with the first character converted to uppercase, if it is alphabetic. L The expansion is a string that is the value of parameter with uppercase alphabetic characters converted to lowercase. Q The expansion is a string that is the value of parameter quoted in a format that can be reused as input. E The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'...' quoting mechanism. P The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see PROMPTING below). A The expansion is a string in the form of an assignment statement or declare command that, if evaluated, will recreate parameter with its attributes and value. K Produces a possibly-quoted version of the value of parameter, except that it prints the values of indexed and associative arrays as a sequence of quoted key-value pairs (see Arrays above). a The expansion is a string consisting of flag values representing parameter's attributes. k Like the K transformation, but expands the keys and values of indexed and associative arrays to separate words after word splitting. If parameter is @ or *, the operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the operation is applied to each member of the array in turn, and the expansion is the resultant list. The result of the expansion is subject to word splitting and pathname expansion as described below. Command Substitution Command substitution allows the output of a command to replace the command name. There are two forms: $(command) or `command` Bash performs the expansion by executing command in a subshell environment and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file). When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \. The first backquote not preceded by a backslash terminates the command substitution. When using the $(command) form, all characters between the parentheses make up the command; none are treated specially. Command substitutions may be nested. To nest when using the backquoted form, escape the inner backquotes with backslashes. If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results. Arithmetic Expansion Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is: $((expression)) The expression undergoes the same expansions as if it were within double quotes, but double quote characters in expression are not treated specially and are removed. All tokens in the expression undergo parameter and variable expansion, command substitution, and quote removal. The result is treated as the arithmetic expression to be evaluated. Arithmetic expansions may be nested. The evaluation is performed according to the rules listed below under ARITHMETIC EVALUATION. If expression is invalid, bash prints a message indicating failure and no substitution occurs. Process Substitution Process substitution allows a process's input or output to be referred to using a filename. It takes the form of <(list) or >(list). The process list is run asynchronously, and its input or output appears as a filename. This filename is passed as an argument to the current command as the result of the expansion. If the >(list) form is used, writing to the file will provide input for list. If the <(list) form is used, the file passed as an argument should be read to obtain the output of list. Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files. When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion. Word Splitting The shell scans the results of parameter expansion, command substitution, and arithmetic expansion that did not occur within double quotes for word splitting. The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words using these characters as field terminators. If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>, <tab>, and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters space, tab, and newline are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs. Explicit null arguments ("" or '') are retained and passed to commands as empty strings. Unquoted implicit null arguments, resulting from the expansion of parameters that have no values, are removed. If a parameter with no value is expanded within double quotes, a null argument results and is retained and passed to a command as an empty string. When a quoted null argument appears as part of a word whose expansion is non-null, the null argument is removed. That is, the word -d'' becomes -d after word splitting and null argument removal. Note that if no expansion occurs, no splitting is performed. Pathname Expansion After word splitting, unless the -f option has been set, bash scans each word for the characters *, ?, and [. If one of these characters appears, and is not quoted, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern (see Pattern Matching below). If no matching filenames are found, and the shell option nullglob is not enabled, the word is left unchanged. If the nullglob option is set, and no matches are found, the word is removed. If the failglob shell option is set, and no matches are found, an error message is printed and the command is not executed. If the shell option nocaseglob is enabled, the match is performed without regard to the case of alphabetic characters. When a pattern is used for pathname expansion, the character ``.'' at the start of a name or immediately following a slash must be matched explicitly, unless the shell option dotglob is set. In order to match the filenames ``.'' and ``..'', the pattern must begin with ``.'' (for example, ``.?''), even if dotglob is set. If the globskipdots shell option is enabled, the filenames ``.'' and ``..'' are never matched, even if the pattern begins with a ``.''. When not matching pathnames, the ``.'' character is not treated specially. When matching a pathname, the slash character must always be matched explicitly by a slash in the pattern, but in other matching contexts it can be matched by a special pattern character as described below under Pattern Matching. See the description of shopt below under SHELL BUILTIN COMMANDS for a description of the nocaseglob, nullglob, globskipdots, failglob, and dotglob shell options. The GLOBIGNORE shell variable may be used to restrict the set of file names matching a pattern. If GLOBIGNORE is set, each matching file name that also matches one of the patterns in GLOBIGNORE is removed from the list of matches. If the nocaseglob option is set, the matching against the patterns in GLOBIGNORE is performed without regard to case. The filenames ``.'' and ``..'' are always ignored when GLOBIGNORE is set and not null. However, setting GLOBIGNORE to a non-null value has the effect of enabling the dotglob shell option, so all other filenames beginning with a ``.'' will match. To get the old behavior of ignoring filenames beginning with a ``.'', make ``.*'' one of the patterns in GLOBIGNORE. The dotglob option is disabled when GLOBIGNORE is unset. The pattern matching honors the setting of the extglob shell option. Pattern Matching Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL character may not occur in a pattern. A backslash escapes the following character; the escaping backslash is discarded when matching. The special pattern characters must be quoted if they are to be matched literally. The special pattern characters have the following meanings: * Matches any string, including the null string. When the globstar shell option is enabled, and * is used in a pathname expansion context, two adjacent *s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a /, two adjacent *s will match only directories and subdirectories. ? Matches any single character. [...] Matches any one of the enclosed characters. A pair of characters separated by a hyphen denotes a range expression; any character that falls between those two characters, inclusive, using the current locale's collating sequence and character set, is matched. If the first character following the [ is a ! or a ^ then any character not enclosed is matched. The sorting order of characters in range expressions, and the characters included in the range, are determined by the current locale and the values of the LC_COLLATE or LC_ALL shell variables, if set. To obtain the traditional interpretation of range expressions, where [a-d] is equivalent to [abcd], set value of the LC_ALL shell variable to C, or enable the globasciiranges shell option. A - may be matched by including it as the first or last character in the set. A ] may be matched by including it as the first character in the set. Within [ and ], character classes can be specified using the syntax [:class:], where class is one of the following classes defined in the POSIX standard: alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit A character class matches any character belonging to that class. The word character class matches letters, digits, and the character _. Within [ and ], an equivalence class can be specified using the syntax [=c=], which matches all characters with the same collation weight (as defined by the current locale) as the character c. Within [ and ], the syntax [.symbol.] matches the collating symbol symbol. If the extglob shell option is enabled using the shopt builtin, the shell recognizes several extended pattern matching operators. In the following description, a pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns: ?(pattern-list) Matches zero or one occurrence of the given patterns *(pattern-list) Matches zero or more occurrences of the given patterns +(pattern-list) Matches one or more occurrences of the given patterns @(pattern-list) Matches one of the given patterns !(pattern-list) Matches anything except one of the given patterns Theextglob option changes the behavior of the parser, since the parentheses are normally treated as operators with syntactic meaning. To ensure that extended matching patterns are parsed correctly, make sure that extglob is enabled before parsing constructs containing the patterns, including shell functions and command substitutions. When matching filenames, the dotglob shell option determines the set of filenames that are tested: when dotglob is enabled, the set of filenames includes all files beginning with ``.'', but ``.'' and ``..'' must be matched by a pattern or sub-pattern that begins with a dot; when it is disabled, the set does not include any filenames beginning with ``.'' unless the pattern or sub- pattern begins with a ``.''. As above, ``.'' only has a special meaning when matching filenames. Complicated extended pattern matching against long strings is slow, especially when the patterns contain alternations and the strings contain multiple matches. Using separate matches against shorter strings, or using arrays of strings instead of a single long string, may be faster. Quote Removal After the preceding expansions, all unquoted occurrences of the characters \, ', and " that did not result from one of the above expansions are removed. REDIRECTION top Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection allows commands' file handles to be duplicated, opened, closed, made to refer to different files, and can change the files the command reads from and writes to. Redirection may also be used to modify file handles in the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right. Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than or equal to 10 and assign it to varname. If >&- or <&- is preceded by {varname}, the value of varname defines the file descriptor to close. If {varname} is supplied, the redirection persists beyond the scope of the command, allowing the shell programmer to manage the file descriptor's lifetime manually. The varredir_close shell option manages this behavior. In the following descriptions, if the file descriptor number is omitted, and the first character of the redirection operator is <, the redirection refers to the standard input (file descriptor 0). If the first character of the redirection operator is >, the redirection refers to the standard output (file descriptor 1). The word following the redirection operator in the following descriptions, unless otherwise noted, is subjected to brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, quote removal, pathname expansion, and word splitting. If it expands to more than one word, bash reports an error. Note that the order of redirections is significant. For example, the command ls > dirlist 2>&1 directs both standard output and standard error to the file dirlist, while the command ls 2>&1 > dirlist directs only the standard output to file dirlist, because the standard error was duplicated from the standard output before the standard output was redirected to dirlist. Bash handles several filenames specially when they are used in redirections, as described in the following table. If the operating system on which bash is running provides these special files, bash will use them; otherwise it will emulate them internally with the behavior described below. /dev/fd/fd If fd is a valid integer, file descriptor fd is duplicated. /dev/stdin File descriptor 0 is duplicated. /dev/stdout File descriptor 1 is duplicated. /dev/stderr File descriptor 2 is duplicated. /dev/tcp/host/port If host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts to open the corresponding TCP socket. /dev/udp/host/port If host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts to open the corresponding UDP socket. A failure to open or create a file causes the redirection to fail. Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally. Redirecting Input Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified. The general format for redirecting input is: [n]<word Redirecting Output Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size. The general format for redirecting output is: [n]>word If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file. If the redirection operator is >|, or the redirection operator is > and the noclobber option to the set builtin command is not enabled, the redirection is attempted even if the file named by word exists. Appending Redirected Output Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created. The general format for appending output is: [n]>>word Redirecting Standard Output and Standard Error This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word. There are two formats for redirecting standard output and standard error: &>word and >&word Of the two forms, the first is preferred. This is semantically equivalent to >word 2>&1 When using the second form, word may not expand to a number or -. If it does, other redirection operators apply (see Duplicating File Descriptors below) for compatibility reasons. Appending Standard Output and Standard Error This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be appended to the file whose name is the expansion of word. The format for appending standard output and standard error is: &>>word This is semantically equivalent to >>word 2>&1 (see Duplicating File Descriptors below). Here Documents This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input (or file descriptor n if n is specified) for a command. The format of here-documents is: [n]<<[-]word here-document delimiter No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `. If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion. Here Strings A variant of here documents, the format is: [n]<<<word The word undergoes tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal. Pathname expansion and word splitting are not performed. The result is supplied as a single string, with a newline appended, to the command on its standard input (or file descriptor n if n is specified). Duplicating File Descriptors The redirection operator [n]<&word is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to -, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used. The operator [n]>&word is used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. If the digits in word do not specify a file descriptor open for output, a redirection error occurs. If word evaluates to -, file descriptor n is closed. As a special case, if n is omitted, and word does not expand to one or more digits or -, the standard output and standard error are redirected as described previously. Moving File Descriptors The redirection operator [n]<&digit- moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit is closed after being duplicated to n. Similarly, the redirection operator [n]>&digit- moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified. Opening File Descriptors for Reading and Writing The redirection operator [n]<>word causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created. ALIASES top Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands (see SHELL BUILTIN COMMANDS below). The first word of each simple command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. The characters /, $, `, and = and any of the shell metacharacters or quoting characters listed above may not appear in an alias name. The replacement text may contain any valid shell input, including shell metacharacters. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to ls -F, for instance, and bash does not try to recursively expand the replacement text. If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion. Aliases are created and listed with the alias command, and removed with the unalias command. There is no mechanism for using arguments in the replacement text. If arguments are needed, use a shell function (see FUNCTIONS below). Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below). The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input, and all lines that make up a compound command, before executing any of the commands on that line or the compound command. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands. For almost every purpose, aliases are superseded by shell functions. FUNCTIONS top A shell function, defined as described above under SHELL GRAMMAR, stores a series of commands for later execution. When the name of a shell function is used as a simple command name, the list of commands associated with that function name is executed. Functions are executed in the context of the current shell; no new process is created to interpret them (contrast this with the execution of a shell script). When a function is executed, the arguments to the function become the positional parameters during its execution. The special parameter # is updated to reflect the change. Special parameter 0 is unchanged. The first element of the FUNCNAME variable is set to the name of the function while the function is executing. All other aspects of the shell execution environment are identical between a function and its caller with these exceptions: the DEBUG and RETURN traps (see the description of the trap builtin under SHELL BUILTIN COMMANDS below) are not inherited unless the function has been given the trace attribute (see the description of the declare builtin below) or the -o functrace shell option has been enabled with the set builtin (in which case all functions inherit the DEBUG and RETURN traps), and the ERR trap is not inherited unless the -o errtrace shell option has been enabled. Variables local to the function may be declared with the local builtin command (local variables). Ordinarily, variables and their values are shared between the function and its caller. If a variable is declared local, the variable's visible scope is restricted to that function and its children (including the functions it calls). In the following description, the current scope is a currently- executing function. Previous scopes consist of that function's caller and so on, back to the "global" scope, where the shell is not executing any shell function. Consequently, a local variable at the current scope is a variable declared using the local or declare builtins in the function that is currently executing. Local variables "shadow" variables with the same name declared at previous scopes. For instance, a local variable declared in a function hides a global variable of the same name: references and assignments refer to the local variable, leaving the global variable unmodified. When the function returns, the global variable is once again visible. The shell uses dynamic scoping to control a variable's visibility within functions. With dynamic scoping, visible variables and their values are a result of the sequence of function calls that caused execution to reach the current function. The value of a variable that a function sees depends on its value within its caller, if any, whether that caller is the "global" scope or another shell function. This is also the value that a local variable declaration "shadows", and the value that is restored when the function returns. For example, if a variable var is declared as local in function func1, and func1 calls another function func2, references to var made from within func2 will resolve to the local variable var from func1, shadowing any global variable named var. The unset builtin also acts using the same dynamic scope: if a variable is local to the current scope, unset will unset it; otherwise the unset will refer to the variable found in any calling scope as described above. If a variable at the current local scope is unset, it will remain so (appearing as unset) until it is reset in that scope or until the function returns. Once the function returns, any instance of the variable at a previous scope will become visible. If the unset acts on a variable at a previous scope, any instance of a variable with that name that had been shadowed will become visible (see below how the localvar_unset shell option changes this behavior). The FUNCNEST variable, if set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed the limit cause the entire command to abort. If the builtin command return is executed in a function, the function completes and execution resumes with the next command after the function call. Any command associated with the RETURN trap is executed before execution resumes. When a function completes, the values of the positional parameters and the special parameter # are restored to the values they had prior to the function's execution. Function names and definitions may be listed with the -f option to the declare or typeset builtin commands. The -F option to declare or typeset will list the function names only (and optionally the source file and line number, if the extdebug shell option is enabled). Functions may be exported so that child shell processes (those created when executing a separate shell invocation) automatically have them defined with the -f option to the export builtin. A function definition may be deleted using the -f option to the unset builtin. Functions may be recursive. The FUNCNEST variable may be used to limit the depth of the function call stack and restrict the number of function invocations. By default, no limit is imposed on the number of recursive calls. ARITHMETIC EVALUATION top The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and declare builtin commands, the (( compound command, and Arithmetic Expansion). Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error. The operators and their precedence, associativity, and values are the same as in the C language. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence. id++ id-- variable post-increment and post-decrement - + unary minus and plus ++id --id variable pre-increment and pre-decrement ! ~ logical and bitwise negation ** exponentiation * / % multiplication, division, remainder + - addition, subtraction << >> left and right bitwise shifts <= >= < > comparison == != equality and inequality & bitwise AND ^ bitwise exclusive OR | bitwise OR && logical AND || logical OR expr?expr:expr conditional operator = *= /= %= += -= <<= >>= &= ^= |= assignment expr1 , expr2 comma Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. A shell variable that is null or unset evaluates to 0 when referenced by name without using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression when it is referenced, or when a variable which has been given the integer attribute using declare -i is assigned a value. A null value evaluates to 0. A shell variable need not have its integer attribute turned on to be used in an expression. Integer constants follow the C language definition, without suffixes or character constants. Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimal. Otherwise, numbers take the form [base#]n, where the optional base is a decimal number between 2 and 64 representing the arithmetic base, and n is a number in that base. If base# is omitted, then base 10 is used. When specifying n, if a non-digit is required, the digits greater than 9 are represented by the lowercase letters, the uppercase letters, @, and _, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35. Operators are evaluated in order of precedence. Sub-expressions in parentheses are evaluated first and may override the precedence rules above. CONDITIONAL EXPRESSIONS top Conditional expressions are used by the [[ compound command and the test and [ builtin commands to test file attributes and perform string and arithmetic comparisons. The test and [ commands determine their behavior based on the number of arguments; see the descriptions of those commands for any other command-specific actions. Expressions are formed from the following unary or binary primaries. Bash handles several filenames specially when they are used in expressions. If the operating system on which bash is running provides these special files, bash will use them; otherwise it will emulate them internally with this behavior: If any file argument to one of the primaries is of the form /dev/fd/n, then file descriptor n is checked. If the file argument to one of the primaries is one of /dev/stdin, /dev/stdout, or /dev/stderr, file descriptor 0, 1, or 2, respectively, is checked. Unless otherwise specified, primaries that operate on files follow symbolic links and operate on the target of the link, rather than the link itself. When used with [[, the < and > operators sort lexicographically using the current locale. The test command sorts using ASCII ordering. -a file True if file exists. -b file True if file exists and is a block special file. -c file True if file exists and is a character special file. -d file True if file exists and is a directory. -e file True if file exists. -f file True if file exists and is a regular file. -g file True if file exists and is set-group-id. -h file True if file exists and is a symbolic link. -k file True if file exists and its ``sticky'' bit is set. -p file True if file exists and is a named pipe (FIFO). -r file True if file exists and is readable. -s file True if file exists and has a size greater than zero. -t fd True if file descriptor fd is open and refers to a terminal. -u file True if file exists and its set-user-id bit is set. -w file True if file exists and is writable. -x file True if file exists and is executable. -G file True if file exists and is owned by the effective group id. -L file True if file exists and is a symbolic link. -N file True if file exists and has been modified since it was last read. -O file True if file exists and is owned by the effective user id. -S file True if file exists and is a socket. file1 -ef file2 True if file1 and file2 refer to the same device and inode numbers. file1 -nt file2 True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not. file1 -ot file2 True if file1 is older than file2, or if file2 exists and file1 does not. -o optname True if the shell option optname is enabled. See the list of options under the description of the -o option to the set builtin below. -v varname True if the shell variable varname is set (has been assigned a value). -R varname True if the shell variable varname is set and is a name reference. -z string True if the length of string is zero. string -n string True if the length of string is non-zero. string1 == string2 string1 = string2 True if the strings are equal. = should be used with the test command for POSIX conformance. When used with the [[ command, this performs pattern matching as described above (Compound Commands). string1 != string2 True if the strings are not equal. string1 < string2 True if string1 sorts before string2 lexicographically. string1 > string2 True if string1 sorts after string2 lexicographically. arg1 OP arg2 OP is one of -eq, -ne, -lt, -le, -gt, or -ge. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2, respectively. Arg1 and arg2 may be positive or negative integers. When used with the [[ command, Arg1 and Arg2 are evaluated as arithmetic expressions (see ARITHMETIC EVALUATION above). SIMPLE COMMAND EXPANSION top When a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right, in the following order. 1. The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later processing. 2. The words that are not variable assignments or redirections are expanded. If any words remain after expansion, the first word is taken to be the name of the command and the remaining words are the arguments. 3. Redirections are performed as described above under REDIRECTION. 4. The text after the = in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the variable. If no command name results, the variable assignments affect the current shell environment. In the case of such a command (one that consists only of assignment statements and redirections), assignment statements are performed before redirections. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign a value to a readonly variable, an error occurs, and the command exits with a non-zero status. If no command name results, redirections are performed, but do not affect the current shell environment. A redirection error causes the command to exit with a non-zero status. If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero. COMMAND EXECUTION top After a command has been split into words, if it results in a simple command and an optional list of arguments, the following actions are taken. If the command name contains no slashes, the shell attempts to locate it. If there exists a shell function by that name, that function is invoked as described above in FUNCTIONS. If the name does not match a function, the shell searches for it in the list of shell builtins. If a match is found, that builtin is invoked. If the name is neither a shell function nor a builtin, and contains no slashes, bash searches each element of the PATH for a directory containing an executable file by that name. Bash uses a hash table to remember the full pathnames of executable files (see hash under SHELL BUILTIN COMMANDS below). A full search of the directories in PATH is performed only if the command is not found in the hash table. If the search is unsuccessful, the shell searches for a defined shell function named command_not_found_handle. If that function exists, it is invoked in a separate execution environment with the original command and the original command's arguments as its arguments, and the function's exit status becomes the exit status of that subshell. If that function is not defined, the shell prints an error message and returns an exit status of 127. If the search is successful, or if the command name contains one or more slashes, the shell executes the named program in a separate execution environment. Argument 0 is set to the name given, and the remaining arguments to the command are set to the arguments given, if any. If this execution fails because the file is not in executable format, and the file is not a directory, it is assumed to be a shell script, a file containing shell commands, and the shell creates a new instance of itself to execute it. This subshell reinitializes itself, so that the effect is as if a new shell had been invoked to handle the script, with the exception that the locations of commands remembered by the parent (see hash below under SHELL BUILTIN COMMANDS) are retained by the child. If the program is a file beginning with #!, the remainder of the first line specifies an interpreter for the program. The shell executes the specified interpreter on operating systems that do not handle this executable format themselves. The arguments to the interpreter consist of a single optional argument following the interpreter name on the first line of the program, followed by the name of the program, followed by the command arguments, if any. COMMAND EXECUTION ENVIRONMENT top The shell has an execution environment, which consists of the following: open files inherited by the shell at invocation, as modified by redirections supplied to the exec builtin the current working directory as set by cd, pushd, or popd, or inherited by the shell at invocation the file creation mode mask as set by umask or inherited from the shell's parent current traps set by trap shell parameters that are set by variable assignment or with set or inherited from the shell's parent in the environment shell functions defined during execution or inherited from the shell's parent in the environment options enabled at invocation (either by default or with command-line arguments) or by set options enabled by shopt shell aliases defined with alias various process IDs, including those of background jobs, the value of $$, and the value of PPID When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited from the shell. the shell's open files, plus any modifications and additions specified by redirections to the command the current working directory the file creation mode mask shell variables and functions marked for export, along with variables exported for the command, passed in the environment traps caught by the shell are reset to the values inherited from the shell's parent, and traps ignored by the shell are ignored A command invoked in this separate environment cannot affect the shell's execution environment. A subshell is a copy of the shell process. Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell's execution environment. Subshells spawned to execute command substitutions inherit the value of the -e option from the parent shell. When not in posix mode, bash clears the -e option in such subshells. If a command is followed by a & and job control is not active, the default standard input for the command is the empty file /dev/null. Otherwise, the invoked command inherits the file descriptors of the calling shell as modified by redirections. ENVIRONMENT top When a program is invoked it is given an array of strings called the environment. This is a list of name-value pairs, of the form name=value. The shell provides several ways to manipulate the environment. On invocation, the shell scans its own environment and creates a parameter for each name found, automatically marking it for export to child processes. Executed commands inherit the environment. The export and declare -x commands allow parameters and functions to be added to and deleted from the environment. If the value of a parameter in the environment is modified, the new value becomes part of the environment, replacing the old. The environment inherited by any executed command consists of the shell's initial environment, whose values may be modified in the shell, less any pairs removed by the unset command, plus any additions via the export and declare -x commands. The environment for any simple command or function may be augmented temporarily by prefixing it with parameter assignments, as described above in PARAMETERS. These assignment statements affect only the environment seen by that command. If the -k option is set (see the set builtin command below), then all parameter assignments are placed in the environment for a command, not just those that precede the command name. When bash invokes an external command, the variable _ is set to the full filename of the command and passed to that command in its environment. EXIT STATUS top The exit status of an executed command is the value returned by the waitpid system call or equivalent function. Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. Exit statuses from shell builtins and compound commands are also limited to this range. Under certain circumstances, the shell will use special values to indicate specific failure modes. For the shell's purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. A non-zero exit status indicates failure. When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status. If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126. If a command fails because of an error during expansion or redirection, the exit status is greater than zero. Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage, generally invalid options or missing arguments. The exit status of the last command is available in the special parameter $?. Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in which case it exits with a non- zero value. See also the exit builtin command below. SIGNALS top When bash is interactive, in the absence of any traps, it ignores SIGTERM (so that kill 0 does not kill an interactive shell), and SIGINT is caught and handled (so that the wait builtin is interruptible). In all cases, bash ignores SIGQUIT. If job control is in effect, bash ignores SIGTTIN, SIGTTOU, and SIGTSTP. Non-builtin commands run by bash have signal handlers set to the values inherited by the shell from its parent. When job control is not in effect, asynchronous commands ignore SIGINT and SIGQUIT in addition to these inherited handlers. Commands run as a result of command substitution ignore the keyboard-generated job control signals SIGTTIN, SIGTTOU, and SIGTSTP. The shell exits by default upon receipt of a SIGHUP. Before exiting, an interactive shell resends the SIGHUP to all jobs, running or stopped. Stopped jobs are sent SIGCONT to ensure that they receive the SIGHUP. To prevent the shell from sending the signal to a particular job, it should be removed from the jobs table with the disown builtin (see SHELL BUILTIN COMMANDS below) or marked to not receive SIGHUP using disown -h. If the huponexit shell option has been set with shopt, bash sends a SIGHUP to all jobs when an interactive login shell exits. If bash is waiting for a command to complete and receives a signal for which a trap has been set, the trap will not be executed until the command completes. When bash is waiting for an asynchronous command via the wait builtin, the reception of a signal for which a trap has been set will cause the wait builtin to return immediately with an exit status greater than 128, immediately after which the trap is executed. When job control is not enabled, and bash is waiting for a foreground command to complete, the shell receives keyboard- generated signals such as SIGINT (usually generated by ^C) that users commonly intend to send to that command. This happens because the shell and the command are in the same process group as the terminal, and ^C sends SIGINT to all processes in that process group. When bash is running without job control enabled and receives SIGINT while waiting for a foreground command, it waits until that foreground command terminates and then decides what to do about the SIGINT: 1. If the command terminates due to the SIGINT, bash concludes that the user meant to end the entire script, and acts on the SIGINT (e.g., by running a SIGINT trap or exiting itself); 2. If the command does not terminate due to SIGINT, the program handled the SIGINT itself and did not treat it as a fatal signal. In that case, bash does not treat SIGINT as a fatal signal, either, instead assuming that the SIGINT was used as part of the program's normal operation (e.g., emacs uses it to abort editing commands) or deliberately discarded. However, bash will run any trap set on SIGINT, as it does with any other trapped signal it receives while it is waiting for the foreground command to complete, for compatibility. JOB CONTROL top Job control refers to the ability to selectively stop (suspend) the execution of processes and continue (resume) their execution at a later point. A user typically employs this facility via an interactive interface supplied jointly by the operating system kernel's terminal driver and bash. The shell associates a job with each pipeline. It keeps a table of currently executing jobs, which may be listed with the jobs command. When bash starts a job asynchronously (in the background), it prints a line that looks like: [1] 25647 indicating that this job is job number 1 and that the process ID of the last process in the pipeline associated with this job is 25647. All of the processes in a single pipeline are members of the same job. Bash uses the job abstraction as the basis for job control. To facilitate the implementation of the user interface to job control, the operating system maintains the notion of a current terminal process group ID. Members of this process group (processes whose process group ID is equal to the current terminal process group ID) receive keyboard-generated signals such as SIGINT. These processes are said to be in the foreground. Background processes are those whose process group ID differs from the terminal's; such processes are immune to keyboard-generated signals. Only foreground processes are allowed to read from or, if the user so specifies with stty tostop, write to the terminal. Background processes which attempt to read from (write to when stty tostop is in effect) the terminal are sent a SIGTTIN (SIGTTOU) signal by the kernel's terminal driver, which, unless caught, suspends the process. If the operating system on which bash is running supports job control, bash contains facilities to use it. Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. Typing the delayed suspend character (typically ^Y, Control-Y) causes the process to be stopped when it attempts to read input from the terminal, and control to be returned to bash. The user may then manipulate the state of this job, using the bg command to continue it in the background, the fg command to continue it in the foreground, or the kill command to kill it. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded. There are a number of ways to refer to a job in the shell. The character % introduces a job specification (jobspec). Job number n may be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For example, %ce refers to a stopped job whose command name begins with ce. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background. The previous job may be referenced using %-. If there is only a single job, %+ and %- can both be used to refer to that job. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -. A single % (with no accompanying job specification) also refers to the current job. Simply naming a job can be used to bring it into the foreground: %1 is a synonym for ``fg %1'', bringing job 1 from the background into the foreground. Similarly, ``%1 &'' resumes job 1 in the background, equivalent to ``bg %1''. The shell learns immediately whenever a job changes state. Normally, bash waits until it is about to print a prompt before reporting changes in a job's status so as to not interrupt any other output. If the -b option to the set builtin command is enabled, bash reports such changes immediately. Any trap on SIGCHLD is executed for each child that exits. If an attempt to exit bash is made while jobs are stopped (or, if the checkjobs shell option has been enabled using the shopt builtin, running), the shell prints a warning message, and, if the checkjobs option is enabled, lists the jobs and their statuses. The jobs command may then be used to inspect their status. If a second attempt to exit is made without an intervening command, the shell does not print another warning, and any stopped jobs are terminated. When the shell is waiting for a job or process using the wait builtin, and job control is enabled, wait will return when the job changes state. The -f option causes wait to wait until the job or process terminates before returning. PROMPTING top When executing interactively, bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash displays PS0 after it reads a command but before executing it. Bash displays PS4 as described above before tracing each command when the -x option is enabled. Bash allows these prompt strings to be customized by inserting a number of backslash-escaped special characters that are decoded as follows: \a an ASCII bell character (07) \d the date in "Weekday Month Date" format (e.g., "Tue May 26") \D{format} the format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required \e an ASCII escape character (033) \h the hostname up to the first `.' \H the hostname \j the number of jobs currently managed by the shell \l the basename of the shell's terminal device name \n newline \r carriage return \s the name of the shell, the basename of $0 (the portion following the final slash) \t the current time in 24-hour HH:MM:SS format \T the current time in 12-hour HH:MM:SS format \@ the current time in 12-hour am/pm format \A the current time in 24-hour HH:MM format \u the username of the current user \v the version of bash (e.g., 2.00) \V the release of bash, version + patch level (e.g., 2.00.0) \w the value of the PWD shell variable ($PWD), with $HOME abbreviated with a tilde (uses the value of the PROMPT_DIRTRIM variable) \W the basename of $PWD, with $HOME abbreviated with a tilde \! the history number of this command \# the command number of this command \$ if the effective UID is 0, a #, otherwise a $ \nnn the character corresponding to the octal number nnn \\ a backslash \[ begin a sequence of non-printing characters, which could be used to embed a terminal control sequence into the prompt \] end a sequence of non-printing characters The command number and the history number are usually different: the history number of a command is its position in the history list, which may include commands restored from the history file (see HISTORY below), while the command number is the position in the sequence of commands executed during the current shell session. After the string is decoded, it is expanded via parameter expansion, command substitution, arithmetic expansion, and quote removal, subject to the value of the promptvars shell option (see the description of the shopt command under SHELL BUILTIN COMMANDS below). This can have unwanted side effects if escaped portions of the string appear within command substitution or contain characters special to word expansion. READLINE top This is the library that handles reading input when using an interactive shell, unless the --noediting option is given at shell invocation. Line editing is also used when using the -e option to the read builtin. By default, the line editing commands are similar to those of Emacs. A vi-style line editing interface is also available. Line editing can be enabled at any time using the -o emacs or -o vi options to the set builtin (see SHELL BUILTIN COMMANDS below). To turn off line editing after the shell is running, use the +o emacs or +o vi options to the set builtin. Readline Notation In this section, the Emacs-style notation is used to denote keystrokes. Control keys are denoted by C-key, e.g., C-n means Control-N. Similarly, meta keys are denoted by M-key, so M-x means Meta-X. (On keyboards without a meta key, M-x means ESC x, i.e., press the Escape key then the x key. This makes ESC the meta prefix. The combination M-C-x means ESC-Control-x, or press the Escape key then hold the Control key while pressing the x key.) Readline commands may be given numeric arguments, which normally act as a repeat count. Sometimes, however, it is the sign of the argument that is significant. Passing a negative argument to a command that acts in the forward direction (e.g., kill-line) causes that command to act in a backward direction. Commands whose behavior with arguments deviates from this are noted below. When a command is described as killing text, the text deleted is saved for possible future retrieval (yanking). The killed text is saved in a kill ring. Consecutive kills cause the text to be accumulated into one unit, which can be yanked all at once. Commands which do not kill text separate the chunks of text on the kill ring. Readline Initialization Readline is customized by putting commands in an initialization file (the inputrc file). The name of this file is taken from the value of the INPUTRC variable. If that variable is unset, the default is ~/.inputrc. If that file does not exist or cannot be read, the ultimate default is /etc/inputrc. When a program which uses the readline library starts up, the initialization file is read, and the key bindings and variables are set. There are only a few basic constructs allowed in the readline initialization file. Blank lines are ignored. Lines beginning with a # are comments. Lines beginning with a $ indicate conditional constructs. Other lines denote key bindings and variable settings. The default key-bindings may be changed with an inputrc file. Other programs that use this library may add their own commands and bindings. For example, placing M-Control-u: universal-argument or C-Meta-u: universal-argument into the inputrc would make M-C-u execute the readline command universal-argument. The following symbolic character names are recognized: RUBOUT, DEL, ESC, LFD, NEWLINE, RET, RETURN, SPC, SPACE, and TAB. In addition to command names, readline allows keys to be bound to a string that is inserted when the key is pressed (a macro). Readline Key Bindings The syntax for controlling key bindings in the inputrc file is simple. All that is required is the name of the command or the text of a macro and a key sequence to which it should be bound. The name may be specified in one of two ways: as a symbolic key name, possibly with Meta- or Control- prefixes, or as a key sequence. When using the form keyname:function-name or macro, keyname is the name of a key spelled out in English. For example: Control-u: universal-argument Meta-Rubout: backward-kill-word Control-o: "> output" In the above example, C-u is bound to the function universal-argument, M-DEL is bound to the function backward-kill-word, and C-o is bound to run the macro expressed on the right hand side (that is, to insert the text ``> output'' into the line). In the second form, "keyseq":function-name or macro, keyseq differs from keyname above in that strings denoting an entire key sequence may be specified by placing the sequence within double quotes. Some GNU Emacs style key escapes can be used, as in the following example, but the symbolic character names are not recognized. "\C-u": universal-argument "\C-x\C-r": re-read-init-file "\e[11~": "Function Key 1" In this example, C-u is again bound to the function universal-argument. C-x C-r is bound to the function re-read-init-file, and ESC [ 1 1 ~ is bound to insert the text ``Function Key 1''. The full set of GNU Emacs style escape sequences is \C- control prefix \M- meta prefix \e an escape character \\ backslash \" literal " \' literal ' In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available: \a alert (bell) \b backspace \d delete \f form feed \n newline \r carriage return \t horizontal tab \v vertical tab \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) When entering the text of a macro, single or double quotes must be used to indicate a macro definition. Unquoted text is assumed to be a function name. In the macro body, the backslash escapes described above are expanded. Backslash will quote any other character in the macro text, including " and '. Bash allows the current readline key bindings to be displayed or modified with the bind builtin command. The editing mode may be switched during interactive use by using the -o option to the set builtin command (see SHELL BUILTIN COMMANDS below). Readline Variables Readline has variables that can be used to further customize its behavior. A variable may be set in the inputrc file with a statement of the form set variable-name value or using the bind builtin command (see SHELL BUILTIN COMMANDS below). Except where noted, readline variables can take the values On or Off (without regard to case). Unrecognized variable names are ignored. When a variable value is read, empty or null values, "on" (case-insensitive), and "1" are equivalent to On. All other values are equivalent to Off. The variables and their default values are: active-region-start-color A string variable that controls the text color and background when displaying the text in the active region (see the description of enable-active-region below). This string must not take up any physical character positions on the display, so it should consist only of terminal escape sequences. It is output to the terminal before displaying the text in the active region. This variable is reset to the default value whenever the terminal type changes. The default value is the string that puts the terminal in standout mode, as obtained from the terminal's terminfo description. A sample value might be "\e[01;33m". active-region-end-color A string variable that "undoes" the effects of active-region-start-color and restores "normal" terminal display appearance after displaying text in the active region. This string must not take up any physical character positions on the display, so it should consist only of terminal escape sequences. It is output to the terminal after displaying the text in the active region. This variable is reset to the default value whenever the terminal type changes. The default value is the string that restores the terminal from standout mode, as obtained from the terminal's terminfo description. A sample value might be "\e[0m". bell-style (audible) Controls what happens when readline wants to ring the terminal bell. If set to none, readline never rings the bell. If set to visible, readline uses a visible bell if one is available. If set to audible, readline attempts to ring the terminal's bell. bind-tty-special-chars (On) If set to On, readline attempts to bind the control characters treated specially by the kernel's terminal driver to their readline equivalents. blink-matching-paren (Off) If set to On, readline attempts to briefly move the cursor to an opening parenthesis when a closing parenthesis is inserted. colored-completion-prefix (Off) If set to On, when listing completions, readline displays the common prefix of the set of possible completions using a different color. The color definitions are taken from the value of the LS_COLORS environment variable. If there is a color definition in $LS_COLORS for the custom suffix "readline-colored-completion-prefix", readline uses this color for the common prefix instead of its default. colored-stats (Off) If set to On, readline displays possible completions using different colors to indicate their file type. The color definitions are taken from the value of the LS_COLORS environment variable. comment-begin (``#'') The string that is inserted when the readline insert-comment command is executed. This command is bound to M-# in emacs mode and to # in vi command mode. completion-display-width (-1) The number of screen columns used to display possible matches when performing completion. The value is ignored if it is less than 0 or greater than the terminal screen width. A value of 0 will cause matches to be displayed one per line. The default value is -1. completion-ignore-case (Off) If set to On, readline performs filename matching and completion in a case-insensitive fashion. completion-map-case (Off) If set to On, and completion-ignore-case is enabled, readline treats hyphens (-) and underscores (_) as equivalent when performing case-insensitive filename matching and completion. completion-prefix-display-length(0) The length in characters of the common prefix of a list of possible completions that is displayed without modification. When set to a value greater than zero, common prefixes longer than this value are replaced with an ellipsis when displaying possible completions. completion-query-items (100) This determines when the user is queried about viewing the number of possible completions generated by the possible-completions command. It may be set to any integer value greater than or equal to zero. If the number of possible completions is greater than or equal to the value of this variable, readline will ask whether or not the user wishes to view them; otherwise they are simply listed on the terminal. A zero value means readline should never ask; negative values are treated as zero. convert-meta (On) If set to On, readline will convert characters with the eighth bit set to an ASCII key sequence by stripping the eighth bit and prefixing an escape character (in effect, using escape as the meta prefix). The default is On, but readline will set it to Off if the locale contains eight- bit characters. This variable is dependent on the LC_CTYPE locale category, and may change if the locale is changed. disable-completion (Off) If set to On, readline will inhibit word completion. Completion characters will be inserted into the line as if they had been mapped to self-insert. echo-control-characters (On) When set to On, on operating systems that indicate they support it, readline echoes a character corresponding to a signal generated from the keyboard. editing-mode (emacs) Controls whether readline begins with a set of key bindings similar to Emacs or vi. editing-mode can be set to either emacs or vi. emacs-mode-string (@) If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when emacs editing mode is active. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escape sequences is available. Use the \1 and \2 escapes to begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. enable-active-region (On) The point is the current cursor position, and mark refers to a saved cursor position. The text between the point and mark is referred to as the region. When this variable is set to On, readline allows certain commands to designate the region as active. When the region is active, readline highlights the text in the region using the value of the active-region-start-color, which defaults to the string that enables the terminal's standout mode. The active region shows the text inserted by bracketed- paste and any matching text found by incremental and non- incremental history searches. enable-bracketed-paste (On) When set to On, readline configures the terminal to insert each paste into the editing buffer as a single string of characters, instead of treating each character as if it had been read from the keyboard. This prevents readline from executing any editing commands bound to key sequences appearing in the pasted text. enable-keypad (Off) When set to On, readline will try to enable the application keypad when it is called. Some systems need this to enable the arrow keys. enable-meta-key (On) When set to On, readline will try to enable any meta modifier key the terminal claims to support when it is called. On many terminals, the meta key is used to send eight-bit characters. expand-tilde (Off) If set to On, tilde expansion is performed when readline attempts word completion. history-preserve-point (Off) If set to On, the history code attempts to place point at the same location on each history line retrieved with previous-history or next-history. history-size (unset) Set the maximum number of history entries saved in the history list. If set to zero, any existing history entries are deleted and no new entries are saved. If set to a value less than zero, the number of history entries is not limited. By default, the number of history entries is set to the value of the HISTSIZE shell variable. If an attempt is made to set history-size to a non-numeric value, the maximum number of history entries will be set to 500. horizontal-scroll-mode (Off) When set to On, makes readline use a single line for display, scrolling the input horizontally on a single screen line when it becomes longer than the screen width rather than wrapping to a new line. This setting is automatically enabled for terminals of height 1. input-meta (Off) If set to On, readline will enable eight-bit input (that is, it will not strip the eighth bit from the characters it reads), regardless of what the terminal claims it can support. The name meta-flag is a synonym for this variable. The default is Off, but readline will set it to On if the locale contains eight-bit characters. This variable is dependent on the LC_CTYPE locale category, and may change if the locale is changed. isearch-terminators (``C-[C-J'') The string of characters that should terminate an incremental search without subsequently executing the character as a command. If this variable has not been given a value, the characters ESC and C-J will terminate an incremental search. keymap (emacs) Set the current readline keymap. The set of valid keymap names is emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-command, and vi-insert. vi is equivalent to vi-command; emacs is equivalent to emacs-standard. The default value is emacs; the value of editing-mode also affects the default keymap. keyseq-timeout (500) Specifies the duration readline will wait for a character when reading an ambiguous key sequence (one that can form a complete key sequence using the input read so far, or can take additional input to complete a longer key sequence). If no input is received within the timeout, readline will use the shorter but complete key sequence. The value is specified in milliseconds, so a value of 1000 means that readline will wait one second for additional input. If this variable is set to a value less than or equal to zero, or to a non-numeric value, readline will wait until another key is pressed to decide which key sequence to complete. mark-directories (On) If set to On, completed directory names have a slash appended. mark-modified-lines (Off) If set to On, history lines that have been modified are displayed with a preceding asterisk (*). mark-symlinked-directories (Off) If set to On, completed names which are symbolic links to directories have a slash appended (subject to the value of mark-directories). match-hidden-files (On) This variable, when set to On, causes readline to match files whose names begin with a `.' (hidden files) when performing filename completion. If set to Off, the leading `.' must be supplied by the user in the filename to be completed. menu-complete-display-prefix (Off) If set to On, menu completion displays the common prefix of the list of possible completions (which may be empty) before cycling through the list. output-meta (Off) If set to On, readline will display characters with the eighth bit set directly rather than as a meta-prefixed escape sequence. The default is Off, but readline will set it to On if the locale contains eight-bit characters. This variable is dependent on the LC_CTYPE locale category, and may change if the locale is changed. page-completions (On) If set to On, readline uses an internal more-like pager to display a screenful of possible completions at a time. print-completions-horizontally (Off) If set to On, readline will display completions with matches sorted horizontally in alphabetical order, rather than down the screen. revert-all-at-newline (Off) If set to On, readline will undo all changes to history lines before returning when accept-line is executed. By default, history lines may be modified and retain individual undo lists across calls to readline. show-all-if-ambiguous (Off) This alters the default behavior of the completion functions. If set to On, words which have more than one possible completion cause the matches to be listed immediately instead of ringing the bell. show-all-if-unmodified (Off) This alters the default behavior of the completion functions in a fashion similar to show-all-if-ambiguous. If set to On, words which have more than one possible completion without any possible partial completion (the possible completions don't share a common prefix) cause the matches to be listed immediately instead of ringing the bell. show-mode-in-prompt (Off) If set to On, add a string to the beginning of the prompt indicating the editing mode: emacs, vi command, or vi insertion. The mode strings are user-settable (e.g., emacs-mode-string). skip-completed-text (Off) If set to On, this alters the default completion behavior when inserting a single match into the line. It's only active when performing completion in the middle of a word. If enabled, readline does not insert characters from the completion that match characters after point in the word being completed, so portions of the word following the cursor are not duplicated. vi-cmd-mode-string ((cmd)) If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when vi editing mode is active and in command mode. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escape sequences is available. Use the \1 and \2 escapes to begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. vi-ins-mode-string ((ins)) If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when vi editing mode is active and in insertion mode. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escape sequences is available. Use the \1 and \2 escapes to begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. visible-stats (Off) If set to On, a character denoting a file's type as reported by stat(2) is appended to the filename when listing possible completions. Readline Conditional Constructs Readline implements a facility similar in spirit to the conditional compilation features of the C preprocessor which allows key bindings and variable settings to be performed as the result of tests. There are four parser directives used. $if The $if construct allows bindings to be made based on the editing mode, the terminal being used, or the application using readline. The text of the test, after any comparison operator, extends to the end of the line; unless otherwise noted, no characters are required to isolate it. mode The mode= form of the $if directive is used to test whether readline is in emacs or vi mode. This may be used in conjunction with the set keymap command, for instance, to set bindings in the emacs-standard and emacs-ctlx keymaps only if readline is starting out in emacs mode. term The term= form may be used to include terminal- specific key bindings, perhaps to bind the key sequences output by the terminal's function keys. The word on the right side of the = is tested against both the full name of the terminal and the portion of the terminal name before the first -. This allows sun to match both sun and sun-cmd, for instance. version The version test may be used to perform comparisons against specific readline versions. The version expands to the current readline version. The set of comparison operators includes =, (and ==), !=, <=, >=, <, and >. The version number supplied on the right side of the operator consists of a major version number, an optional decimal point, and an optional minor version (e.g., 7.1). If the minor version is omitted, it is assumed to be 0. The operator may be separated from the string version and from the version number argument by whitespace. application The application construct is used to include application-specific settings. Each program using the readline library sets the application name, and an initialization file can test for a particular value. This could be used to bind key sequences to functions useful for a specific program. For instance, the following command adds a key sequence that quotes the current or previous word in bash: $if Bash # Quote the current or previous word "\C-xq": "\eb\"\ef\"" $endif variable The variable construct provides simple equality tests for readline variables and values. The permitted comparison operators are =, ==, and !=. The variable name must be separated from the comparison operator by whitespace; the operator may be separated from the value on the right hand side by whitespace. Both string and boolean variables may be tested. Boolean variables must be tested against the values on and off. $endif This command, as seen in the previous example, terminates an $if command. $else Commands in this branch of the $if directive are executed if the test fails. $include This directive takes a single filename as an argument and reads commands and bindings from that file. For example, the following directive would read /etc/inputrc: $include /etc/inputrc Searching Readline provides commands for searching through the command history (see HISTORY below) for lines containing a specified string. There are two search modes: incremental and non- incremental. Incremental searches begin before the user has finished typing the search string. As each character of the search string is typed, readline displays the next entry from the history matching the string typed so far. An incremental search requires only as many characters as needed to find the desired history entry. The characters present in the value of the isearch-terminators variable are used to terminate an incremental search. If that variable has not been assigned a value the Escape and Control-J characters will terminate an incremental search. Control-G will abort an incremental search and restore the original line. When the search is terminated, the history entry containing the search string becomes the current line. To find other matching entries in the history list, type Control- S or Control-R as appropriate. This will search backward or forward in the history for the next entry matching the search string typed so far. Any other key sequence bound to a readline command will terminate the search and execute that command. For instance, a newline will terminate the search and accept the line, thereby executing the command from the history list. Readline remembers the last incremental search string. If two Control-Rs are typed without any intervening characters defining a new search string, any remembered search string is used. Non-incremental searches read the entire search string before starting to search for matching history lines. The search string may be typed by the user or be part of the contents of the current line. Readline Command Names The following is a list of the names of the commands and the default key sequences to which they are bound. Command names without an accompanying key sequence are unbound by default. In the following descriptions, point refers to the current cursor position, and mark refers to a cursor position saved by the set-mark command. The text between the point and mark is referred to as the region. Commands for Moving beginning-of-line (C-a) Move to the start of the current line. end-of-line (C-e) Move to the end of the line. forward-char (C-f) Move forward a character. backward-char (C-b) Move back a character. forward-word (M-f) Move forward to the end of the next word. Words are composed of alphanumeric characters (letters and digits). backward-word (M-b) Move back to the start of the current or previous word. Words are composed of alphanumeric characters (letters and digits). shell-forward-word Move forward to the end of the next word. Words are delimited by non-quoted shell metacharacters. shell-backward-word Move back to the start of the current or previous word. Words are delimited by non-quoted shell metacharacters. previous-screen-line Attempt to move point to the same physical screen column on the previous physical screen line. This will not have the desired effect if the current readline line does not take up more than one physical line or if point is not greater than the length of the prompt plus the screen width. next-screen-line Attempt to move point to the same physical screen column on the next physical screen line. This will not have the desired effect if the current readline line does not take up more than one physical line or if the length of the current readline line is not greater than the length of the prompt plus the screen width. clear-display (M-C-l) Clear the screen and, if possible, the terminal's scrollback buffer, then redraw the current line, leaving the current line at the top of the screen. clear-screen (C-l) Clear the screen, then redraw the current line, leaving the current line at the top of the screen. With an argument, refresh the current line without clearing the screen. redraw-current-line Refresh the current line. Commands for Manipulating the History accept-line (Newline, Return) Accept the line regardless of where the cursor is. If this line is non-empty, add it to the history list according to the state of the HISTCONTROL variable. If the line is a modified history line, then restore the history line to its original state. previous-history (C-p) Fetch the previous command from the history list, moving back in the list. next-history (C-n) Fetch the next command from the history list, moving forward in the list. beginning-of-history (M-<) Move to the first line in the history. end-of-history (M->) Move to the end of the input history, i.e., the line currently being entered. operate-and-get-next (C-o) Accept the current line for execution and fetch the next line relative to the current line from the history for editing. A numeric argument, if supplied, specifies the history entry to use instead of the current line. fetch-history With a numeric argument, fetch that entry from the history list and make it the current line. Without an argument, move back to the first entry in the history list. reverse-search-history (C-r) Search backward starting at the current line and moving `up' through the history as necessary. This is an incremental search. forward-search-history (C-s) Search forward starting at the current line and moving `down' through the history as necessary. This is an incremental search. non-incremental-reverse-search-history (M-p) Search backward through the history starting at the current line using a non-incremental search for a string supplied by the user. non-incremental-forward-search-history (M-n) Search forward through the history using a non-incremental search for a string supplied by the user. history-search-forward Search forward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. history-search-backward Search backward through the history for the string of characters between the start of the current line and the point. This is a non-incremental search. history-substring-search-backward Search backward through the history for the string of characters between the start of the current line and the current cursor position (the point). The search string may match anywhere in a history line. This is a non- incremental search. history-substring-search-forward Search forward through the history for the string of characters between the start of the current line and the point. The search string may match anywhere in a history line. This is a non-incremental search. yank-nth-arg (M-C-y) Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the nth word from the end of the previous command. Once the argument n is computed, the argument is extracted as if the "!n" history expansion had been specified. yank-last-arg (M-., M-_) Insert the last argument to the previous command (the last word of the previous history entry). With a numeric argument, behave exactly like yank-nth-arg. Successive calls to yank-last-arg move back through the history list, inserting the last word (or the word specified by the argument to the first call) of each line in turn. Any numeric argument supplied to these successive calls determines the direction to move through the history. A negative argument switches the direction through the history (back or forward). The history expansion facilities are used to extract the last word, as if the "!$" history expansion had been specified. shell-expand-line (M-C-e) Expand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions. See HISTORY EXPANSION below for a description of history expansion. history-expand-line (M-^) Perform history expansion on the current line. See HISTORY EXPANSION below for a description of history expansion. magic-space Perform history expansion on the current line and insert a space. See HISTORY EXPANSION below for a description of history expansion. alias-expand-line Perform alias expansion on the current line. See ALIASES above for a description of alias expansion. history-and-alias-expand-line Perform history and alias expansion on the current line. insert-last-argument (M-., M-_) A synonym for yank-last-arg. edit-and-execute-command (C-x C-e) Invoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke $VISUAL, $EDITOR, and emacs as the editor, in that order. Commands for Changing Text end-of-file (usually C-d) The character indicating end-of-file as set, for example, by ``stty''. If this character is read when there are no characters on the line, and point is at the beginning of the line, readline interprets it as the end of input and returns EOF. delete-char (C-d) Delete the character at point. If this function is bound to the same character as the tty EOF character, as C-d commonly is, see above for the effects. backward-delete-char (Rubout) Delete the character behind the cursor. When given a numeric argument, save the deleted text on the kill ring. forward-backward-delete-char Delete the character under the cursor, unless the cursor is at the end of the line, in which case the character behind the cursor is deleted. quoted-insert (C-q, C-v) Add the next character typed to the line verbatim. This is how to insert characters like C-q, for example. tab-insert (C-v TAB) Insert a tab character. self-insert (a, b, A, 1, !, ...) Insert the character typed. transpose-chars (C-t) Drag the character before point forward over the character at point, moving point forward as well. If point is at the end of the line, then this transposes the two characters before point. Negative arguments have no effect. transpose-words (M-t) Drag the word before point past the word after point, moving point over that word as well. If point is at the end of the line, this transposes the last two words on the line. upcase-word (M-u) Uppercase the current (or following) word. With a negative argument, uppercase the previous word, but do not move point. downcase-word (M-l) Lowercase the current (or following) word. With a negative argument, lowercase the previous word, but do not move point. capitalize-word (M-c) Capitalize the current (or following) word. With a negative argument, capitalize the previous word, but do not move point. overwrite-mode Toggle overwrite mode. With an explicit positive numeric argument, switches to overwrite mode. With an explicit non-positive numeric argument, switches to insert mode. This command affects only emacs mode; vi mode does overwrite differently. Each call to readline() starts in insert mode. In overwrite mode, characters bound to self-insert replace the text at point rather than pushing the text to the right. Characters bound to backward-delete-char replace the character before point with a space. By default, this command is unbound. Killing and Yanking kill-line (C-k) Kill the text from point to the end of the line. backward-kill-line (C-x Rubout) Kill backward to the beginning of the line. unix-line-discard (C-u) Kill backward from point to the beginning of the line. The killed text is saved on the kill-ring. kill-whole-line Kill all characters on the current line, no matter where point is. kill-word (M-d) Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as those used by forward-word. backward-kill-word (M-Rubout) Kill the word behind point. Word boundaries are the same as those used by backward-word. shell-kill-word Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as those used by shell-forward-word. shell-backward-kill-word Kill the word behind point. Word boundaries are the same as those used by shell-backward-word. unix-word-rubout (C-w) Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring. unix-filename-rubout Kill the word behind point, using white space and the slash character as the word boundaries. The killed text is saved on the kill-ring. delete-horizontal-space (M-\) Delete all spaces and tabs around point. kill-region Kill the text in the current region. copy-region-as-kill Copy the text in the region to the kill buffer. copy-backward-word Copy the word before point to the kill buffer. The word boundaries are the same as backward-word. copy-forward-word Copy the word following point to the kill buffer. The word boundaries are the same as forward-word. yank (C-y) Yank the top of the kill ring into the buffer at point. yank-pop (M-y) Rotate the kill ring, and yank the new top. Only works following yank or yank-pop. Numeric Arguments digit-argument (M-0, M-1, ..., M--) Add this digit to the argument already accumulating, or start a new argument. M-- starts a negative argument. universal-argument This is another way to specify an argument. If this command is followed by one or more digits, optionally with a leading minus sign, those digits define the argument. If the command is followed by digits, executing universal-argument again ends the numeric argument, but is otherwise ignored. As a special case, if this command is immediately followed by a character that is neither a digit nor minus sign, the argument count for the next command is multiplied by four. The argument count is initially one, so executing this function the first time makes the argument count four, a second time makes the argument count sixteen, and so on. Completing complete (TAB) Attempt to perform completion on the text before point. Bash attempts completion treating the text as a variable (if the text begins with $), username (if the text begins with ~), hostname (if the text begins with @), or command (including aliases and functions) in turn. If none of these produces a match, filename completion is attempted. possible-completions (M-?) List the possible completions of the text before point. insert-completions (M-*) Insert all completions of the text before point that would have been generated by possible-completions. menu-complete Similar to complete, but replaces the word to be completed with a single match from the list of possible completions. Repeated execution of menu-complete steps through the list of possible completions, inserting each match in turn. At the end of the list of completions, the bell is rung (subject to the setting of bell-style) and the original text is restored. An argument of n moves n positions forward in the list of matches; a negative argument may be used to move backward through the list. This command is intended to be bound to TAB, but is unbound by default. menu-complete-backward Identical to menu-complete, but moves backward through the list of possible completions, as if menu-complete had been given a negative argument. This command is unbound by default. delete-char-or-list Deletes the character under the cursor if not at the beginning or end of the line (like delete-char). If at the end of the line, behaves identically to possible-completions. This command is unbound by default. complete-filename (M-/) Attempt filename completion on the text before point. possible-filename-completions (C-x /) List the possible completions of the text before point, treating it as a filename. complete-username (M-~) Attempt completion on the text before point, treating it as a username. possible-username-completions (C-x ~) List the possible completions of the text before point, treating it as a username. complete-variable (M-$) Attempt completion on the text before point, treating it as a shell variable. possible-variable-completions (C-x $) List the possible completions of the text before point, treating it as a shell variable. complete-hostname (M-@) Attempt completion on the text before point, treating it as a hostname. possible-hostname-completions (C-x @) List the possible completions of the text before point, treating it as a hostname. complete-command (M-!) Attempt completion on the text before point, treating it as a command name. Command completion attempts to match the text against aliases, reserved words, shell functions, shell builtins, and finally executable filenames, in that order. possible-command-completions (C-x !) List the possible completions of the text before point, treating it as a command name. dynamic-complete-history (M-TAB) Attempt completion on the text before point, comparing the text against lines from the history list for possible completion matches. dabbrev-expand Attempt menu completion on the text before point, comparing the text against lines from the history list for possible completion matches. complete-into-braces (M-{) Perform filename completion and insert the list of possible completions enclosed within braces so the list is available to the shell (see Brace Expansion above). Keyboard Macros start-kbd-macro (C-x () Begin saving the characters typed into the current keyboard macro. end-kbd-macro (C-x )) Stop saving the characters typed into the current keyboard macro and store the definition. call-last-kbd-macro (C-x e) Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard. print-last-kbd-macro () Print the last keyboard macro defined in a format suitable for the inputrc file. Miscellaneous re-read-init-file (C-x C-r) Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there. abort (C-g) Abort the current editing command and ring the terminal's bell (subject to the setting of bell-style). do-lowercase-version (M-A, M-B, M-x, ...) If the metafied character x is uppercase, run the command that is bound to the corresponding metafied lowercase character. The behavior is undefined if x is already lowercase. prefix-meta (ESC) Metafy the next character typed. ESC f is equivalent to Meta-f. undo (C-_, C-x C-u) Incremental undo, separately remembered for each line. revert-line (M-r) Undo all changes made to this line. This is like executing the undo command enough times to return the line to its initial state. tilde-expand (M-&) Perform tilde expansion on the current word. set-mark (C-@, M-<space>) Set the mark to the point. If a numeric argument is supplied, the mark is set to that position. exchange-point-and-mark (C-x C-x) Swap the point with the mark. The current cursor position is set to the saved position, and the old cursor position is saved as the mark. character-search (C-]) A character is read and point is moved to the next occurrence of that character. A negative argument searches for previous occurrences. character-search-backward (M-C-]) A character is read and point is moved to the previous occurrence of that character. A negative argument searches for subsequent occurrences. skip-csi-sequence Read enough characters to consume a multi-key sequence such as those defined for keys like Home and End. Such sequences begin with a Control Sequence Indicator (CSI), usually ESC-[. If this sequence is bound to "\[", keys producing such sequences will have no effect unless explicitly bound to a readline command, instead of inserting stray characters into the editing buffer. This is unbound by default, but usually bound to ESC-[. insert-comment (M-#) Without a numeric argument, the value of the readline comment-begin variable is inserted at the beginning of the current line. If a numeric argument is supplied, this command acts as a toggle: if the characters at the beginning of the line do not match the value of comment-begin, the value is inserted, otherwise the characters in comment-begin are deleted from the beginning of the line. In either case, the line is accepted as if a newline had been typed. The default value of comment-begin causes this command to make the current line a shell comment. If a numeric argument causes the comment character to be removed, the line will be executed by the shell. spell-correct-word (C-x s) Perform spelling correction on the current word, treating it as a directory or filename, in the same way as the cdspell shell option. Word boundaries are the same as those used by shell-forward-word. glob-complete-word (M-g) The word before point is treated as a pattern for pathname expansion, with an asterisk implicitly appended. This pattern is used to generate a list of matching filenames for possible completions. glob-expand-word (C-x *) The word before point is treated as a pattern for pathname expansion, and the list of matching filenames is inserted, replacing the word. If a numeric argument is supplied, an asterisk is appended before pathname expansion. glob-list-expansions (C-x g) The list of expansions that would have been generated by glob-expand-word is displayed, and the line is redrawn. If a numeric argument is supplied, an asterisk is appended before pathname expansion. dump-functions Print all of the functions and their key bindings to the readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. dump-variables Print all of the settable readline variables and their values to the readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. dump-macros Print all of the readline key sequences bound to macros and the strings they output. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. display-shell-version (C-x C-v) Display version information about the current instance of bash. Programmable Completion When word completion is attempted for an argument to a command for which a completion specification (a compspec) has been defined using the complete builtin (see SHELL BUILTIN COMMANDS below), the programmable completion facilities are invoked. First, the command name is identified. If the command word is the empty string (completion attempted at the beginning of an empty line), any compspec defined with the -E option to complete is used. If a compspec has been defined for that command, the compspec is used to generate the list of possible completions for the word. If the command word is a full pathname, a compspec for the full pathname is searched for first. If no compspec is found for the full pathname, an attempt is made to find a compspec for the portion following the final slash. If those searches do not result in a compspec, any compspec defined with the -D option to complete is used as the default. If there is no default compspec, bash attempts alias expansion on the command word as a final resort, and attempts to find a compspec for the command word from any successful expansion. Once a compspec has been found, it is used to generate the list of matching words. If a compspec is not found, the default bash completion as described above under Completing is performed. First, the actions specified by the compspec are used. Only matches which are prefixed by the word being completed are returned. When the -f or -d option is used for filename or directory name completion, the shell variable FIGNORE is used to filter the matches. Any completions specified by a pathname expansion pattern to the -G option are generated next. The words generated by the pattern need not match the word being completed. The GLOBIGNORE shell variable is not used to filter the matches, but the FIGNORE variable is used. Next, the string specified as the argument to the -W option is considered. The string is first split using the characters in the IFS special variable as delimiters. Shell quoting is honored. Each word is then expanded using brace expansion, tilde expansion, parameter and variable expansion, command substitution, and arithmetic expansion, as described above under EXPANSION. The results are split using the rules described above under Word Splitting. The results of the expansion are prefix- matched against the word being completed, and the matching words become the possible completions. After these matches have been generated, any shell function or command specified with the -F and -C options is invoked. When the command or function is invoked, the COMP_LINE, COMP_POINT, COMP_KEY, and COMP_TYPE variables are assigned values as described above under Shell Variables. If a shell function is being invoked, the COMP_WORDS and COMP_CWORD variables are also set. When the function or command is invoked, the first argument ($1) is the name of the command whose arguments are being completed, the second argument ($2) is the word being completed, and the third argument ($3) is the word preceding the word being completed on the current command line. No filtering of the generated completions against the word being completed is performed; the function or command has complete freedom in generating the matches. Any function specified with -F is invoked first. The function may use any of the shell facilities, including the compgen builtin described below, to generate the matches. It must put the possible completions in the COMPREPLY array variable, one per array element. Next, any command specified with the -C option is invoked in an environment equivalent to command substitution. It should print a list of completions, one per line, to the standard output. Backslash may be used to escape a newline, if necessary. After all of the possible completions are generated, any filter specified with the -X option is applied to the list. The filter is a pattern as used for pathname expansion; a & in the pattern is replaced with the text of the word being completed. A literal & may be escaped with a backslash; the backslash is removed before attempting a match. Any completion that matches the pattern will be removed from the list. A leading ! negates the pattern; in this case any completion not matching the pattern will be removed. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. Finally, any prefix and suffix specified with the -P and -S options are added to each member of the completion list, and the result is returned to the readline completion code as the list of possible completions. If the previously-applied actions do not generate any matches, and the -o dirnames option was supplied to complete when the compspec was defined, directory name completion is attempted. If the -o plusdirs option was supplied to complete when the compspec was defined, directory name completion is attempted and any matches are added to the results of the other actions. By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of possible completions. The default bash completions are not attempted, and the readline default of filename completion is disabled. If the -o bashdefault option was supplied to complete when the compspec was defined, the bash default completions are attempted if the compspec generates no matches. If the -o default option was supplied to complete when the compspec was defined, readline's default completion will be performed if the compspec (and, if attempted, the default bash completions) generate no matches. When a compspec indicates that directory name completion is desired, the programmable completion functions force readline to append a slash to completed names which are symbolic links to directories, subject to the value of the mark-directories readline variable, regardless of the setting of the mark- symlinked-directories readline variable. There is some support for dynamically modifying completions. This is most useful when used in combination with a default completion specified with complete -D. It's possible for shell functions executed as completion handlers to indicate that completion should be retried by returning an exit status of 124. If a shell function returns 124, and changes the compspec associated with the command on which completion is being attempted (supplied as the first argument when the function is executed), programmable completion restarts from the beginning, with an attempt to find a new compspec for that command. This allows a set of completions to be built dynamically as completion is attempted, rather than being loaded all at once. For instance, assuming that there is a library of compspecs, each kept in a file corresponding to the name of the command, the following default completion function would load completions dynamically: _completion_loader() { . "/etc/bash_completion.d/$1.sh" >/dev/null 2>&1 && return 124 } complete -D -F _completion_loader -o bashdefault -o default HISTORY top When the -o history option to the set builtin is enabled, the shell provides access to the command history, the list of commands previously typed. The value of the HISTSIZE variable is used as the number of commands to save in a history list. The text of the last HISTSIZE commands (default 500) is saved. The shell stores each command in the history list prior to parameter and variable expansion (see EXPANSION above) but after history expansion is performed, subject to the values of the shell variables HISTIGNORE and HISTCONTROL. On startup, the history is initialized from the file named by the variable HISTFILE (default ~/.bash_history). The file named by the value of HISTFILE is truncated, if necessary, to contain no more than the number of lines specified by the value of HISTFILESIZE. If HISTFILESIZE is unset, or set to null, a non- numeric value, or a numeric value less than zero, the history file is not truncated. When the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted as timestamps for the following history line. These timestamps are optionally displayed depending on the value of the HISTTIMEFORMAT variable. When a shell with history enabled exits, the last $HISTSIZE lines are copied from the history list to $HISTFILE. If the histappend shell option is enabled (see the description of shopt under SHELL BUILTIN COMMANDS below), the lines are appended to the history file, otherwise the history file is overwritten. If HISTFILE is unset, or if the history file is unwritable, the history is not saved. If the HISTTIMEFORMAT variable is set, time stamps are written to the history file, marked with the history comment character, so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines. After saving the history, the history file is truncated to contain no more than HISTFILESIZE lines. If HISTFILESIZE is unset, or set to null, a non-numeric value, or a numeric value less than zero, the history file is not truncated. The builtin command fc (see SHELL BUILTIN COMMANDS below) may be used to list or edit and re-execute a portion of the history list. The history builtin may be used to display or modify the history list and manipulate the history file. When using command-line editing, search commands are available in each editing mode that provide access to the history list. The shell allows control over which commands are saved on the history list. The HISTCONTROL and HISTIGNORE variables may be set to cause the shell to save only a subset of the commands entered. The cmdhist shell option, if enabled, causes the shell to attempt to save each line of a multi-line command in the same history entry, adding semicolons where necessary to preserve syntactic correctness. The lithist shell option causes the shell to save the command with embedded newlines instead of semicolons. See the description of the shopt builtin below under SHELL BUILTIN COMMANDS for information on setting and unsetting shell options. HISTORY EXPANSION top The shell supports a history expansion feature that is similar to the history expansion in csh. This section describes what syntax features are available. This feature is enabled by default for interactive shells, and can be disabled using the +H option to the set builtin command (see SHELL BUILTIN COMMANDS below). Non- interactive shells do not perform history expansion by default. History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the current input line, or fix errors in previous commands quickly. History expansion is performed immediately after a complete line is read, before the shell breaks it into words, and is performed on each line individually without taking quoting on previous lines into account. It takes place in two parts. The first is to determine which line from the history list to use during substitution. The second is to select portions of that line for inclusion into the current one. The line selected from the history is the event, and the portions of that line that are acted upon are words. Various modifiers are available to manipulate the selected words. The line is broken into words in the same fashion as when reading input, so that several metacharacter-separated words surrounded by quotes are considered one word. History expansions are introduced by the appearance of the history expansion character, which is ! by default. Only backslash (\) and single quotes can quote the history expansion character, but the history expansion character is also treated as quoted if it immediately precedes the closing double quote in a double-quoted string. Several characters inhibit history expansion if found immediately following the history expansion character, even if it is unquoted: space, tab, newline, carriage return, and =. If the extglob shell option is enabled, ( will also inhibit expansion. Several shell options settable with the shopt builtin may be used to tailor the behavior of history expansion. If the histverify shell option is enabled (see the description of the shopt builtin below), and readline is being used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the readline editing buffer for further modification. If readline is being used, and the histreedit shell option is enabled, a failed history substitution will be reloaded into the readline editing buffer for correction. The -p option to the history builtin command may be used to see what a history expansion will do before using it. The -s option to the history builtin may be used to add commands to the end of the history list without actually executing them, so that they are available for subsequent recall. The shell allows control of the various characters used by the history expansion mechanism (see the description of histchars above under Shell Variables). The shell uses the history comment character to mark history timestamps when writing the history file. Event Designators An event designator is a reference to a command line entry in the history list. Unless the reference is absolute, events are relative to the current position in the history list. ! Start a history substitution, except when followed by a blank, newline, carriage return, = or ( (when the extglob shell option is enabled using the shopt builtin). !n Refer to command line n. !-n Refer to the current command minus n. !! Refer to the previous command. This is a synonym for `!-1'. !string Refer to the most recent command preceding the current position in the history list starting with string. !?string[?] Refer to the most recent command preceding the current position in the history list containing string. The trailing ? may be omitted if string is followed immediately by a newline. If string is missing, the string from the most recent search is used; it is an error if there is no previous search string. ^string1^string2^ Quick substitution. Repeat the previous command, replacing string1 with string2. Equivalent to ``!!:s^string1^string2^'' (see Modifiers below). !# The entire command line typed so far. Word Designators Word designators are used to select desired words from the event. A : separates the event specification from the word designator. It may be omitted if the word designator begins with a ^, $, *, -, or %. Words are numbered from the beginning of the line, with the first word being denoted by 0 (zero). Words are inserted into the current line separated by single spaces. 0 (zero) The zeroth word. For the shell, this is the command word. n The nth word. ^ The first argument. That is, word 1. $ The last word. This is usually the last argument, but will expand to the zeroth word if there is only one word in the line. % The first word matched by the most recent `?string?' search, if the search string begins with a character that is part of a word. x-y A range of words; `-y' abbreviates `0-y'. * All of the words but the zeroth. This is a synonym for `1-$'. It is not an error to use * if there is just one word in the event; the empty string is returned in that case. x* Abbreviates x-$. x- Abbreviates x-$ like x*, but omits the last word. If x is missing, it defaults to 0. If a word designator is supplied without an event specification, the previous command is used as the event. Modifiers After the optional word designator, there may appear a sequence of one or more of the following modifiers, each preceded by a `:'. These modify, or edit, the word or words selected from the history event. h Remove a trailing filename component, leaving only the head. t Remove all leading filename components, leaving the tail. r Remove a trailing suffix of the form .xxx, leaving the basename. e Remove all but the trailing suffix. p Print the new command but do not execute it. q Quote the substituted words, escaping further substitutions. x Quote the substituted words as with q, but break into words at blanks and newlines. The q and x modifiers are mutually exclusive; the last one supplied is used. s/old/new/ Substitute new for the first occurrence of old in the event line. Any character may be used as the delimiter in place of /. The final delimiter is optional if it is the last character of the event line. The delimiter may be quoted in old and new with a single backslash. If & appears in new, it is replaced by old. A single backslash will quote the &. If old is null, it is set to the last old substituted, or, if no previous history substitutions took place, the last string in a !?string[?] search. If new is null, each matching old is deleted. & Repeat the previous substitution. g Cause changes to be applied over the entire event line. This is used in conjunction with `:s' (e.g., `:gs/old/new/') or `:&'. If used with `:s', any delimiter can be used in place of /, and the final delimiter is optional if it is the last character of the event line. An a may be used as a synonym for g. G Apply the following `s' or `&' modifier once to each word in the event line. SHELL BUILTIN COMMANDS top Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options. The :, true, false, and test/[ builtins do not accept options and do not treat -- specially. The exit, logout, return, break, continue, let, and shift builtins accept and process arguments beginning with - without requiring --. Other builtins that accept arguments but are not specified as accepting options interpret arguments beginning with - as invalid options and require -- to prevent this interpretation. : [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. The return status is zero. . filename [arguments] source filename [arguments] Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, filenames in PATH are used to find the directory containing filename, but filename does not need to be executable. The file searched for in PATH need not be executable. When bash is not in posix mode, it searches the current directory if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. If the -T option is enabled, . inherits any trap on DEBUG; if it is not, any DEBUG trap string is saved and restored around the call to ., and . unsets the DEBUG trap while it executes. If -T is not set, and the sourced file changes the DEBUG trap, the new value is retained when . completes. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. alias [-p] [name[=value] ...] Alias with no arguments or with the -p option prints the list of aliases in the form alias name=value on standard output. When arguments are supplied, an alias is defined for each name whose value is given. A trailing space in value causes the next word to be checked for alias substitution when the alias is expanded. For each name in the argument list for which no value is supplied, the name and value of the alias is printed. Alias returns true unless a name is given for which no alias has been defined. bg [jobspec ...] Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used. bg jobspec returns 0 unless run when job control is disabled or, when run with job control enabled, any specified jobspec was not found or was started without job control. bind [-m keymap] [-lpsvPSVX] bind [-m keymap] [-q function] [-u function] [-r keyseq] bind [-m keymap] -f filename bind [-m keymap] -x keyseq:shell-command bind [-m keymap] keyseq:function-name bind [-m keymap] keyseq:readline-command bind readline-command-line Display current readline key and function bindings, bind a key sequence to a readline function or macro, or set a readline variable. Each non-option argument is a command as it would appear in a readline initialization file such as .inputrc, but each binding or command must be passed as a separate argument; e.g., '"\C-x\C-r": re-read-init-file'. Options, if supplied, have the following meanings: -m keymap Use keymap as the keymap to be affected by the subsequent bindings. Acceptable keymap names are emacs, emacs-standard, emacs-meta, emacs-ctlx, vi, vi-move, vi-command, and vi-insert. vi is equivalent to vi-command (vi-move is also a synonym); emacs is equivalent to emacs-standard. -l List the names of all readline functions. -p Display readline function names and bindings in such a way that they can be re-read. -P List current readline function names and bindings. -s Display readline key sequences bound to macros and the strings they output in such a way that they can be re-read. -S Display readline key sequences bound to macros and the strings they output. -v Display readline variable names and values in such a way that they can be re-read. -V List current readline variable names and values. -f filename Read key bindings from filename. -q function Query about which keys invoke the named function. -u function Unbind all keys bound to the named function. -r keyseq Remove any current binding for keyseq. -x keyseq:shell-command Cause shell-command to be executed whenever keyseq is entered. When shell-command is executed, the shell sets the READLINE_LINE variable to the contents of the readline line buffer and the READLINE_POINT and READLINE_MARK variables to the current location of the insertion point and the saved insertion point (the mark), respectively. The shell assigns any numeric argument the user supplied to the READLINE_ARGUMENT variable. If there was no argument, that variable is not set. If the executed command changes the value of any of READLINE_LINE, READLINE_POINT, or READLINE_MARK, those new values will be reflected in the editing state. -X List all key sequences bound to shell commands and the associated commands in a format that can be reused as input. The return value is 0 unless an unrecognized option is given or an error occurred. break [n] Exit from within a for, while, until, or select loop. If n is specified, break n levels. n must be 1. If n is greater than the number of enclosing loops, all enclosing loops are exited. The return value is 0 unless n is not greater than or equal to 1. builtin shell-builtin [arguments] Execute the specified shell builtin, passing it arguments, and return its exit status. This is useful when defining a function whose name is the same as a shell builtin, retaining the functionality of the builtin within the function. The cd builtin is commonly redefined this way. The return status is false if shell-builtin is not a shell builtin command. caller [expr] Returns the context of any active subroutine call (a shell function or a script executed with the . or source builtins). Without expr, caller displays the line number and source filename of the current subroutine call. If a non-negative integer is supplied as expr, caller displays the line number, subroutine name, and source file corresponding to that position in the current execution call stack. This extra information may be used, for example, to print a stack trace. The current frame is frame 0. The return value is 0 unless the shell is not executing a subroutine call or expr does not correspond to a valid position in the call stack. cd [-L|[-P [-e]] [-@]] [dir] Change the current directory to dir. if dir is not supplied, the value of the HOME shell variable is the default. The variable CDPATH defines the search path for the directory containing dir: each directory name in CDPATH is searched for dir. Alternative directory names in CDPATH are separated by a colon (:). A null directory name in CDPATH is the same as the current directory, i.e., ``.''. If dir begins with a slash (/), then CDPATH is not used. The -P option causes cd to use the physical directory structure by resolving symbolic links while traversing dir and before processing instances of .. in dir (see also the -P option to the set builtin command); the -L option forces symbolic links to be followed by resolving the link after processing instances of .. in dir. If .. appears in dir, it is processed by removing the immediately previous pathname component from dir, back to a slash or the beginning of dir. If the -e option is supplied with -P, and the current working directory cannot be successfully determined after a successful directory change, cd will return an unsuccessful status. On systems that support it, the -@ option presents the extended attributes associated with a file as a directory. An argument of - is converted to $OLDPWD before the directory change is attempted. If a non-empty directory name from CDPATH is used, or if - is the first argument, and the directory change is successful, the absolute pathname of the new working directory is written to the standard output. If the directory change is successful, cd sets the value of the PWD environment variable to the new directory name, and sets the OLDPWD environment variable to the value of the current working directory before the change. The return value is true if the directory was successfully changed; false otherwise. command [-pVv] command [arg ...] Run command with args suppressing the normal shell function lookup. Only builtin commands or commands found in the PATH are executed. If the -p option is given, the search for command is performed using a default value for PATH that is guaranteed to find all of the standard utilities. If either the -V or -v option is supplied, a description of command is printed. The -v option causes a single word indicating the command or filename used to invoke command to be displayed; the -V option produces a more verbose description. If the -V or -v option is supplied, the exit status is 0 if command was found, and 1 if not. If neither option is supplied and an error occurred or command cannot be found, the exit status is 127. Otherwise, the exit status of the command builtin is the exit status of command. compgen [option] [word] Generate possible completion matches for word according to the options, which may be any option accepted by the complete builtin with the exception of -p and -r, and write the matches to the standard output. When using the -F or -C options, the various shell variables set by the programmable completion facilities, while available, will not have useful values. The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags. If word is specified, only those completions matching word will be displayed. The return value is true unless an invalid option is supplied, or no matches were generated. complete [-abcdefgjksuv] [-o comp-option] [-DEI] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] name [name ...] complete -pr [-DEI] [name ...] Specify how arguments to each name should be completed. If the -p option is supplied, or if no options are supplied, existing completion specifications are printed in a way that allows them to be reused as input. The -r option removes a completion specification for each name, or, if no names are supplied, all completion specifications. The -D option indicates that other supplied options and actions should apply to the ``default'' command completion; that is, completion attempted on a command for which no completion has previously been defined. The -E option indicates that other supplied options and actions should apply to ``empty'' command completion; that is, completion attempted on a blank line. The -I option indicates that other supplied options and actions should apply to completion on the initial non-assignment word on the line, or after a command delimiter such as ; or |, which is usually command name completion. If multiple options are supplied, the -D option takes precedence over -E, and both take precedence over -I. If any of -D, -E, or -I are supplied, any other name arguments are ignored; these completions only apply to the case specified by the option. The process of applying these completion specifications when word completion is attempted is described above under Programmable Completion. Other options, if specified, have the following meanings. The arguments to the -G, -W, and -X options (and, if necessary, the -P and -S options) should be quoted to protect them from expansion before the complete builtin is invoked. -o comp-option The comp-option controls several aspects of the compspec's behavior beyond the simple generation of completions. comp-option may be one of: bashdefault Perform the rest of the default bash completions if the compspec generates no matches. default Use readline's default filename completion if the compspec generates no matches. dirnames Perform directory name completion if the compspec generates no matches. filenames Tell readline that the compspec generates filenames, so it can perform any filename-specific processing (like adding a slash to directory names, quoting special characters, or suppressing trailing spaces). Intended to be used with shell functions. noquote Tell readline not to quote the completed words if they are filenames (quoting filenames is the default). nosort Tell readline not to sort the list of possible completions alphabetically. nospace Tell readline not to append a space (the default) to words completed at the end of the line. plusdirs After any matches defined by the compspec are generated, directory name completion is attempted and any matches are added to the results of the other actions. -A action The action may be one of the following to generate a list of possible completions: alias Alias names. May also be specified as -a. arrayvar Array variable names. binding Readline key binding names. builtin Names of shell builtin commands. May also be specified as -b. command Command names. May also be specified as -c. directory Directory names. May also be specified as -d. disabled Names of disabled shell builtins. enabled Names of enabled shell builtins. export Names of exported shell variables. May also be specified as -e. file File names. May also be specified as -f. function Names of shell functions. group Group names. May also be specified as -g. helptopic Help topics as accepted by the help builtin. hostname Hostnames, as taken from the file specified by the HOSTFILE shell variable. job Job names, if job control is active. May also be specified as -j. keyword Shell reserved words. May also be specified as -k. running Names of running jobs, if job control is active. service Service names. May also be specified as -s. setopt Valid arguments for the -o option to the set builtin. shopt Shell option names as accepted by the shopt builtin. signal Signal names. stopped Names of stopped jobs, if job control is active. user User names. May also be specified as -u. variable Names of all shell variables. May also be specified as -v. -C command command is executed in a subshell environment, and its output is used as the possible completions. Arguments are passed as with the -F option. -F function The shell function function is executed in the current shell environment. When the function is executed, the first argument ($1) is the name of the command whose arguments are being completed, the second argument ($2) is the word being completed, and the third argument ($3) is the word preceding the word being completed on the current command line. When it finishes, the possible completions are retrieved from the value of the COMPREPLY array variable. -G globpat The pathname expansion pattern globpat is expanded to generate the possible completions. -P prefix prefix is added at the beginning of each possible completion after all other options have been applied. -S suffix suffix is appended to each possible completion after all other options have been applied. -W wordlist The wordlist is split using the characters in the IFS special variable as delimiters, and each resultant word is expanded. Shell quoting is honored within wordlist, in order to provide a mechanism for the words to contain shell metacharacters or characters in the value of IFS. The possible completions are the members of the resultant list which match the word being completed. -X filterpat filterpat is a pattern as used for pathname expansion. It is applied to the list of possible completions generated by the preceding options and arguments, and each completion matching filterpat is removed from the list. A leading ! in filterpat negates the pattern; in this case, any completion not matching filterpat is removed. The return value is true unless an invalid option is supplied, an option other than -p or -r is supplied without a name argument, an attempt is made to remove a completion specification for a name for which no specification exists, or an error occurs adding a completion specification. compopt [-o option] [-DEI] [+o option] [name] Modify completion options for each name according to the options, or for the currently-executing completion if no names are supplied. If no options are given, display the completion options for each name or the current completion. The possible values of option are those valid for the complete builtin described above. The -D option indicates that other supplied options should apply to the ``default'' command completion; that is, completion attempted on a command for which no completion has previously been defined. The -E option indicates that other supplied options should apply to ``empty'' command completion; that is, completion attempted on a blank line. The -I option indicates that other supplied options should apply to completion on the initial non-assignment word on the line, or after a command delimiter such as ; or |, which is usually command name completion. The return value is true unless an invalid option is supplied, an attempt is made to modify the options for a name for which no completion specification exists, or an output error occurs. continue [n] Resume the next iteration of the enclosing for, while, until, or select loop. If n is specified, resume at the nth enclosing loop. n must be 1. If n is greater than the number of enclosing loops, the last enclosing loop (the ``top-level'' loop) is resumed. The return value is 0 unless n is not greater than or equal to 1. declare [-aAfFgiIlnrtux] [-p] [name[=value] ...] typeset [-aAfFgiIlnrtux] [-p] [name[=value] ...] Declare variables and/or give them attributes. If no names are given then display the values of variables. The -p option will display the attributes and values of each name. When -p is used with name arguments, additional options, other than -f and -F, are ignored. When -p is supplied without name arguments, it will display the attributes and values of all variables having the attributes specified by the additional options. If no other options are supplied with -p, declare will display the attributes and values of all shell variables. The -f option will restrict the display to shell functions. The -F option inhibits the display of function definitions; only the function name and attributes are printed. If the extdebug shell option is enabled using shopt, the source file name and line number where each name is defined are displayed as well. The -F option implies -f. The -g option forces variables to be created or modified at the global scope, even when declare is executed in a shell function. It is ignored in all other cases. The -I option causes local variables to inherit the attributes (except the nameref attribute) and value of any existing variable with the same name at a surrounding scope. If there is no existing variable, the local variable is initially unset. The following options can be used to restrict output to variables with the specified attribute or to give variables attributes: -a Each name is an indexed array variable (see Arrays above). -A Each name is an associative array variable (see Arrays above). -f Use function names only. -i The variable is treated as an integer; arithmetic evaluation (see ARITHMETIC EVALUATION above) is performed when the variable is assigned a value. -l When the variable is assigned a value, all upper- case characters are converted to lower-case. The upper-case attribute is disabled. -n Give each name the nameref attribute, making it a name reference to another variable. That other variable is defined by the value of name. All references, assignments, and attribute modifications to name, except those using or changing the -n attribute itself, are performed on the variable referenced by name's value. The nameref attribute cannot be applied to array variables. -r Make names readonly. These names cannot then be assigned values by subsequent assignment statements or unset. -t Give each name the trace attribute. Traced functions inherit the DEBUG and RETURN traps from the calling shell. The trace attribute has no special meaning for variables. -u When the variable is assigned a value, all lower- case characters are converted to upper-case. The lower-case attribute is disabled. -x Mark names for export to subsequent commands via the environment. Using `+' instead of `-' turns off the attribute instead, with the exceptions that +a and +A may not be used to destroy array variables and +r will not remove the readonly attribute. When used in a function, declare and typeset make each name local, as with the local command, unless the -g option is supplied. If a variable name is followed by =value, the value of the variable is set to value. When using -a or -A and the compound assignment syntax to create array variables, additional attributes do not take effect until subsequent assignments. The return value is 0 unless an invalid option is encountered, an attempt is made to define a function using ``-f foo=bar'', an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see Arrays above), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-existent function with -f. dirs [-clpv] [+n] [-n] Without options, displays the list of currently remembered directories. The default display is on a single line with directory names separated by spaces. Directories are added to the list with the pushd command; the popd command removes entries from the list. The current directory is always the first directory in the stack. -c Clears the directory stack by deleting all of the entries. -l Produces a listing using full pathnames; the default listing format uses a tilde to denote the home directory. -p Print the directory stack with one entry per line. -v Print the directory stack with one entry per line, prefixing each entry with its index in the stack. +n Displays the nth entry counting from the left of the list shown by dirs when invoked without options, starting with zero. -n Displays the nth entry counting from the right of the list shown by dirs when invoked without options, starting with zero. The return value is 0 unless an invalid option is supplied or n indexes beyond the end of the directory stack. disown [-ar] [-h] [jobspec ... | pid ... ] Without options, remove each jobspec from the table of active jobs. If jobspec is not present, and neither the -a nor the -r option is supplied, the current job is used. If the -h option is given, each jobspec is not removed from the table, but is marked so that SIGHUP is not sent to the job if the shell receives a SIGHUP. If no jobspec is supplied, the -a option means to remove or mark all jobs; the -r option without a jobspec argument restricts operation to running jobs. The return value is 0 unless a jobspec does not specify a valid job. echo [-neE] [arg ...] Output the args, separated by spaces, followed by a newline. The return status is 0 unless a write error occurs. If -n is specified, the trailing newline is suppressed. If the -e option is given, interpretation of the following backslash-escaped characters is enabled. The -E option disables the interpretation of these escape characters, even on systems where they are interpreted by default. The xpg_echo shell option may be used to dynamically determine whether or not echo expands these escape characters by default. echo does not interpret -- to mean the end of options. echo interprets the following escape sequences: \a alert (bell) \b backspace \c suppress further output \e \E an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \0nnn the eight-bit character whose value is the octal value nnn (zero to three octal digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \uHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits) \UHHHHHHHH the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits) enable [-a] [-dnps] [-f filename] [name ...] Enable and disable builtin shell commands. Disabling a builtin allows a disk command which has the same name as a shell builtin to be executed without specifying a full pathname, even though the shell normally searches for builtins before disk commands. If -n is used, each name is disabled; otherwise, names are enabled. For example, to use the test binary found via the PATH instead of the shell builtin version, run ``enable -n test''. The -f option means to load the new builtin command name from shared object filename, on systems that support dynamic loading. Bash will use the value of the BASH_LOADABLES_PATH variable as a colon-separated list of directories in which to search for filename. The default is system-dependent. The -d option will delete a builtin previously loaded with -f. If no name arguments are given, or if the -p option is supplied, a list of shell builtins is printed. With no other option arguments, the list consists of all enabled shell builtins. If -n is supplied, only disabled builtins are printed. If -a is supplied, the list printed includes all builtins, with an indication of whether or not each is enabled. If -s is supplied, the output is restricted to the POSIX special builtins. If no options are supplied and a name is not a shell builtin, enable will attempt to load name from a shared object named name, as if the command were ``enable -f name name . The return value is 0 unless a name is not a shell builtin or there is an error loading a new builtin from a shared object. eval [arg ...] The args are read and concatenated together into a single command. This command is then read and executed by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0. exec [-cl] [-a name] [command [arguments]] If command is specified, it replaces the shell. No new process is created. The arguments become the arguments to command. If the -l option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what login(1) does. The -c option causes command to be executed with an empty environment. If -a is supplied, the shell passes name as the zeroth argument to the executed command. If command cannot be executed for some reason, a non-interactive shell exits, unless the execfail shell option is enabled. In that case, it returns failure. An interactive shell returns failure if the file cannot be executed. A subshell exits unconditionally if exec fails. If command is not specified, any redirections take effect in the current shell, and the return status is 0. If there is a redirection error, the return status is 1. exit [n] Cause the shell to exit with a status of n. If n is omitted, the exit status is that of the last command executed. A trap on EXIT is executed before the shell terminates. export [-fn] [name[=word]] ... export -p The supplied names are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of names of all exported variables is printed. The -n option causes the export property to be removed from each name. If a variable name is followed by =word, the value of the variable is set to word. export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function. fc [-e ename] [-lnr] [first] [last] fc -s [pat=rep] [cmd] The first form selects a range of commands from first to last from the history list and displays or edits and re- executes them. First and last may be specified as a string (to locate the last command beginning with that string) or as a number (an index into the history list, where a negative number is used as an offset from the current command number). When listing, a first or last of 0 is equivalent to -1 and -0 is equivalent to the current command (usually the fc command); otherwise 0 is equivalent to -1 and -0 is invalid. If last is not specified, it is set to the current command for listing (so that ``fc -l -10'' prints the last 10 commands) and to first otherwise. If first is not specified, it is set to the previous command for editing and -16 for listing. The -n option suppresses the command numbers when listing. The -r option reverses the order of the commands. If the -l option is given, the commands are listed on standard output. Otherwise, the editor given by ename is invoked on a file containing those commands. If ename is not given, the value of the FCEDIT variable is used, and the value of EDITOR if FCEDIT is not set. If neither variable is set, vi is used. When editing is complete, the edited commands are echoed and executed. In the second form, command is re-executed after each instance of pat is replaced by rep. Command is interpreted the same as first above. A useful alias to use with this is ``r="fc -s"'', so that typing ``r cc'' runs the last command beginning with ``cc'' and typing ``r'' re-executes the last command. If the first form is used, the return value is 0 unless an invalid option is encountered or first or last specify history lines out of range. If the -e option is supplied, the return value is the value of the last command executed or failure if an error occurs with the temporary file of commands. If the second form is used, the return status is that of the command re-executed, unless cmd does not specify a valid history line, in which case fc returns failure. fg [jobspec] Resume jobspec in the foreground, and make it the current job. If jobspec is not present, the shell's notion of the current job is used. The return value is that of the command placed into the foreground, or failure if run when job control is disabled or, when run with job control enabled, if jobspec does not specify a valid job or jobspec specifies a job that was started without job control. getopts optstring name [arg ...] getopts is used by shell procedures to parse positional parameters. optstring contains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by white space. The colon and question mark characters may not be used as option characters. Each time it is invoked, getopts places the next option in the shell variable name, initializing name if it does not exist, and the index of the next argument to be processed into the variable OPTIND. OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the variable OPTARG. The shell does not reset OPTIND automatically; it must be manually reset between multiple calls to getopts within the same shell invocation if a new set of parameters is to be used. When the end of options is encountered, getopts exits with a return value greater than zero. OPTIND is set to the index of the first non-option argument, and name is set to ?. getopts normally parses the positional parameters, but if more arguments are supplied as arg values, getopts parses those instead. getopts can report errors in two ways. If the first character of optstring is a colon, silent error reporting is used. In normal operation, diagnostic messages are printed when invalid options or missing option arguments are encountered. If the variable OPTERR is set to 0, no error messages will be displayed, even if the first character of optstring is not a colon. If an invalid option is seen, getopts places ? into name and, if not silent, prints an error message and unsets OPTARG. If getopts is silent, the option character found is placed in OPTARG and no diagnostic message is printed. If a required argument is not found, and getopts is not silent, a question mark (?) is placed in name, OPTARG is unset, and a diagnostic message is printed. If getopts is silent, then a colon (:) is placed in name and OPTARG is set to the option character found. getopts returns true if an option, specified or unspecified, is found. It returns false if the end of options is encountered or an error occurs. hash [-lr] [-p filename] [-dt] [name] Each time hash is invoked, the full pathname of the command name is determined by searching the directories in $PATH and remembered. Any previously-remembered pathname is discarded. If the -p option is supplied, no path search is performed, and filename is used as the full filename of the command. The -r option causes the shell to forget all remembered locations. The -d option causes the shell to forget the remembered location of each name. If the -t option is supplied, the full pathname to which each name corresponds is printed. If multiple name arguments are supplied with -t, the name is printed before the hashed full pathname. The -l option causes output to be displayed in a format that may be reused as input. If no arguments are given, or if only -l is supplied, information about remembered commands is printed. The return status is true unless a name is not found or an invalid option is supplied. help [-dms] [pattern] Display helpful information about builtin commands. If pattern is specified, help gives detailed help on all commands matching pattern; otherwise help for all the builtins and shell control structures is printed. -d Display a short description of each pattern -m Display the description of each pattern in a manpage-like format -s Display only a short usage synopsis for each pattern The return status is 0 unless no command matches pattern. history [n] history -c history -d offset history -d start-end history -anrw [filename] history -p arg [arg ...] history -s arg [arg ...] With no options, display the command history list with line numbers. Lines listed with a * have been modified. An argument of n lists only the last n lines. If the shell variable HISTTIMEFORMAT is set and not null, it is used as a format string for strftime(3) to display the time stamp associated with each displayed history entry. No intervening blank is printed between the formatted time stamp and the history line. If filename is supplied, it is used as the name of the history file; if not, the value of HISTFILE is used. Options, if supplied, have the following meanings: -c Clear the history list by deleting all the entries. -d offset Delete the history entry at position offset. If offset is negative, it is interpreted as relative to one greater than the last history position, so negative indices count back from the end of the history, and an index of -1 refers to the current history -d command. -d start-end Delete the range of history entries between positions start and end, inclusive. Positive and negative values for start and end are interpreted as described above. -a Append the ``new'' history lines to the history file. These are history lines entered since the beginning of the current bash session, but not already appended to the history file. -n Read the history lines not already read from the history file into the current history list. These are lines appended to the history file since the beginning of the current bash session. -r Read the contents of the history file and append them to the current history list. -w Write the current history list to the history file, overwriting the history file's contents. -p Perform history substitution on the following args and display the result on the standard output. Does not store the results in the history list. Each arg must be quoted to disable normal history expansion. -s Store the args in the history list as a single entry. The last command in the history list is removed before the args are added. If the HISTTIMEFORMAT variable is set, the time stamp information associated with each history entry is written to the history file, marked with the history comment character. When the history file is read, lines beginning with the history comment character followed immediately by a digit are interpreted as timestamps for the following history entry. The return value is 0 unless an invalid option is encountered, an error occurs while reading or writing the history file, an invalid offset or range is supplied as an argument to -d, or the history expansion supplied as an argument to -p fails. jobs [-lnprs] [ jobspec ... ] jobs -x command [ args ... ] The first form lists the active jobs. The options have the following meanings: -l List process IDs in addition to the normal information. -n Display information only about jobs that have changed status since the user was last notified of their status. -p List only the process ID of the job's process group leader. -r Display only running jobs. -s Display only stopped jobs. If jobspec is given, output is restricted to information about that job. The return status is 0 unless an invalid option is encountered or an invalid jobspec is supplied. If the -x option is supplied, jobs replaces any jobspec found in command or args with the corresponding process group ID, and executes command passing it args, returning its exit status. kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ... kill -l|-L [sigspec | exit_status] Send the signal named by sigspec or signum to the processes named by pid or jobspec. sigspec is either a case-insensitive signal name such as SIGKILL (with or without the SIG prefix) or a signal number; signum is a signal number. If sigspec is not present, then SIGTERM is assumed. An argument of -l lists the signal names. If any arguments are supplied when -l is given, the names of the signals corresponding to the arguments are listed, and the return status is 0. The exit_status argument to -l is a number specifying either a signal number or the exit status of a process terminated by a signal. The -L option is equivalent to -l. kill returns true if at least one signal was successfully sent, or false if an error occurs or an invalid option is encountered. let arg [arg ...] Each arg is an arithmetic expression to be evaluated (see ARITHMETIC EVALUATION above). If the last arg evaluates to 0, let returns 1; 0 is returned otherwise. local [option] [name[=value] ... | - ] For each argument, a local variable named name is created, and assigned value. The option can be any of the options accepted by declare. When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children. If name is -, the set of shell options is made local to the function in which local is invoked: shell options changed using the set builtin inside the function are restored to their original values when the function returns. The restore is effected as if a series of set commands were executed to restore the values that were in place before the function. With no operands, local writes a list of local variables to the standard output. It is an error to use local when not within a function. The return status is 0 unless local is used outside a function, an invalid name is supplied, or name is a readonly variable. logout Exit a login shell. mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array] readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array] Read lines from the standard input into the indexed array variable array, or from file descriptor fd if the -u option is supplied. The variable MAPFILE is the default array. Options, if supplied, have the following meanings: -d The first character of delim is used to terminate each input line, rather than newline. If delim is the empty string, mapfile will terminate a line when it reads a NUL character. -n Copy at most count lines. If count is 0, all lines are copied. -O Begin assigning to array at index origin. The default index is 0. -s Discard the first count lines read. -t Remove a trailing delim (default newline) from each line read. -u Read lines from file descriptor fd instead of the standard input. -C Evaluate callback each time quantum lines are read. The -c option specifies quantum. -c Specify the number of lines read between each call to callback. If -C is specified without -c, the default quantum is 5000. When callback is evaluated, it is supplied the index of the next array element to be assigned and the line to be assigned to that element as additional arguments. callback is evaluated after the line is read but before the array element is assigned. If not supplied with an explicit origin, mapfile will clear array before assigning to it. mapfile returns successfully unless an invalid option or option argument is supplied, array is invalid or unassignable, or if array is not an indexed array. popd [-n] [+n] [-n] Removes entries from the directory stack. The elements are numbered from 0 starting at the first directory listed by dirs. With no arguments, popd removes the top directory from the stack, and changes to the new top directory. Arguments, if supplied, have the following meanings: -n Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. +n Removes the nth entry counting from the left of the list shown by dirs, starting with zero, from the stack. For example: ``popd +0'' removes the first directory, ``popd +1'' the second. -n Removes the nth entry counting from the right of the list shown by dirs, starting with zero. For example: ``popd -0'' removes the last directory, ``popd -1'' the next to last. If the top element of the directory stack is modified, and the -n option was not supplied, popd uses the cd builtin to change to the directory at the top of the stack. If the cd fails, popd returns a non-zero value. Otherwise, popd returns false if an invalid option is encountered, the directory stack is empty, or a non- existent directory stack entry is specified. If the popd command is successful, bash runs dirs to show the final contents of the directory stack, and the return status is 0. printf [-v var] format [arguments] Write the formatted arguments to the standard output under the control of the format. The -v option causes the output to be assigned to the variable var rather than being printed to the standard output. The format is a character string which contains three types of objects: plain characters, which are simply copied to standard output, character escape sequences, which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. In addition to the standard printf(1) format specifications, printf interprets the following extensions: %b causes printf to expand backslash escape sequences in the corresponding argument in the same way as echo -e. %q causes printf to output the corresponding argument in a format that can be reused as shell input. %Q like %q, but applies any supplied precision to the argument before quoting it. %(datefmt)T causes printf to output the date-time string resulting from using datefmt as a format string for strftime(3). The corresponding argument is an integer representing the number of seconds since the epoch. Two special argument values may be used: -1 represents the current time, and -2 represents the time the shell was invoked. If no argument is specified, conversion behaves as if -1 had been given. This is an exception to the usual printf behavior. The %b, %q, and %T directives all use the field width and precision arguments from the format specification and write that many bytes from (or use that wide a field for) the expanded argument, which usually contains more characters than the original. Arguments to non-string format specifiers are treated as C constants, except that a leading plus or minus sign is allowed, and if the leading character is a single or double quote, the value is the ASCII value of the following character. The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. The return value is zero on success, non-zero on failure. pushd [-n] [+n] [-n] pushd [-n] [dir] Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the current working directory. With no arguments, pushd exchanges the top two elements of the directory stack. Arguments, if supplied, have the following meanings: -n Suppresses the normal change of directory when rotating or adding directories to the stack, so that only the stack is manipulated. +n Rotates the stack so that the nth directory (counting from the left of the list shown by dirs, starting with zero) is at the top. -n Rotates the stack so that the nth directory (counting from the right of the list shown by dirs, starting with zero) is at the top. dir Adds dir to the directory stack at the top After the stack has been modified, if the -n option was not supplied, pushd uses the cd builtin to change to the directory at the top of the stack. If the cd fails, pushd returns a non-zero value. Otherwise, if no arguments are supplied, pushd returns 0 unless the directory stack is empty. When rotating the directory stack, pushd returns 0 unless the directory stack is empty or a non-existent directory stack element is specified. If the pushd command is successful, bash runs dirs to show the final contents of the directory stack. pwd [-LP] Print the absolute pathname of the current working directory. The pathname printed contains no symbolic links if the -P option is supplied or the -o physical option to the set builtin command is enabled. If the -L option is used, the pathname printed may contain symbolic links. The return status is 0 unless an error occurs while reading the name of the current directory or an invalid option is supplied. read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...] One line is read from the standard input, or from the file descriptor fd supplied as an argument to the -u option, split into words as described above under Word Splitting, and the first word is assigned to the first name, the second word to the second name, and so on. If there are more words than names, the remaining words and their intervening delimiters are assigned to the last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values. The characters in IFS are used to split the line into words using the same rules the shell uses for expansion (described above under Word Splitting). The backslash character (\) may be used to remove any special meaning for the next character read and for line continuation. Options, if supplied, have the following meanings: -a aname The words are assigned to sequential indices of the array variable aname, starting at 0. aname is unset before any new values are assigned. Other name arguments are ignored. -d delim The first character of delim is used to terminate the input line, rather than newline. If delim is the empty string, read will terminate a line when it reads a NUL character. -e If the standard input is coming from a terminal, readline (see READLINE above) is used to obtain the line. Readline uses the current (or default, if line editing was not previously active) editing settings, but uses readline's default filename completion. -i text If readline is being used to read the line, text is placed into the editing buffer before editing begins. -n nchars read returns after reading nchars characters rather than waiting for a complete line of input, but honors a delimiter if fewer than nchars characters are read before the delimiter. -N nchars read returns after reading exactly nchars characters rather than waiting for a complete line of input, unless EOF is encountered or read times out. Delimiter characters encountered in the input are not treated specially and do not cause read to return until nchars characters are read. The result is not split on the characters in IFS; the intent is that the variable is assigned exactly the characters read (with the exception of backslash; see the -r option below). -p prompt Display prompt on standard error, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal. -r Backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not then be used as a line continuation. -s Silent mode. If input is coming from a terminal, characters are not echoed. -t timeout Cause read to time out and return failure if a complete line of input (or a specified number of characters) is not read within timeout seconds. timeout may be a decimal number with a fractional portion following the decimal point. This option is only effective if read is reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If read times out, read saves any partial input read into the specified variable name. If timeout is 0, read returns immediately, without trying to read any data. The exit status is 0 if input is available on the specified file descriptor, or the read will return EOF, non-zero otherwise. The exit status is greater than 128 if the timeout is exceeded. -u fd Read input from file descriptor fd. If no names are supplied, the line read, without the ending delimiter but otherwise unmodified, is assigned to the variable REPLY. The exit status is zero, unless end- of-file is encountered, read times out (in which case the status is greater than 128), a variable assignment error (such as assigning to a readonly variable) occurs, or an invalid file descriptor is supplied as the argument to -u. readonly [-aAf] [-p] [name[=word] ...] The given names are marked readonly; the values of these names may not be changed by subsequent assignment. If the -f option is supplied, the functions corresponding to the names are so marked. The -a option restricts the variables to indexed arrays; the -A option restricts the variables to associative arrays. If both options are supplied, -A takes precedence. If no name arguments are given, or if the -p option is supplied, a list of all readonly names is printed. The other options may be used to restrict the output to a subset of the set of readonly names. The -p option causes output to be displayed in a format that may be reused as input. If a variable name is followed by =word, the value of the variable is set to word. The return status is 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function. return [n] Causes a function to stop executing and return the value specified by n to its caller. If n is omitted, the return status is that of the last command executed in the function body. If return is executed by a trap handler, the last command used to determine the status is the last command executed before the trap handler. If return is executed during a DEBUG trap, the last command used to determine the status is the last command executed by the trap handler before return was invoked. If return is used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. If n is supplied, the return value is its least significant 8 bits. The return status is non-zero if return is supplied a non-numeric argument, or is used outside a function and not during execution of a script by . or source. Any command associated with the RETURN trap is executed before execution resumes after the function or script. set [-abefhkmnptuvxBCEHPT] [-o option-name] [--] [-] [arg ...] set [+abefhkmnptuvxBCEHPT] [+o option-name] [--] [-] [arg ...] Without options, display the name and value of each shell variable in a format that can be reused as input for setting or resetting the currently-set variables. Read- only variables cannot be reset. In posix mode, only shell variables are listed. The output is sorted according to the current locale. When options are specified, they set or unset shell attributes. Any arguments remaining after option processing are treated as values for the positional parameters and are assigned, in order, to $1, $2, ... $n. Options, if specified, have the following meanings: -a Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands. -b Report the status of terminated background jobs immediately, rather than before the next primary prompt. This is effective only when job control is enabled. -e Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR above), exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !. If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit. A trap on ERR, if set, is executed before the shell exits. This option applies to the shell environment and each subshell environment separately (see COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit before executing all the commands in the subshell. If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed within the compound command or function body will be affected by the -e setting, even if -e is set and a command returns a failure status. If a compound command or shell function sets -e while executing in a context where -e is ignored, that setting will not have any effect until the compound command or the command containing the function call completes. -f Disable pathname expansion. -h Remember the location of commands as they are looked up for execution. This is enabled by default. -k All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name. -m Monitor mode. Job control is enabled. This option is on by default for interactive shells on systems that support it (see JOB CONTROL above). All processes run in a separate process group. When a background job completes, the shell prints a line containing its exit status. -n Read commands but do not execute them. This may be used to check a shell script for syntax errors. This is ignored by interactive shells. -o option-name The option-name can be one of the following: allexport Same as -a. braceexpand Same as -B. emacs Use an emacs-style command line editing interface. This is enabled by default when the shell is interactive, unless the shell is started with the --noediting option. This also affects the editing interface used for read -e. errexit Same as -e. errtrace Same as -E. functrace Same as -T. hashall Same as -h. histexpand Same as -H. history Enable command history, as described above under HISTORY. This option is on by default in interactive shells. ignoreeof The effect is as if the shell command ``IGNOREEOF=10'' had been executed (see Shell Variables above). keyword Same as -k. monitor Same as -m. noclobber Same as -C. noexec Same as -n. noglob Same as -f. nolog Currently ignored. notify Same as -b. nounset Same as -u. onecmd Same as -t. physical Same as -P. pipefail If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default. posix Change the behavior of bash where the default operation differs from the POSIX standard to match the standard (posix mode). See SEE ALSO below for a reference to a document that details how posix mode affects bash's behavior. privileged Same as -p. verbose Same as -v. vi Use a vi-style command line editing interface. This also affects the editing interface used for read -e. xtrace Same as -x. If -o is supplied with no option-name, the values of the current options are printed. If +o is supplied with no option-name, a series of set commands to recreate the current option settings is displayed on the standard output. -p Turn on privileged mode. In this mode, the $ENV and $BASH_ENV files are not processed, shell functions are not inherited from the environment, and the SHELLOPTS, BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear in the environment, are ignored. If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, these actions are taken and the effective user id is set to the real user id. If the -p option is supplied at startup, the effective user id is not reset. Turning this option off causes the effective user and group ids to be set to the real user and group ids. -r Enable restricted shell mode. This option cannot be unset once it has been set. -t Exit after reading and executing one command. -u Treat unset variables and parameters other than the special parameters "@" and "*", or array variables subscripted with "@" or "*", as an error when performing parameter expansion. If expansion is attempted on an unset variable or parameter, the shell prints an error message, and, if not interactive, exits with a non-zero status. -v Print shell input lines as they are read. -x After expanding each simple command, for command, case command, select command, or arithmetic for command, display the expanded value of PS4, followed by the command and its expanded arguments or associated word list. -B The shell performs brace expansion (see Brace Expansion above). This is on by default. -C If set, bash does not overwrite an existing file with the >, >&, and <> redirection operators. This may be overridden when creating output files by using the redirection operator >| instead of >. -E If set, any trap on ERR is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The ERR trap is normally not inherited in such cases. -H Enable ! style history substitution. This option is on by default when the shell is interactive. -P If set, the shell does not resolve symbolic links when executing commands such as cd that change the current working directory. It uses the physical directory structure instead. By default, bash follows the logical chain of directories when performing commands which change the current directory. -T If set, any traps on DEBUG and RETURN are inherited by shell functions, command substitutions, and commands executed in a subshell environment. The DEBUG and RETURN traps are normally not inherited in such cases. -- If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters are set to the args, even if some of them begin with a -. - Signal the end of options, cause all remaining args to be assigned to the positional parameters. The -x and -v options are turned off. If there are no args, the positional parameters remain unchanged. The options are off by default unless otherwise noted. Using + rather than - causes these options to be turned off. The options can also be specified as arguments to an invocation of the shell. The current set of options may be found in $-. The return status is always true unless an invalid option is encountered. shift [n] The positional parameters from n+1 ... are renamed to $1 .... Parameters represented by the numbers $# down to $#-n+1 are unset. n must be a non-negative number less than or equal to $#. If n is 0, no parameters are changed. If n is not given, it is assumed to be 1. If n is greater than $#, the positional parameters are not changed. The return status is greater than zero if n is greater than $# or less than zero; otherwise 0. shopt [-pqsu] [-o] [optname ...] Toggle the values of settings controlling optional shell behavior. The settings can be either those listed below, or, if the -o option is used, those available with the -o option to the set builtin command. With no options, or with the -p option, a list of all settable options is displayed, with an indication of whether or not each is set; if optnames are supplied, the output is restricted to those options. The -p option causes output to be displayed in a form that may be reused as input. Other options have the following meanings: -s Enable (set) each optname. -u Disable (unset) each optname. -q Suppresses normal output (quiet mode); the return status indicates whether the optname is set or unset. If multiple optname arguments are given with -q, the return status is zero if all optnames are enabled; non-zero otherwise. -o Restricts the values of optname to be those defined for the -o option to the set builtin. If either -s or -u is used with no optname arguments, shopt shows only those options which are set or unset, respectively. Unless otherwise noted, the shopt options are disabled (unset) by default. The return status when listing options is zero if all optnames are enabled, non-zero otherwise. When setting or unsetting options, the return status is zero unless an optname is not a valid shell option. The list of shopt options is: assoc_expand_once If set, the shell suppresses multiple evaluation of associative array subscripts during arithmetic expression evaluation, while executing builtins that can perform variable assignments, and while executing builtins that perform array dereferencing. autocd If set, a command name that is the name of a directory is executed as if it were the argument to the cd command. This option is only used by interactive shells. cdable_vars If set, an argument to the cd builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to. cdspell If set, minor errors in the spelling of a directory component in a cd command will be corrected. The errors checked for are transposed characters, a missing character, and one character too many. If a correction is found, the corrected filename is printed, and the command proceeds. This option is only used by interactive shells. checkhash If set, bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed. checkjobs If set, bash lists the status of any stopped and running jobs before exiting an interactive shell. If any jobs are running, this causes the exit to be deferred until a second exit is attempted without an intervening command (see JOB CONTROL above). The shell always postpones exiting if any jobs are stopped. checkwinsize If set, bash checks the window size after each external (non-builtin) command and, if necessary, updates the values of LINES and COLUMNS. This option is enabled by default. cmdhist If set, bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multi-line commands. This option is enabled by default, but only has an effect if command history is enabled, as described above under HISTORY. compat31 compat32 compat40 compat41 compat42 compat43 compat44 compat50 These control aspects of the shell's compatibility mode (see SHELL COMPATIBILITY MODE below). complete_fullquote If set, bash quotes all shell metacharacters in filenames and directory names when performing completion. If not set, bash removes metacharacters such as the dollar sign from the set of characters that will be quoted in completed filenames when these metacharacters appear in shell variable references in words to be completed. This means that dollar signs in variable names that expand to directories will not be quoted; however, any dollar signs appearing in filenames will not be quoted, either. This is active only when bash is using backslashes to quote completed filenames. This variable is set by default, which is the default bash behavior in versions through 4.2. direxpand If set, bash replaces directory names with the results of word expansion when performing filename completion. This changes the contents of the readline editing buffer. If not set, bash attempts to preserve what the user typed. dirspell If set, bash attempts spelling correction on directory names during word completion if the directory name initially supplied does not exist. dotglob If set, bash includes filenames beginning with a `.' in the results of pathname expansion. The filenames ``.'' and ``..'' must always be matched explicitly, even if dotglob is set. execfail If set, a non-interactive shell will not exit if it cannot execute the file specified as an argument to the exec builtin command. An interactive shell does not exit if exec fails. expand_aliases If set, aliases are expanded as described above under ALIASES. This option is enabled by default for interactive shells. extdebug If set at shell invocation, or in a shell startup file, arrange to execute the debugger profile before the shell starts, identical to the --debugger option. If set after invocation, behavior intended for use by debuggers is enabled: 1. The -F option to the declare builtin displays the source file name and line number corresponding to each function name supplied as an argument. 2. If the command run by the DEBUG trap returns a non-zero value, the next command is skipped and not executed. 3. If the command run by the DEBUG trap returns a value of 2, and the shell is executing in a subroutine (a shell function or a shell script executed by the . or source builtins), the shell simulates a call to return. 4. BASH_ARGC and BASH_ARGV are updated as described in their descriptions above). 5. Function tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the DEBUG and RETURN traps. 6. Error tracing is enabled: command substitution, shell functions, and subshells invoked with ( command ) inherit the ERR trap. extglob If set, the extended pattern matching features described above under Pathname Expansion are enabled. extquote If set, $'string' and $"string" quoting is performed within ${parameter} expansions enclosed in double quotes. This option is enabled by default. failglob If set, patterns which fail to match filenames during pathname expansion result in an expansion error. force_fignore If set, the suffixes specified by the FIGNORE shell variable cause words to be ignored when performing word completion even if the ignored words are the only possible completions. See SHELL VARIABLES above for a description of FIGNORE. This option is enabled by default. globasciiranges If set, range expressions used in pattern matching bracket expressions (see Pattern Matching above) behave as if in the traditional C locale when performing comparisons. That is, the current locale's collating sequence is not taken into account, so b will not collate between A and B, and upper-case and lower-case ASCII characters will collate together. globskipdots If set, pathname expansion will never match the filenames ``.'' and ``..'', even if the pattern begins with a ``.''. This option is enabled by default. globstar If set, the pattern ** used in a pathname expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a /, only directories and subdirectories match. gnu_errfmt If set, shell error messages are written in the standard GNU error message format. histappend If set, the history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file. histreedit If set, and readline is being used, a user is given the opportunity to re-edit a failed history substitution. histverify If set, and readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the readline editing buffer, allowing further modification. hostcomplete If set, and readline is being used, bash will attempt to perform hostname completion when a word containing a @ is being completed (see Completing under READLINE above). This is enabled by default. huponexit If set, bash will send SIGHUP to all jobs when an interactive login shell exits. inherit_errexit If set, command substitution inherits the value of the errexit option, instead of unsetting it in the subshell environment. This option is enabled when posix mode is enabled. interactive_comments If set, allow a word beginning with # to cause that word and all remaining characters on that line to be ignored in an interactive shell (see COMMENTS above). This option is enabled by default. lastpipe If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment. lithist If set, and the cmdhist option is enabled, multi- line commands are saved to the history with embedded newlines rather than using semicolon separators where possible. localvar_inherit If set, local variables inherit the value and attributes of a variable of the same name that exists at a previous scope before any new value is assigned. The nameref attribute is not inherited. localvar_unset If set, calling unset on local variables in previous function scopes marks them so subsequent lookups find them unset until that function returns. This is identical to the behavior of unsetting local variables at the current function scope. login_shell The shell sets this option if it is started as a login shell (see INVOCATION above). The value may not be changed. mailwarn If set, and a file that bash is checking for mail has been accessed since the last time it was checked, the message ``The mail in mailfile has been read'' is displayed. no_empty_cmd_completion If set, and readline is being used, bash will not attempt to search the PATH for possible completions when completion is attempted on an empty line. nocaseglob If set, bash matches filenames in a case-insensitive fashion when performing pathname expansion (see Pathname Expansion above). nocasematch If set, bash matches patterns in a case-insensitive fashion when performing matching while executing case or [[ conditional commands, when performing pattern substitution word expansions, or when filtering possible completions as part of programmable completion. noexpand_translation If set, bash encloses the translated results of $"..." quoting in single quotes instead of double quotes. If the string is not translated, this has no effect. nullglob If set, bash allows patterns which match no files (see Pathname Expansion above) to expand to a null string, rather than themselves. patsub_replacement If set, bash expands occurrences of & in the replacement string of pattern substitution to the text matched by the pattern, as described under Parameter Expansion above. This option is enabled by default. progcomp If set, the programmable completion facilities (see Programmable Completion above) are enabled. This option is enabled by default. progcomp_alias If set, and programmable completion is enabled, bash treats a command name that doesn't have any completions as a possible alias and attempts alias expansion. If it has an alias, bash attempts programmable completion using the command word resulting from the expanded alias. promptvars If set, prompt strings undergo parameter expansion, command substitution, arithmetic expansion, and quote removal after being expanded as described in PROMPTING above. This option is enabled by default. restricted_shell The shell sets this option if it is started in restricted mode (see RESTRICTED SHELL below). The value may not be changed. This is not reset when the startup files are executed, allowing the startup files to discover whether or not a shell is restricted. shift_verbose If set, the shift builtin prints an error message when the shift count exceeds the number of positional parameters. sourcepath If set, the . (source) builtin uses the value of PATH to find the directory containing the file supplied as an argument. This option is enabled by default. varredir_close If set, the shell automatically closes file descriptors assigned using the {varname} redirection syntax (see REDIRECTION above) instead of leaving them open when the command completes. xpg_echo If set, the echo builtin expands backslash-escape sequences by default. suspend [-f] Suspend the execution of this shell until it receives a SIGCONT signal. A login shell, or a shell without job control enabled, cannot be suspended; the -f option can be used to override this and force the suspension. The return status is 0 unless the shell is a login shell or job control is not enabled and -f is not supplied. test expr [ expr ] Return a status of 0 (true) or 1 (false) depending on the evaluation of the conditional expression expr. Each operator and operand must be a separate argument. Expressions are composed of the primaries described above under CONDITIONAL EXPRESSIONS. test does not accept any options, nor does it accept and ignore an argument of -- as signifying the end of options. Expressions may be combined using the following operators, listed in decreasing order of precedence. The evaluation depends on the number of arguments; see below. Operator precedence is used when there are five or more arguments. ! expr True if expr is false. ( expr ) Returns the value of expr. This may be used to override the normal precedence of operators. expr1 -a expr2 True if both expr1 and expr2 are true. expr1 -o expr2 True if either expr1 or expr2 is true. test and [ evaluate conditional expressions using a set of rules based on the number of arguments. 0 arguments The expression is false. 1 argument The expression is true if and only if the argument is not null. 2 arguments If the first argument is !, the expression is true if and only if the second argument is null. If the first argument is one of the unary conditional operators listed above under CONDITIONAL EXPRESSIONS, the expression is true if the unary test is true. If the first argument is not a valid unary conditional operator, the expression is false. 3 arguments The following conditions are applied in the order listed. If the second argument is one of the binary conditional operators listed above under CONDITIONAL EXPRESSIONS, the result of the expression is the result of the binary test using the first and third arguments as operands. The -a and -o operators are considered binary operators when there are three arguments. If the first argument is !, the value is the negation of the two-argument test using the second and third arguments. If the first argument is exactly ( and the third argument is exactly ), the result is the one-argument test of the second argument. Otherwise, the expression is false. 4 arguments The following conditions are applied in the order listed. If the first argument is !, the result is the negation of the three-argument expression composed of the remaining arguments. the two- argument test using the second and third arguments. If the first argument is exactly ( and the fourth argument is exactly ), the result is the two- argument test of the second and third arguments. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above. 5 or more arguments The expression is parsed and evaluated according to precedence using the rules listed above. When used with test or [, the < and > operators sort lexicographically using ASCII ordering. times Print the accumulated user and system times for the shell and for processes run from the shell. The return status is 0. trap [-lp] [[arg] sigspec ...] The command arg is to be read and executed when the shell receives signal(s) sigspec. If arg is absent (and there is a single sigspec) or -, each specified signal is reset to its original disposition (the value it had upon entrance to the shell). If arg is the null string the signal specified by each sigspec is ignored by the shell and by the commands it invokes. If arg is not present and -p has been supplied, then the trap commands associated with each sigspec are displayed. If no arguments are supplied or if only -p is given, trap prints the list of commands associated with each signal. The -l option causes the shell to print a list of signal names and their corresponding numbers. Each sigspec is either a signal name defined in <signal.h>, or a signal number. Signal names are case insensitive and the SIG prefix is optional. If a sigspec is EXIT (0) the command arg is executed on exit from the shell. If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function (see SHELL GRAMMAR above). Refer to the description of the extdebug option to the shopt builtin for details of its effect on the DEBUG trap. If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing. If a sigspec is ERR, the command arg is executed whenever a pipeline (which may consist of a single simple command), a list, or a compound command returns a non-zero exit status, subject to the following conditions. The ERR trap is not executed if the failed command is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted using !. These are the same conditions obeyed by the errexit (-e) option. Signals ignored upon entry to the shell cannot be trapped or reset. Trapped signals that are not being ignored are reset to their original values in a subshell or subshell environment when one is created. The return status is false if any sigspec is invalid; otherwise trap returns true. type [-aftpP] name [name ...] With no options, indicate how each name would be interpreted if used as a command name. If the -t option is used, type prints a string which is one of alias, keyword, function, builtin, or file if name is an alias, shell reserved word, function, builtin, or disk file, respectively. If the name is not found, then nothing is printed, and an exit status of false is returned. If the -p option is used, type either returns the name of the disk file that would be executed if name were specified as a command name, or nothing if ``type -t name'' would not return file. The -P option forces a PATH search for each name, even if ``type -t name'' would not return file. If a command is hashed, -p and -P print the hashed value, which is not necessarily the file that appears first in PATH. If the -a option is used, type prints all of the places that contain an executable named name. This includes aliases and functions, if and only if the -p option is not also used. The table of hashed commands is not consulted when using -a. The -f option suppresses shell function lookup, as with the command builtin. type returns true if all of the arguments are found, false if any are not found. ulimit [-HS] -a ulimit [-HS] [-bcdefiklmnpqrstuvxPRT [limit]] Provides control over the resources available to the shell and to processes started by it, on systems that allow such control. The -H and -S options specify that the hard or soft limit is set for the given resource. A hard limit cannot be increased by a non-root user once it is set; a soft limit may be increased up to the value of the hard limit. If neither -H nor -S is specified, both the soft and hard limits are set. The value of limit can be a number in the unit specified for the resource or one of the special values hard, soft, or unlimited, which stand for the current hard limit, the current soft limit, and no limit, respectively. If limit is omitted, the current value of the soft limit of the resource is printed, unless the -H option is given. When more than one resource is specified, the limit name and unit, if appropriate, are printed before the value. Other options are interpreted as follows: -a All current limits are reported; no limits are set -b The maximum socket buffer size -c The maximum size of core files created -d The maximum size of a process's data segment -e The maximum scheduling priority ("nice") -f The maximum size of files written by the shell and its children -i The maximum number of pending signals -k The maximum number of kqueues that may be allocated -l The maximum size that may be locked into memory -m The maximum resident set size (many systems do not honor this limit) -n The maximum number of open file descriptors (most systems do not allow this value to be set) -p The pipe size in 512-byte blocks (this may not be set) -q The maximum number of bytes in POSIX message queues -r The maximum real-time scheduling priority -s The maximum stack size -t The maximum amount of cpu time in seconds -u The maximum number of processes available to a single user -v The maximum amount of virtual memory available to the shell and, on some systems, to its children -x The maximum number of file locks -P The maximum number of pseudoterminals -R The maximum time a real-time process can run before blocking, in microseconds -T The maximum number of threads If limit is given, and the -a option is not used, limit is the new value of the specified resource. If no option is given, then -f is assumed. Values are in 1024-byte increments, except for -t, which is in seconds; -R, which is in microseconds; -p, which is in units of 512-byte blocks; -P, -T, -b, -k, -n, and -u, which are unscaled values; and, when in posix mode, -c and -f, which are in 512-byte increments. The return status is 0 unless an invalid option or argument is supplied, or an error occurs while setting a new limit. umask [-p] [-S] [mode] The user file-creation mask is set to mode. If mode begins with a digit, it is interpreted as an octal number; otherwise it is interpreted as a symbolic mode mask similar to that accepted by chmod(1). If mode is omitted, the current value of the mask is printed. The -S option causes the mask to be printed in symbolic form; the default output is an octal number. If the -p option is supplied, and mode is omitted, the output is in a form that may be reused as input. The return status is 0 if the mode was successfully changed or if no mode argument was supplied, and false otherwise. unalias [-a] [name ...] Remove each name from the list of defined aliases. If -a is supplied, all alias definitions are removed. The return value is true unless a supplied name is not a defined alias. unset [-fv] [-n] [name ...] For each name, remove the corresponding variable or function. If the -v option is given, each name refers to a shell variable, and that variable is removed. Read-only variables may not be unset. If -f is specified, each name refers to a shell function, and the function definition is removed. If the -n option is supplied, and name is a variable with the nameref attribute, name will be unset rather than the variable it references. -n has no effect if the -f option is supplied. If no options are supplied, each name refers to a variable; if there is no variable by that name, a function with that name, if any, is unset. Each unset variable or function is removed from the environment passed to subsequent commands. If any of BASH_ALIASES, BASH_ARGV0, BASH_CMDS, BASH_COMMAND, BASH_SUBSHELL, BASHPID, COMP_WORDBREAKS, DIRSTACK, EPOCHREALTIME, EPOCHSECONDS, FUNCNAME, GROUPS, HISTCMD, LINENO, RANDOM, SECONDS, or SRANDOM are unset, they lose their special properties, even if they are subsequently reset. The exit status is true unless a name is readonly or may not be unset. wait [-fn] [-p varname] [id ...] Wait for each specified child process and return its termination status. Each id may be a process ID or a job specification; if a job spec is given, all processes in that job's pipeline are waited for. If id is not given, wait waits for all running background jobs and the last- executed process substitution, if its process id is the same as $!, and the return status is zero. If the -n option is supplied, wait waits for a single job from the list of ids or, if no ids are supplied, any job, to complete and returns its exit status. If none of the supplied arguments is a child of the shell, or if no arguments are supplied and the shell has no unwaited-for children, the exit status is 127. If the -p option is supplied, the process or job identifier of the job for which the exit status is returned is assigned to the variable varname named by the option argument. The variable will be unset initially, before any assignment. This is useful only when the -n option is supplied. Supplying the -f option, when job control is enabled, forces wait to wait for id to terminate before returning its status, instead of returning when it changes status. If id specifies a non-existent process or job, the return status is 127. If wait is interrupted by a signal, the return status will be greater than 128, as described under SIGNALS above. Otherwise, the return status is the exit status of the last process or job waited for. SHELL COMPATIBILITY MODE top Bash-4.0 introduced the concept of a shell compatibility level, specified as a set of options to the shopt builtin ( compat31, compat32, compat40, compat41, and so on). There is only one current compatibility level -- each option is mutually exclusive. The compatibility level is intended to allow users to select behavior from previous versions that is incompatible with newer versions while they migrate scripts to use current features and behavior. It's intended to be a temporary solution. This section does not mention behavior that is standard for a particular version (e.g., setting compat32 means that quoting the rhs of the regexp matching operator quotes special regexp characters in the word, which is default behavior in bash-3.2 and subsequent versions). If a user enables, say, compat32, it may affect the behavior of other compatibility levels up to and including the current compatibility level. The idea is that each compatibility level controls behavior that changed in that version of bash, but that behavior may have been present in earlier versions. For instance, the change to use locale-based comparisons with the [[ command came in bash-4.1, and earlier versions used ASCII-based comparisons, so enabling compat32 will enable ASCII-based comparisons as well. That granularity may not be sufficient for all uses, and as a result users should employ compatibility levels carefully. Read the documentation for a particular feature to find out the current behavior. Bash-4.3 introduced a new shell variable: BASH_COMPAT. The value assigned to this variable (a decimal version number like 4.2, or an integer corresponding to the compatNN option, like 42) determines the compatibility level. Starting with bash-4.4, Bash has begun deprecating older compatibility levels. Eventually, the options will be removed in favor of BASH_COMPAT. Bash-5.0 is the final version for which there will be an individual shopt option for the previous version. Users should use BASH_COMPAT on bash-5.0 and later versions. The following table describes the behavior changes controlled by each compatibility level setting. The compatNN tag is used as shorthand for setting the compatibility level to NN using one of the following mechanisms. For versions prior to bash-5.0, the compatibility level may be set using the corresponding compatNN shopt option. For bash-4.3 and later versions, the BASH_COMPAT variable is preferred, and it is required for bash-5.1 and later versions. compat31 quoting the rhs of the [[ command's regexp matching operator (=~) has no special effect compat32 interrupting a command list such as "a ; b ; c" causes the execution of the next command in the list (in bash-4.0 and later versions, the shell acts as if it received the interrupt, so interrupting one command in a list aborts the execution of the entire list) compat40 the < and > operators to the [[ command do not consider the current locale when comparing strings; they use ASCII ordering. Bash versions prior to bash-4.1 use ASCII collation and strcmp(3); bash-4.1 and later use the current locale's collation sequence and strcoll(3). compat41 in posix mode, time may be followed by options and still be recognized as a reserved word (this is POSIX interpretation 267) in posix mode, the parser requires that an even number of single quotes occur in the word portion of a double-quoted parameter expansion and treats them specially, so that characters within the single quotes are considered quoted (this is POSIX interpretation 221) compat42 the replacement string in double-quoted pattern substitution does not undergo quote removal, as it does in versions after bash-4.2 in posix mode, single quotes are considered special when expanding the word portion of a double-quoted parameter expansion and can be used to quote a closing brace or other special character (this is part of POSIX interpretation 221); in later versions, single quotes are not special within double-quoted word expansions compat43 the shell does not print a warning message if an attempt is made to use a quoted compound assignment as an argument to declare (e.g., declare -a foo='(1 2)'). Later versions warn that this usage is deprecated word expansion errors are considered non-fatal errors that cause the current command to fail, even in posix mode (the default behavior is to make them fatal errors that cause the shell to exit) when executing a shell function, the loop state (while/until/etc.) is not reset, so break or continue in that function will break or continue loops in the calling context. Bash-4.4 and later reset the loop state to prevent this compat44 the shell sets up the values used by BASH_ARGV and BASH_ARGC so they can expand to the shell's positional parameters even if extended debugging mode is not enabled a subshell inherits loops from its parent context, so break or continue will cause the subshell to exit. Bash-5.0 and later reset the loop state to prevent the exit variable assignments preceding builtins like export and readonly that set attributes continue to affect variables with the same name in the calling environment even if the shell is not in posix mode compat50 Bash-5.1 changed the way $RANDOM is generated to introduce slightly more randomness. If the shell compatibility level is set to 50 or lower, it reverts to the method from bash-5.0 and previous versions, so seeding the random number generator by assigning a value to RANDOM will produce the same sequence as in bash-5.0 If the command hash table is empty, bash versions prior to bash-5.1 printed an informational message to that effect, even when producing output that can be reused as input. Bash-5.1 suppresses that message when the -l option is supplied. compat51 The unset builtin treats attempts to unset array subscripts @ and * differently depending on whether the array is indexed or associative, and differently than in previous versions. RESTRICTED SHELL top If bash is started with the name rbash, or the -r option is supplied at invocation, the shell becomes restricted. A restricted shell is used to set up an environment more controlled than the standard shell. It behaves identically to bash with the exception that the following are disallowed or not performed: changing directories with cd setting or unsetting the values of SHELL, PATH, HISTFILE, ENV, or BASH_ENV specifying command names containing / specifying a filename containing a / as an argument to the . builtin command specifying a filename containing a slash as an argument to the history builtin command specifying a filename containing a slash as an argument to the -p option to the hash builtin command importing function definitions from the shell environment at startup parsing the value of SHELLOPTS from the shell environment at startup redirecting output using the >, >|, <>, >&, &>, and >> redirection operators using the exec builtin command to replace the shell with another command adding or deleting builtin commands with the -f and -d options to the enable builtin command using the enable builtin command to enable disabled shell builtins specifying the -p option to the command builtin command turning off restricted mode with set +r or shopt -u restricted_shell. These restrictions are enforced after any startup files are read. When a command that is found to be a shell script is executed (see COMMAND EXECUTION above), rbash turns off any restrictions in the shell spawned to execute the script. SEE ALSO top Bash Reference Manual, Brian Fox and Chet Ramey The Gnu Readline Library, Brian Fox and Chet Ramey The Gnu History Library, Brian Fox and Chet Ramey Portable Operating System Interface (POSIX) Part 2: Shell and Utilities, IEEE -- http://pubs.opengroup.org/onlinepubs/9699919799/ http://tiswww.case.edu/~chet/bash/POSIX -- a description of posix mode sh(1), ksh(1), csh(1) emacs(1), vi(1) readline(3) FILES top /bin/bash The bash executable /etc/profile The systemwide initialization file, executed for login shells ~/.bash_profile The personal initialization file, executed for login shells ~/.bashrc The individual per-interactive-shell startup file ~/.bash_logout The individual login shell cleanup file, executed when a login shell exits ~/.bash_history The default value of HISTFILE, the file in which bash saves the command history ~/.inputrc Individual readline initialization file AUTHORS top Brian Fox, Free Software Foundation bfox@gnu.org Chet Ramey, Case Western Reserve University chet.ramey@case.edu BUG REPORTS top If you find a bug in bash, you should report it. But first, you should make sure that it really is a bug, and that it appears in the latest version of bash. The latest version is always available from ftp://ftp.gnu.org/pub/gnu/bash/ and http://git.savannah.gnu.org/cgit/bash.git/snapshot/bash- master.tar.gz. Once you have determined that a bug actually exists, use the bashbug command to submit a bug report. If you have a fix, you are encouraged to mail that as well! Suggestions and `philosophical' bug reports may be mailed to bug-bash@gnu.org or posted to the Usenet newsgroup gnu.bash.bug. ALL bug reports should include: The version number of bash The hardware and operating system The compiler used to compile A description of the bug behaviour A short script or `recipe' which exercises the bug bashbug inserts the first three items automatically into the template it provides for filing a bug report. Comments and bug reports concerning this manual page should be directed to chet.ramey@case.edu. BUGS top It's too big and too slow. There are some subtle differences between bash and traditional versions of sh, mostly because of the POSIX specification. Aliases are confusing in some uses. Shell builtin commands and functions are not stoppable/restartable. Compound commands and command sequences of the form `a ; b ; c' are not handled gracefully when process suspension is attempted. When a process is stopped, the shell immediately executes the next command in the sequence. It suffices to place the sequence of commands between parentheses to force it into a subshell, which may be stopped as a unit. Array variables may not (yet) be exported. There may be only one active coprocess at a time. COLOPHON top This page is part of the bash (Bourne again shell) project. Information about the project can be found at http://www.gnu.org/software/bash/. If you have a bug report for this manual page, see http://www.gnu.org/software/bash/. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/bash.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-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 Bash 5.2 2022 September 19 BASH(1) Pages that refer to this page: getopt(1), intro(1), kill(1), pmdabash(1), pv(1), quilt(1), systemctl(1), systemd-notify(1), systemd-run(1), time(1), setpgid(2), getopt(3), history(3), readline(3), strcmp(3), termios(3), ulimit(3), core(5), credentials(7), environ(7), suffixes(7), time_namespaces(7), cupsenable(8), dpkg-fsys-usrunmess(8), wg(8), wg-quick(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. 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. Task: Convert *.au files to *.wav files using `sox' Bash Command:<START>find -type f -name '*.au' | awk '{printf "sox %s %s\n",$0,$0".wav" }' | bash<END>
Convert Unix `cal` output to latex table code.
cal -h 02 2012| cut -c4-17 | sed -r 's/(..)\s/\0\t\&/g' | sed 's/$/\t\\\\/' | head -n-1 | tail -n +2
['head', 'tail', 'sed', 'cut', 'cal']
Output a Bash command to accomplish the following task. Task: Convert Unix `cal` output to latex table code. Bash Command:<START>cal -h 02 2012| cut -c4-17 | sed -r 's/(..)\s/\0\t\&/g' | sed 's/$/\t\\\\/' | head -n-1 | tail -n +2<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # 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 # 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 # cut\n\n> Cut out fields from `stdin` or files.\n> More information: <https://www.gnu.org/software/coreutils/cut>.\n\n- Print a specific character/field range of each line:\n\n`{{command}} | cut --{{characters|fields}}={{1|1,10|1-10|1-|-10}}`\n\n- Print a field range of each line with a specific delimiter:\n\n`{{command}} | cut --delimiter="{{,}}" --fields={{1}}`\n\n- Print a character range of each line of the specific file:\n\n`cut --characters={{1}} {{path/to/file}}`\n # cal\n\n> Display a calendar with the current day highlighted.\n> More information: <https://manned.org/cal>.\n\n- Display a calendar for the current month:\n\n`cal`\n\n- Display [3] months spanning the date:\n\n`cal -3`\n\n- Display the whole calendar for the current [y]ear:\n\n`cal --year`\n\n- Display the next twelve months:\n\n`cal --twelve`\n\n- Use Monday as the first day of the week:\n\n`cal --monday`\n\n- Display a calendar for a specific year (4 digits):\n\n`cal {{year}}`\n\n- Display a calendar for a specific month and year:\n\n`cal {{month}} {{year}}`\n Task: Convert Unix `cal` output to latex table code. Bash Command:<START>cal -h 02 2012| cut -c4-17 | sed -r 's/(..)\s/\0\t\&/g' | sed 's/$/\t\\\\/' | head -n-1 | tail -n +2<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. 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. 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. cut(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cut(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CUT(1) User Commands CUT(1) NAME top cut - remove sections from each line of files SYNOPSIS top cut OPTION... [FILE]... DESCRIPTION top Print selected parts of lines from each FILE to standard output. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -b, --bytes=LIST select only these bytes -c, --characters=LIST select only these characters -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter -f, --fields=LIST select only these fields; also print any line that contains no delimiter character, unless the -s option is specified -n (ignored) --complement complement the set of selected bytes, characters or fields -s, --only-delimited do not print lines not containing delimiters --output-delimiter=STRING use STRING as the output delimiter the default is to use the input delimiter -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit Use one, and only one of -b, -c or -f. Each LIST is made up of one range, or many ranges separated by commas. Selected input is written in the same order that it is read, and is written exactly once. Each range is one of: N N'th byte, character or field, counted from 1 N- from N'th byte, character or field, to end of line N-M from N'th to M'th (included) byte, character or field -M from first to M'th (included) byte, character or field AUTHOR top Written by David M. Ihnat, 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 Full documentation <https://www.gnu.org/software/coreutils/cut> or available locally via: info '(coreutils) cut 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 CUT(1) Pages that refer to this page: man-pages(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. cal(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cal(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | PARAMETERS | NOTES | COLORS | HISTORY | BUGS | SEE ALSO | REPORTING BUGS | AVAILABILITY CAL(1) User Commands CAL(1) NAME top cal - display a calendar SYNOPSIS top cal [options] [[[day] month] year] cal [options] [timestamp|monthname] DESCRIPTION top cal displays a simple calendar. If no arguments are specified, the current month is displayed. The month may be specified as a number (1-12), as a month name or as an abbreviated month name according to the current locales. Two different calendar systems are used, Gregorian and Julian. These are nearly identical systems with Gregorian making a small adjustment to the frequency of leap years; this facilitates improved synchronization with solar events like the equinoxes. The Gregorian calendar reform was introduced in 1582, but its adoption continued up to 1923. By default cal uses the adoption date of 3 Sept 1752. From that date forward the Gregorian calendar is displayed; previous dates use the Julian calendar system. 11 days were removed at the time of adoption to bring the calendar in sync with solar events. So Sept 1752 has a mix of Julian and Gregorian dates by which the 2nd is followed by the 14th (the 3rd through the 13th are absent). Optionally, either the proleptic Gregorian calendar or the Julian calendar may be used exclusively. See --reform below. OPTIONS top -1, --one Display single month output. (This is the default.) -3, --three Display three months spanning the date. -n , --months number Display number of months, starting from the month containing the date. -S, --span Display months spanning the date. -s, --sunday Display Sunday as the first day of the week. -m, --monday Display Monday as the first day of the week. -v, --vertical Display using a vertical layout (aka ncal(1) mode). --iso Display the proleptic Gregorian calendar exclusively. This option does not affect week numbers and the first day of the week. See --reform below. -j, --julian Use day-of-year numbering for all calendars. These are also called ordinal days. Ordinal days range from 1 to 366. This option does not switch from the Gregorian to the Julian calendar system, that is controlled by the --reform option. Sometimes Gregorian calendars using ordinal dates are referred to as Julian calendars. This can be confusing due to the many date related conventions that use Julian in their name: (ordinal) julian date, julian (calendar) date, (astronomical) julian date, (modified) julian date, and more. This option is named julian, because ordinal days are identified as julian by the POSIX standard. However, be aware that cal also uses the Julian calendar system. See DESCRIPTION above. --reform val This option sets the adoption date of the Gregorian calendar reform. Calendar dates previous to reform use the Julian calendar system. Calendar dates after reform use the Gregorian calendar system. The argument val can be: 1752 - sets 3 September 1752 as the reform date (default). This is when the Gregorian calendar reform was adopted by the British Empire. gregorian - display Gregorian calendars exclusively. This special placeholder sets the reform date below the smallest year that cal can use; meaning all calendar output uses the Gregorian calendar system. This is called the proleptic Gregorian calendar, because dates prior to the calendar systems creation use extrapolated values. iso - alias of gregorian. The ISO 8601 standard for the representation of dates and times in information interchange requires using the proleptic Gregorian calendar. julian - display Julian calendars exclusively. This special placeholder sets the reform date above the largest year that cal can use; meaning all calendar output uses the Julian calendar system. See DESCRIPTION above. -y, --year Display a calendar for the whole year. -Y, --twelve Display a calendar for the next twelve months. -w, --week[=number] Display week numbers in the calendar (US or ISO-8601). See the NOTES section for more details. --color[=when] Colorize the output. The optional argument when can be auto, never or always. If the when argument is omitted, it defaults to auto. The colors can be disabled; for the current built-in default see the --help output. See also the COLORS section. -c, --columns=columns Number of columns to use. auto uses as many as fit the terminal. -h, --help Display help text and exit. -V, --version Print version and exit. PARAMETERS top Single digits-only parameter (e.g., 'cal 2020') Specifies the year to be displayed; note the year must be fully specified: cal 89 will not display a calendar for 1989. Single string parameter (e.g., 'cal tomorrow' or 'cal August') Specifies timestamp or a month name (or abbreviated name) according to the current locales. The special placeholders are accepted when parsing timestamp, "now" may be used to refer to the current time, "today", "yesterday", "tomorrow" refer to of the current day, the day before or the next day, respectively. The relative date specifications are also accepted, in this case "+" is evaluated to the current time plus the specified time span. Correspondingly, a time span that is prefixed with "-" is evaluated to the current time minus the specified time span, for example '+2days'. Instead of prefixing the time span with "+" or "-", it may also be suffixed with a space and the word "left" or "ago" (for example '1 week ago'). Two parameters (e.g., 'cal 11 2020') Denote the month (1 - 12) and year. Three parameters (e.g., 'cal 25 11 2020') Denote the day (1-31), month and year, and the day will be highlighted if the calendar is displayed on a terminal. If no parameters are specified, the current months calendar is displayed. NOTES top A year starts on January 1. The first day of the week is determined by the locale or the --sunday and --monday options. The week numbering depends on the choice of the first day of the week. If it is Sunday then the customary North American numbering is used, where 1 January is in week number 1. If it is Monday (-m) then the ISO 8601 standard week numbering is used, where the first Thursday is in week number 1. COLORS top The output colorization is implemented by terminal-colors.d(5) functionality. Implicit coloring can be disabled by an empty file /etc/terminal-colors.d/cal.disable for the cal command or for all tools by /etc/terminal-colors.d/disable The user-specific $XDG_CONFIG_HOME/terminal-colors.d or $HOME/.config/terminal-colors.d overrides the global setting. Note that the output colorization may be enabled by default, and in this case terminal-colors.d directories do not have to exist yet. The logical color names supported by cal are: today The current day. weeknumber The number of the week. header The header of a month. workday Days that fall within the work-week. weekend Days that fall outside the work-week. For example: echo -e 'weekend 35\ntoday 1;41\nheader yellow' > $HOME/.config/terminal-colors.d/cal.scheme HISTORY top A cal command appeared in Version 6 AT&T UNIX. BUGS top The default cal output uses 3 September 1752 as the Gregorian calendar reform date. The historical reform dates for the other locales, including its introduction in October 1582, are not implemented. Alternative calendars, such as the Umm al-Qura, the Solar Hijri, the Geez, or the lunisolar Hindu, are not supported. SEE ALSO top terminal-colors.d(5) REPORTING BUGS top For bug reports, use the issue tracker at https://github.com/util-linux/util-linux/issues. AVAILABILITY top The cal 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 CAL(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: Convert Unix `cal` output to latex table code. Bash Command:<START>cal -h 02 2012| cut -c4-17 | sed -r 's/(..)\s/\0\t\&/g' | sed 's/$/\t\\\\/' | head -n-1 | tail -n +2<END>
Convert Unix `cal` output to latex table code.
cal | sed '1d;2{h;s/./ /g;x};/^\s*$/b;G;s/\n/ /;s/^...\(.\{15\}\).*/\1/;s/.../ &\t\&/g;s/\&$/\\\\/'
['sed', 'cal']
Output a Bash command to accomplish the following task. Task: Convert Unix `cal` output to latex table code. Bash Command:<START>cal | sed '1d;2{h;s/./ /g;x};/^\s*$/b;G;s/\n/ /;s/^...\(.\{15\}\).*/\1/;s/.../ &\t\&/g;s/\&$/\\\\/'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # cal\n\n> Display a calendar with the current day highlighted.\n> More information: <https://manned.org/cal>.\n\n- Display a calendar for the current month:\n\n`cal`\n\n- Display [3] months spanning the date:\n\n`cal -3`\n\n- Display the whole calendar for the current [y]ear:\n\n`cal --year`\n\n- Display the next twelve months:\n\n`cal --twelve`\n\n- Use Monday as the first day of the week:\n\n`cal --monday`\n\n- Display a calendar for a specific year (4 digits):\n\n`cal {{year}}`\n\n- Display a calendar for a specific month and year:\n\n`cal {{month}} {{year}}`\n Task: Convert Unix `cal` output to latex table code. Bash Command:<START>cal | sed '1d;2{h;s/./ /g;x};/^\s*$/b;G;s/\n/ /;s/^...\(.\{15\}\).*/\1/;s/.../ &\t\&/g;s/\&$/\\\\/'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. cal(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cal(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | PARAMETERS | NOTES | COLORS | HISTORY | BUGS | SEE ALSO | REPORTING BUGS | AVAILABILITY CAL(1) User Commands CAL(1) NAME top cal - display a calendar SYNOPSIS top cal [options] [[[day] month] year] cal [options] [timestamp|monthname] DESCRIPTION top cal displays a simple calendar. If no arguments are specified, the current month is displayed. The month may be specified as a number (1-12), as a month name or as an abbreviated month name according to the current locales. Two different calendar systems are used, Gregorian and Julian. These are nearly identical systems with Gregorian making a small adjustment to the frequency of leap years; this facilitates improved synchronization with solar events like the equinoxes. The Gregorian calendar reform was introduced in 1582, but its adoption continued up to 1923. By default cal uses the adoption date of 3 Sept 1752. From that date forward the Gregorian calendar is displayed; previous dates use the Julian calendar system. 11 days were removed at the time of adoption to bring the calendar in sync with solar events. So Sept 1752 has a mix of Julian and Gregorian dates by which the 2nd is followed by the 14th (the 3rd through the 13th are absent). Optionally, either the proleptic Gregorian calendar or the Julian calendar may be used exclusively. See --reform below. OPTIONS top -1, --one Display single month output. (This is the default.) -3, --three Display three months spanning the date. -n , --months number Display number of months, starting from the month containing the date. -S, --span Display months spanning the date. -s, --sunday Display Sunday as the first day of the week. -m, --monday Display Monday as the first day of the week. -v, --vertical Display using a vertical layout (aka ncal(1) mode). --iso Display the proleptic Gregorian calendar exclusively. This option does not affect week numbers and the first day of the week. See --reform below. -j, --julian Use day-of-year numbering for all calendars. These are also called ordinal days. Ordinal days range from 1 to 366. This option does not switch from the Gregorian to the Julian calendar system, that is controlled by the --reform option. Sometimes Gregorian calendars using ordinal dates are referred to as Julian calendars. This can be confusing due to the many date related conventions that use Julian in their name: (ordinal) julian date, julian (calendar) date, (astronomical) julian date, (modified) julian date, and more. This option is named julian, because ordinal days are identified as julian by the POSIX standard. However, be aware that cal also uses the Julian calendar system. See DESCRIPTION above. --reform val This option sets the adoption date of the Gregorian calendar reform. Calendar dates previous to reform use the Julian calendar system. Calendar dates after reform use the Gregorian calendar system. The argument val can be: 1752 - sets 3 September 1752 as the reform date (default). This is when the Gregorian calendar reform was adopted by the British Empire. gregorian - display Gregorian calendars exclusively. This special placeholder sets the reform date below the smallest year that cal can use; meaning all calendar output uses the Gregorian calendar system. This is called the proleptic Gregorian calendar, because dates prior to the calendar systems creation use extrapolated values. iso - alias of gregorian. The ISO 8601 standard for the representation of dates and times in information interchange requires using the proleptic Gregorian calendar. julian - display Julian calendars exclusively. This special placeholder sets the reform date above the largest year that cal can use; meaning all calendar output uses the Julian calendar system. See DESCRIPTION above. -y, --year Display a calendar for the whole year. -Y, --twelve Display a calendar for the next twelve months. -w, --week[=number] Display week numbers in the calendar (US or ISO-8601). See the NOTES section for more details. --color[=when] Colorize the output. The optional argument when can be auto, never or always. If the when argument is omitted, it defaults to auto. The colors can be disabled; for the current built-in default see the --help output. See also the COLORS section. -c, --columns=columns Number of columns to use. auto uses as many as fit the terminal. -h, --help Display help text and exit. -V, --version Print version and exit. PARAMETERS top Single digits-only parameter (e.g., 'cal 2020') Specifies the year to be displayed; note the year must be fully specified: cal 89 will not display a calendar for 1989. Single string parameter (e.g., 'cal tomorrow' or 'cal August') Specifies timestamp or a month name (or abbreviated name) according to the current locales. The special placeholders are accepted when parsing timestamp, "now" may be used to refer to the current time, "today", "yesterday", "tomorrow" refer to of the current day, the day before or the next day, respectively. The relative date specifications are also accepted, in this case "+" is evaluated to the current time plus the specified time span. Correspondingly, a time span that is prefixed with "-" is evaluated to the current time minus the specified time span, for example '+2days'. Instead of prefixing the time span with "+" or "-", it may also be suffixed with a space and the word "left" or "ago" (for example '1 week ago'). Two parameters (e.g., 'cal 11 2020') Denote the month (1 - 12) and year. Three parameters (e.g., 'cal 25 11 2020') Denote the day (1-31), month and year, and the day will be highlighted if the calendar is displayed on a terminal. If no parameters are specified, the current months calendar is displayed. NOTES top A year starts on January 1. The first day of the week is determined by the locale or the --sunday and --monday options. The week numbering depends on the choice of the first day of the week. If it is Sunday then the customary North American numbering is used, where 1 January is in week number 1. If it is Monday (-m) then the ISO 8601 standard week numbering is used, where the first Thursday is in week number 1. COLORS top The output colorization is implemented by terminal-colors.d(5) functionality. Implicit coloring can be disabled by an empty file /etc/terminal-colors.d/cal.disable for the cal command or for all tools by /etc/terminal-colors.d/disable The user-specific $XDG_CONFIG_HOME/terminal-colors.d or $HOME/.config/terminal-colors.d overrides the global setting. Note that the output colorization may be enabled by default, and in this case terminal-colors.d directories do not have to exist yet. The logical color names supported by cal are: today The current day. weeknumber The number of the week. header The header of a month. workday Days that fall within the work-week. weekend Days that fall outside the work-week. For example: echo -e 'weekend 35\ntoday 1;41\nheader yellow' > $HOME/.config/terminal-colors.d/cal.scheme HISTORY top A cal command appeared in Version 6 AT&T UNIX. BUGS top The default cal output uses 3 September 1752 as the Gregorian calendar reform date. The historical reform dates for the other locales, including its introduction in October 1582, are not implemented. Alternative calendars, such as the Umm al-Qura, the Solar Hijri, the Geez, or the lunisolar Hindu, are not supported. SEE ALSO top terminal-colors.d(5) REPORTING BUGS top For bug reports, use the issue tracker at https://github.com/util-linux/util-linux/issues. AVAILABILITY top The cal 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 CAL(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: Convert Unix `cal` output to latex table code. Bash Command:<START>cal | sed '1d;2{h;s/./ /g;x};/^\s*$/b;G;s/\n/ /;s/^...\(.\{15\}\).*/\1/;s/.../ &\t\&/g;s/\&$/\\\\/'<END>
Convert all characters in "$a" to lower case and save to variable "b"
b=`echo "$a" | sed 's/./\L&/g'`
['sed', 'echo']
Output a Bash command to accomplish the following task. Task: Convert all characters in "$a" to lower case and save to variable "b" Bash Command:<START>b=`echo "$a" | sed 's/./\L&/g'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # 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: Convert all characters in "$a" to lower case and save to variable "b" Bash Command:<START>b=`echo "$a" | sed 's/./\L&/g'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. 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: Convert all characters in "$a" to lower case and save to variable "b" Bash Command:<START>b=`echo "$a" | sed 's/./\L&/g'`<END>
Convert all characters in "$a" to upper case and save to variable "b"
b=`echo "$a" | sed 's/./\U&/g'`
['sed', 'echo']
Output a Bash command to accomplish the following task. Task: Convert all characters in "$a" to upper case and save to variable "b" Bash Command:<START>b=`echo "$a" | sed 's/./\U&/g'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # 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: Convert all characters in "$a" to upper case and save to variable "b" Bash Command:<START>b=`echo "$a" | sed 's/./\U&/g'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. 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: Convert all characters in "$a" to upper case and save to variable "b" Bash Command:<START>b=`echo "$a" | sed 's/./\U&/g'`<END>
Convert all characters in standard input to lower case
sed 's/.*/\L&/'
['sed']
Output a Bash command to accomplish the following task. Task: Convert all characters in standard input to lower case Bash Command:<START>sed 's/.*/\L&/'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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: Convert all characters in standard input to lower case Bash Command:<START>sed 's/.*/\L&/'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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: Convert all characters in standard input to lower case Bash Command:<START>sed 's/.*/\L&/'<END>
Convert relative path "/x/y/../../a/b/z/../c/d" into absolute path with resolved symbolic links
readlink -f /x/y/../../a/b/z/../c/d
['readlink']
Output a Bash command to accomplish the following task. Task: Convert relative path "/x/y/../../a/b/z/../c/d" into absolute path with resolved symbolic links Bash Command:<START>readlink -f /x/y/../../a/b/z/../c/d<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # readlink\n\n> Follow symlinks and get symlink information.\n> More information: <https://www.gnu.org/software/coreutils/readlink>.\n\n- Get the actual file to which the symlink points:\n\n`readlink {{path/to/file}}`\n\n- Get the absolute path to a file:\n\n`readlink -f {{path/to/file}}`\n Task: Convert relative path "/x/y/../../a/b/z/../c/d" into absolute path with resolved symbolic links Bash Command:<START>readlink -f /x/y/../../a/b/z/../c/d<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: readlink(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training readlink(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON READLINK(1) User Commands READLINK(1) NAME top readlink - print resolved symbolic links or canonical file names SYNOPSIS top readlink [OPTION]... FILE... DESCRIPTION top Note realpath(1) is the preferred command to use for canonicalization functionality. Print value of a symbolic link or canonical file name -f, --canonicalize canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist -e, --canonicalize-existing canonicalize by following every symlink in every component of the given name recursively, all components must exist -m, --canonicalize-missing canonicalize by following every symlink in every component of the given name recursively, without requirements on components existence -n, --no-newline do not output the trailing delimiter -q, --quiet -s, --silent suppress most error messages (on by default) -v, --verbose report error messages -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit AUTHOR top Written by Dmitry V. Levin. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top readlink(2), realpath(1), realpath(3) Full documentation <https://www.gnu.org/software/coreutils/readlink> or available locally via: info '(coreutils) readlink invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 READLINK(1) Pages that refer to this page: basename(1), dirname(1), dpkg-realpath(1), realpath(1), unshare(1), mount(2), readlink(2), unshare(2), namespaces(7), mount(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Convert relative path "/x/y/../../a/b/z/../c/d" into absolute path with resolved symbolic links Bash Command:<START>readlink -f /x/y/../../a/b/z/../c/d<END>
Convert relative symbolic link "$link" to absolute symbolic link
ln -sf "$(readlink -f "$link")" "$link"
['readlink', 'ln']
Output a Bash command to accomplish the following task. Task: Convert relative symbolic link "$link" to absolute symbolic link Bash Command:<START>ln -sf "$(readlink -f "$link")" "$link"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # readlink\n\n> Follow symlinks and get symlink information.\n> More information: <https://www.gnu.org/software/coreutils/readlink>.\n\n- Get the actual file to which the symlink points:\n\n`readlink {{path/to/file}}`\n\n- Get the absolute path to a file:\n\n`readlink -f {{path/to/file}}`\n # ln\n\n> Creates links to files and directories.\n> More information: <https://www.gnu.org/software/coreutils/ln>.\n\n- Create a symbolic link to a file or directory:\n\n`ln -s {{/path/to/file_or_directory}} {{path/to/symlink}}`\n\n- Overwrite an existing symbolic link to point to a different file:\n\n`ln -sf {{/path/to/new_file}} {{path/to/symlink}}`\n\n- Create a hard link to a file:\n\n`ln {{/path/to/file}} {{path/to/hardlink}}`\n Task: Convert relative symbolic link "$link" to absolute symbolic link Bash Command:<START>ln -sf "$(readlink -f "$link")" "$link"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: readlink(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training readlink(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON READLINK(1) User Commands READLINK(1) NAME top readlink - print resolved symbolic links or canonical file names SYNOPSIS top readlink [OPTION]... FILE... DESCRIPTION top Note realpath(1) is the preferred command to use for canonicalization functionality. Print value of a symbolic link or canonical file name -f, --canonicalize canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist -e, --canonicalize-existing canonicalize by following every symlink in every component of the given name recursively, all components must exist -m, --canonicalize-missing canonicalize by following every symlink in every component of the given name recursively, without requirements on components existence -n, --no-newline do not output the trailing delimiter -q, --quiet -s, --silent suppress most error messages (on by default) -v, --verbose report error messages -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit AUTHOR top Written by Dmitry V. Levin. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top readlink(2), realpath(1), realpath(3) Full documentation <https://www.gnu.org/software/coreutils/readlink> or available locally via: info '(coreutils) readlink invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 READLINK(1) Pages that refer to this page: basename(1), dirname(1), dpkg-realpath(1), realpath(1), unshare(1), mount(2), readlink(2), unshare(2), namespaces(7), mount(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. ln(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training ln(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON LN(1) User Commands LN(1) NAME top ln - make links between files SYNOPSIS top ln [OPTION]... [-T] TARGET LINK_NAME ln [OPTION]... TARGET ln [OPTION]... TARGET... DIRECTORY ln [OPTION]... -t DIRECTORY TARGET... DESCRIPTION top In the 1st form, create a link to TARGET with the name LINK_NAME. In the 2nd form, create a link to TARGET in the current directory. In the 3rd and 4th forms, create links to each TARGET in DIRECTORY. Create hard links by default, symbolic links with --symbolic. By default, each destination (name of new link) should not already exist. When creating hard links, each TARGET must exist. Symbolic links can hold arbitrary text; if later resolved, a relative link is interpreted in relation to its parent directory. Mandatory arguments to long options are mandatory for short options too. --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument -d, -F, --directory allow the superuser to attempt to hard link directories (note: will probably fail due to system restrictions, even for the superuser) -f, --force remove existing destination files -i, --interactive prompt whether to remove destinations -L, --logical dereference TARGETs that are symbolic links -n, --no-dereference treat LINK_NAME as a normal file if it is a symbolic link to a directory -P, --physical make hard links directly to symbolic links -r, --relative with -s, create links relative to link location -s, --symbolic make symbolic links instead of hard links -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY specify the DIRECTORY in which to create the links -T, --no-target-directory treat LINK_NAME as a normal file always -v, --verbose print name of each linked file --help display this help and exit --version output version information and exit The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups Using -s ignores -L and -P. Otherwise, the last option specified controls behavior when a TARGET is a symbolic link, defaulting to -P. AUTHOR top Written by Mike Parker 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 link(2), symlink(2) Full documentation <https://www.gnu.org/software/coreutils/ln> or available locally via: info '(coreutils) ln 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 LN(1) Pages that refer to this page: dh_link(1), pmlogmv(1), update-alternatives(1), link(2), symlink(2), hier(7), symlink(7), sln(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: Convert relative symbolic link "$link" to absolute symbolic link Bash Command:<START>ln -sf "$(readlink -f "$link")" "$link"<END>
Convert standard input into a dump of octal bytes without the first 8 bytes of address and count the unique results
od | cut -b 8- | xargs -n 1 | sort | uniq | wc -l
['wc', 'xargs', 'cut', 'sort', 'uniq', 'od']
Output a Bash command to accomplish the following task. Task: Convert standard input into a dump of octal bytes without the first 8 bytes of address and count the unique results Bash Command:<START>od | cut -b 8- | xargs -n 1 | sort | uniq | wc -l<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # wc\n\n> Count lines, words, and bytes.\n> More information: <https://www.gnu.org/software/coreutils/wc>.\n\n- Count all lines in a file:\n\n`wc --lines {{path/to/file}}`\n\n- Count all words in a file:\n\n`wc --words {{path/to/file}}`\n\n- Count all bytes in a file:\n\n`wc --bytes {{path/to/file}}`\n\n- Count all characters in a file (taking multi-byte characters into account):\n\n`wc --chars {{path/to/file}}`\n\n- Count all lines, words and bytes from `stdin`:\n\n`{{find .}} | wc`\n\n- Count the length of the longest line in number of characters:\n\n`wc --max-line-length {{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 # cut\n\n> Cut out fields from `stdin` or files.\n> More information: <https://www.gnu.org/software/coreutils/cut>.\n\n- Print a specific character/field range of each line:\n\n`{{command}} | cut --{{characters|fields}}={{1|1,10|1-10|1-|-10}}`\n\n- Print a field range of each line with a specific delimiter:\n\n`{{command}} | cut --delimiter="{{,}}" --fields={{1}}`\n\n- Print a character range of each line of the specific file:\n\n`cut --characters={{1}} {{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 # 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 # od\n\n> Display file contents in octal, decimal or hexadecimal format.\n> Optionally display the byte offsets and/or printable representation for each line.\n> More information: <https://www.gnu.org/software/coreutils/od>.\n\n- Display file using default settings: octal format, 8 bytes per line, byte offsets in octal, and duplicate lines replaced with `*`:\n\n`od {{path/to/file}}`\n\n- Display file in verbose mode, i.e. without replacing duplicate lines with `*`:\n\n`od -v {{path/to/file}}`\n\n- Display file in hexadecimal format (2-byte units), with byte offsets in decimal format:\n\n`od --format={{x}} --address-radix={{d}} -v {{path/to/file}}`\n\n- Display file in hexadecimal format (1-byte units), and 4 bytes per line:\n\n`od --format={{x1}} --width={{4}} -v {{path/to/file}}`\n\n- Display file in hexadecimal format along with its character representation, and do not print byte offsets:\n\n`od --format={{xz}} --address-radix={{n}} -v {{path/to/file}}`\n\n- Read only 100 bytes of a file starting from the 500th byte:\n\n`od --read-bytes {{100}} --skip-bytes={{500}} -v {{path/to/file}}`\n Task: Convert standard input into a dump of octal bytes without the first 8 bytes of address and count the unique results Bash Command:<START>od | cut -b 8- | xargs -n 1 | sort | uniq | wc -l<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: wc(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training wc(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON WC(1) User Commands WC(1) NAME top wc - print newline, word, and byte counts for each file SYNOPSIS top wc [OPTION]... [FILE]... wc [OPTION]... --files0-from=F DESCRIPTION top Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified. A word is a non-zero-length sequence of printable characters delimited by white space. With no FILE, or when FILE is -, read standard input. The options below may be used to select which counts are printed, always in the following order: newline, word, character, byte, maximum line length. -c, --bytes print the byte counts -m, --chars print the character counts -l, --lines print the newline counts --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 -L, --max-line-length print the maximum display width -w, --words print the word counts --total=WHEN when to print a line with total counts; WHEN can be: auto, always, only, never --help display this help and exit --version output version information and exit AUTHOR top Written by Paul Rubin 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/wc> or available locally via: info '(coreutils) wc 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 WC(1) Pages that refer to this page: 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. 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. cut(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cut(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CUT(1) User Commands CUT(1) NAME top cut - remove sections from each line of files SYNOPSIS top cut OPTION... [FILE]... DESCRIPTION top Print selected parts of lines from each FILE to standard output. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -b, --bytes=LIST select only these bytes -c, --characters=LIST select only these characters -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter -f, --fields=LIST select only these fields; also print any line that contains no delimiter character, unless the -s option is specified -n (ignored) --complement complement the set of selected bytes, characters or fields -s, --only-delimited do not print lines not containing delimiters --output-delimiter=STRING use STRING as the output delimiter the default is to use the input delimiter -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit Use one, and only one of -b, -c or -f. Each LIST is made up of one range, or many ranges separated by commas. Selected input is written in the same order that it is read, and is written exactly once. Each range is one of: N N'th byte, character or field, counted from 1 N- from N'th byte, character or field, to end of line N-M from N'th to M'th (included) byte, character or field -M from first to M'th (included) byte, character or field AUTHOR top Written by David M. Ihnat, 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 Full documentation <https://www.gnu.org/software/coreutils/cut> or available locally via: info '(coreutils) cut 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 CUT(1) Pages that refer to this page: man-pages(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. 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. od(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training od(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON OD(1) User Commands OD(1) NAME top od - dump files in octal and other formats SYNOPSIS top od [OPTION]... [FILE]... od [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]] od --traditional [OPTION]... [FILE] [[+]OFFSET[.][b] [+][LABEL][.][b]] DESCRIPTION top Write an unambiguous representation, octal bytes by default, of FILE to standard output. With more than one FILE argument, concatenate them in the listed order to form the input. With no FILE, or when FILE is -, read standard input. If first and second call formats both apply, the second format is assumed if the last operand begins with + or (if there are 2 operands) a digit. An OFFSET operand means -j OFFSET. LABEL is the pseudo-address at first byte printed, incremented when dump is progressing. For OFFSET and LABEL, a 0x or 0X prefix indicates hexadecimal; suffixes may be . for octal and b for multiply by 512. Mandatory arguments to long options are mandatory for short options too. -A, --address-radix=RADIX output format for file offsets; RADIX is one of [doxn], for Decimal, Octal, Hex or None --endian={big|little} swap input bytes according the specified order -j, --skip-bytes=BYTES skip BYTES input bytes first -N, --read-bytes=BYTES limit dump to BYTES input bytes -S BYTES, --strings[=BYTES] show only NUL terminated strings of at least BYTES (3) printable characters -t, --format=TYPE select output format or formats -v, --output-duplicates do not use * to mark line suppression -w[BYTES], --width[=BYTES] output BYTES bytes per output line; 32 is implied when BYTES is not specified --traditional accept arguments in third form above --help display this help and exit --version output version information and exit Traditional format specifications may be intermixed; they accumulate: -a same as -t a, select named characters, ignoring high-order bit -b same as -t o1, select octal bytes -c same as -t c, select printable characters or backslash escapes -d same as -t u2, select unsigned decimal 2-byte units -f same as -t fF, select floats -i same as -t dI, select decimal ints -l same as -t dL, select decimal longs -o same as -t o2, select octal 2-byte units -s same as -t d2, select decimal 2-byte units -x same as -t x2, select hexadecimal 2-byte units TYPE is made up of one or more of these specifications: a named character, ignoring high-order bit c printable character or backslash escape d[SIZE] signed decimal, SIZE bytes per integer f[SIZE] floating point, SIZE bytes per float o[SIZE] octal, SIZE bytes per integer u[SIZE] unsigned decimal, SIZE bytes per integer x[SIZE] hexadecimal, SIZE bytes per integer SIZE is a number. For TYPE in [doux], SIZE may also be C for sizeof(char), S for sizeof(short), I for sizeof(int) or L for sizeof(long). If TYPE is f, SIZE may also be F for sizeof(float), D for sizeof(double) or L for sizeof(long double). Adding a z suffix to any type displays printable characters at the end of each output line. BYTES is hex with 0x or 0X prefix, and may have a multiplier suffix: b 512 KB 1000 K 1024 MB 1000*1000 M 1024*1024 and so on for G, T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. EXAMPLES top od -A x -t x1z -v Display hexdump format output od -A o -t oS -w16 The default output format used by od 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 Full documentation <https://www.gnu.org/software/coreutils/od> or available locally via: info '(coreutils) od 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 OD(1) Pages that refer to this page: scr_dump(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: Convert standard input into a dump of octal bytes without the first 8 bytes of address and count the unique results Bash Command:<START>od | cut -b 8- | xargs -n 1 | sort | uniq | wc -l<END>
Convert the content of variable 'CLEAN' to small letters
CLEAN=`echo -n $CLEAN | tr A-Z a-z`
['tr', 'echo']
Output a Bash command to accomplish the following task. Task: Convert the content of variable 'CLEAN' to small letters Bash Command:<START>CLEAN=`echo -n $CLEAN | tr A-Z a-z`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # tr\n\n> Translate characters: run replacements based on single characters and character sets.\n> More information: <https://www.gnu.org/software/coreutils/tr>.\n\n- Replace all occurrences of a character in a file, and print the result:\n\n`tr {{find_character}} {{replace_character}} < {{path/to/file}}`\n\n- Replace all occurrences of a character from another command's output:\n\n`echo {{text}} | tr {{find_character}} {{replace_character}}`\n\n- Map each character of the first set to the corresponding character of the second set:\n\n`tr '{{abcd}}' '{{jkmn}}' < {{path/to/file}}`\n\n- Delete all occurrences of the specified set of characters from the input:\n\n`tr -d '{{input_characters}}' < {{path/to/file}}`\n\n- Compress a series of identical characters to a single character:\n\n`tr -s '{{input_characters}}' < {{path/to/file}}`\n\n- Translate the contents of a file to upper-case:\n\n`tr "[:lower:]" "[:upper:]" < {{path/to/file}}`\n\n- Strip out non-printable characters from a file:\n\n`tr -cd "[:print:]" < {{path/to/file}}`\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: Convert the content of variable 'CLEAN' to small letters Bash Command:<START>CLEAN=`echo -n $CLEAN | tr A-Z a-z`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: tr(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tr(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | BUGS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TR(1) User Commands TR(1) NAME top tr - translate or delete characters SYNOPSIS top tr [OPTION]... STRING1 [STRING2] DESCRIPTION top Translate, squeeze, and/or delete characters from standard input, writing to standard output. STRING1 and STRING2 specify arrays of characters ARRAY1 and ARRAY2 that control the action. -c, -C, --complement use the complement of ARRAY1 -d, --delete delete characters in ARRAY1, do not translate -s, --squeeze-repeats replace each sequence of a repeated character that is listed in the last specified ARRAY, with a single occurrence of that character -t, --truncate-set1 first truncate ARRAY1 to length of ARRAY2 --help display this help and exit --version output version information and exit ARRAYs are specified as strings of characters. Most represent themselves. Interpreted sequences are: \NNN character with octal value NNN (1 to 3 octal digits) \\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab \v vertical tab CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in ARRAY2, copies of CHAR until length of ARRAY1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [:alnum:] all letters and digits [:alpha:] all letters [:blank:] all horizontal whitespace [:cntrl:] all control characters [:digit:] all digits [:graph:] all printable characters, not including space [:lower:] all lower case letters [:print:] all printable characters, including space [:punct:] all punctuation characters [:space:] all horizontal or vertical whitespace [:upper:] all upper case letters [:xdigit:] all hexadecimal digits [=CHAR=] all characters which are equivalent to CHAR Translation occurs if -d is not given and both STRING1 and STRING2 appear. -t is only significant when translating. ARRAY2 is extended to length of ARRAY1 by repeating its last character as necessary. Excess characters of ARRAY2 are ignored. Character classes expand in unspecified order; while translating, [:lower:] and [:upper:] may be used in pairs to specify case conversion. Squeezing occurs after translation or deletion. BUGS top Full support is available only for safe single-byte locales, in which every possible input byte represents a single character. The C locale is safe in GNU systems, so you can avoid this issue in the shell by running LC_ALL=C tr instead of plain tr. 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 Full documentation <https://www.gnu.org/software/coreutils/tr> or available locally via: info '(coreutils) tr 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 TR(1) Pages that refer to this page: sed(1), 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. 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: Convert the content of variable 'CLEAN' to small letters Bash Command:<START>CLEAN=`echo -n $CLEAN | tr A-Z a-z`<END>
Convert the contents of 'var1' variable to lowercase
var1=`echo $var1 | tr '[A-Z]' '[a-z]'`
['tr', 'echo']
Output a Bash command to accomplish the following task. Task: Convert the contents of 'var1' variable to lowercase Bash Command:<START>var1=`echo $var1 | tr '[A-Z]' '[a-z]'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # tr\n\n> Translate characters: run replacements based on single characters and character sets.\n> More information: <https://www.gnu.org/software/coreutils/tr>.\n\n- Replace all occurrences of a character in a file, and print the result:\n\n`tr {{find_character}} {{replace_character}} < {{path/to/file}}`\n\n- Replace all occurrences of a character from another command's output:\n\n`echo {{text}} | tr {{find_character}} {{replace_character}}`\n\n- Map each character of the first set to the corresponding character of the second set:\n\n`tr '{{abcd}}' '{{jkmn}}' < {{path/to/file}}`\n\n- Delete all occurrences of the specified set of characters from the input:\n\n`tr -d '{{input_characters}}' < {{path/to/file}}`\n\n- Compress a series of identical characters to a single character:\n\n`tr -s '{{input_characters}}' < {{path/to/file}}`\n\n- Translate the contents of a file to upper-case:\n\n`tr "[:lower:]" "[:upper:]" < {{path/to/file}}`\n\n- Strip out non-printable characters from a file:\n\n`tr -cd "[:print:]" < {{path/to/file}}`\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: Convert the contents of 'var1' variable to lowercase Bash Command:<START>var1=`echo $var1 | tr '[A-Z]' '[a-z]'`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: tr(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tr(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | BUGS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TR(1) User Commands TR(1) NAME top tr - translate or delete characters SYNOPSIS top tr [OPTION]... STRING1 [STRING2] DESCRIPTION top Translate, squeeze, and/or delete characters from standard input, writing to standard output. STRING1 and STRING2 specify arrays of characters ARRAY1 and ARRAY2 that control the action. -c, -C, --complement use the complement of ARRAY1 -d, --delete delete characters in ARRAY1, do not translate -s, --squeeze-repeats replace each sequence of a repeated character that is listed in the last specified ARRAY, with a single occurrence of that character -t, --truncate-set1 first truncate ARRAY1 to length of ARRAY2 --help display this help and exit --version output version information and exit ARRAYs are specified as strings of characters. Most represent themselves. Interpreted sequences are: \NNN character with octal value NNN (1 to 3 octal digits) \\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab \v vertical tab CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in ARRAY2, copies of CHAR until length of ARRAY1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [:alnum:] all letters and digits [:alpha:] all letters [:blank:] all horizontal whitespace [:cntrl:] all control characters [:digit:] all digits [:graph:] all printable characters, not including space [:lower:] all lower case letters [:print:] all printable characters, including space [:punct:] all punctuation characters [:space:] all horizontal or vertical whitespace [:upper:] all upper case letters [:xdigit:] all hexadecimal digits [=CHAR=] all characters which are equivalent to CHAR Translation occurs if -d is not given and both STRING1 and STRING2 appear. -t is only significant when translating. ARRAY2 is extended to length of ARRAY1 by repeating its last character as necessary. Excess characters of ARRAY2 are ignored. Character classes expand in unspecified order; while translating, [:lower:] and [:upper:] may be used in pairs to specify case conversion. Squeezing occurs after translation or deletion. BUGS top Full support is available only for safe single-byte locales, in which every possible input byte represents a single character. The C locale is safe in GNU systems, so you can avoid this issue in the shell by running LC_ALL=C tr instead of plain tr. 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 Full documentation <https://www.gnu.org/software/coreutils/tr> or available locally via: info '(coreutils) tr 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 TR(1) Pages that refer to this page: sed(1), 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. 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: Convert the contents of 'var1' variable to lowercase Bash Command:<START>var1=`echo $var1 | tr '[A-Z]' '[a-z]'`<END>
Convert the first 16 characters in "/dev/random" to a single hexadecimal value
head /dev/random -c16 | od -tx1 -w16 | head -n1 | cut -d' ' -f2- | tr -d ' '
['head', 'tr', 'cut', 'od']
Output a Bash command to accomplish the following task. Task: Convert the first 16 characters in "/dev/random" to a single hexadecimal value Bash Command:<START>head /dev/random -c16 | od -tx1 -w16 | head -n1 | cut -d' ' -f2- | tr -d ' '<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # tr\n\n> Translate characters: run replacements based on single characters and character sets.\n> More information: <https://www.gnu.org/software/coreutils/tr>.\n\n- Replace all occurrences of a character in a file, and print the result:\n\n`tr {{find_character}} {{replace_character}} < {{path/to/file}}`\n\n- Replace all occurrences of a character from another command's output:\n\n`echo {{text}} | tr {{find_character}} {{replace_character}}`\n\n- Map each character of the first set to the corresponding character of the second set:\n\n`tr '{{abcd}}' '{{jkmn}}' < {{path/to/file}}`\n\n- Delete all occurrences of the specified set of characters from the input:\n\n`tr -d '{{input_characters}}' < {{path/to/file}}`\n\n- Compress a series of identical characters to a single character:\n\n`tr -s '{{input_characters}}' < {{path/to/file}}`\n\n- Translate the contents of a file to upper-case:\n\n`tr "[:lower:]" "[:upper:]" < {{path/to/file}}`\n\n- Strip out non-printable characters from a file:\n\n`tr -cd "[:print:]" < {{path/to/file}}`\n # cut\n\n> Cut out fields from `stdin` or files.\n> More information: <https://www.gnu.org/software/coreutils/cut>.\n\n- Print a specific character/field range of each line:\n\n`{{command}} | cut --{{characters|fields}}={{1|1,10|1-10|1-|-10}}`\n\n- Print a field range of each line with a specific delimiter:\n\n`{{command}} | cut --delimiter="{{,}}" --fields={{1}}`\n\n- Print a character range of each line of the specific file:\n\n`cut --characters={{1}} {{path/to/file}}`\n # od\n\n> Display file contents in octal, decimal or hexadecimal format.\n> Optionally display the byte offsets and/or printable representation for each line.\n> More information: <https://www.gnu.org/software/coreutils/od>.\n\n- Display file using default settings: octal format, 8 bytes per line, byte offsets in octal, and duplicate lines replaced with `*`:\n\n`od {{path/to/file}}`\n\n- Display file in verbose mode, i.e. without replacing duplicate lines with `*`:\n\n`od -v {{path/to/file}}`\n\n- Display file in hexadecimal format (2-byte units), with byte offsets in decimal format:\n\n`od --format={{x}} --address-radix={{d}} -v {{path/to/file}}`\n\n- Display file in hexadecimal format (1-byte units), and 4 bytes per line:\n\n`od --format={{x1}} --width={{4}} -v {{path/to/file}}`\n\n- Display file in hexadecimal format along with its character representation, and do not print byte offsets:\n\n`od --format={{xz}} --address-radix={{n}} -v {{path/to/file}}`\n\n- Read only 100 bytes of a file starting from the 500th byte:\n\n`od --read-bytes {{100}} --skip-bytes={{500}} -v {{path/to/file}}`\n Task: Convert the first 16 characters in "/dev/random" to a single hexadecimal value Bash Command:<START>head /dev/random -c16 | od -tx1 -w16 | head -n1 | cut -d' ' -f2- | tr -d ' '<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. tr(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training tr(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | BUGS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TR(1) User Commands TR(1) NAME top tr - translate or delete characters SYNOPSIS top tr [OPTION]... STRING1 [STRING2] DESCRIPTION top Translate, squeeze, and/or delete characters from standard input, writing to standard output. STRING1 and STRING2 specify arrays of characters ARRAY1 and ARRAY2 that control the action. -c, -C, --complement use the complement of ARRAY1 -d, --delete delete characters in ARRAY1, do not translate -s, --squeeze-repeats replace each sequence of a repeated character that is listed in the last specified ARRAY, with a single occurrence of that character -t, --truncate-set1 first truncate ARRAY1 to length of ARRAY2 --help display this help and exit --version output version information and exit ARRAYs are specified as strings of characters. Most represent themselves. Interpreted sequences are: \NNN character with octal value NNN (1 to 3 octal digits) \\ backslash \a audible BEL \b backspace \f form feed \n new line \r return \t horizontal tab \v vertical tab CHAR1-CHAR2 all characters from CHAR1 to CHAR2 in ascending order [CHAR*] in ARRAY2, copies of CHAR until length of ARRAY1 [CHAR*REPEAT] REPEAT copies of CHAR, REPEAT octal if starting with 0 [:alnum:] all letters and digits [:alpha:] all letters [:blank:] all horizontal whitespace [:cntrl:] all control characters [:digit:] all digits [:graph:] all printable characters, not including space [:lower:] all lower case letters [:print:] all printable characters, including space [:punct:] all punctuation characters [:space:] all horizontal or vertical whitespace [:upper:] all upper case letters [:xdigit:] all hexadecimal digits [=CHAR=] all characters which are equivalent to CHAR Translation occurs if -d is not given and both STRING1 and STRING2 appear. -t is only significant when translating. ARRAY2 is extended to length of ARRAY1 by repeating its last character as necessary. Excess characters of ARRAY2 are ignored. Character classes expand in unspecified order; while translating, [:lower:] and [:upper:] may be used in pairs to specify case conversion. Squeezing occurs after translation or deletion. BUGS top Full support is available only for safe single-byte locales, in which every possible input byte represents a single character. The C locale is safe in GNU systems, so you can avoid this issue in the shell by running LC_ALL=C tr instead of plain tr. 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 Full documentation <https://www.gnu.org/software/coreutils/tr> or available locally via: info '(coreutils) tr 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 TR(1) Pages that refer to this page: sed(1), 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. cut(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cut(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CUT(1) User Commands CUT(1) NAME top cut - remove sections from each line of files SYNOPSIS top cut OPTION... [FILE]... DESCRIPTION top Print selected parts of lines from each FILE to standard output. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -b, --bytes=LIST select only these bytes -c, --characters=LIST select only these characters -d, --delimiter=DELIM use DELIM instead of TAB for field delimiter -f, --fields=LIST select only these fields; also print any line that contains no delimiter character, unless the -s option is specified -n (ignored) --complement complement the set of selected bytes, characters or fields -s, --only-delimited do not print lines not containing delimiters --output-delimiter=STRING use STRING as the output delimiter the default is to use the input delimiter -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit Use one, and only one of -b, -c or -f. Each LIST is made up of one range, or many ranges separated by commas. Selected input is written in the same order that it is read, and is written exactly once. Each range is one of: N N'th byte, character or field, counted from 1 N- from N'th byte, character or field, to end of line N-M from N'th to M'th (included) byte, character or field -M from first to M'th (included) byte, character or field AUTHOR top Written by David M. Ihnat, 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 Full documentation <https://www.gnu.org/software/coreutils/cut> or available locally via: info '(coreutils) cut 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 CUT(1) Pages that refer to this page: man-pages(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. od(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training od(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON OD(1) User Commands OD(1) NAME top od - dump files in octal and other formats SYNOPSIS top od [OPTION]... [FILE]... od [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]] od --traditional [OPTION]... [FILE] [[+]OFFSET[.][b] [+][LABEL][.][b]] DESCRIPTION top Write an unambiguous representation, octal bytes by default, of FILE to standard output. With more than one FILE argument, concatenate them in the listed order to form the input. With no FILE, or when FILE is -, read standard input. If first and second call formats both apply, the second format is assumed if the last operand begins with + or (if there are 2 operands) a digit. An OFFSET operand means -j OFFSET. LABEL is the pseudo-address at first byte printed, incremented when dump is progressing. For OFFSET and LABEL, a 0x or 0X prefix indicates hexadecimal; suffixes may be . for octal and b for multiply by 512. Mandatory arguments to long options are mandatory for short options too. -A, --address-radix=RADIX output format for file offsets; RADIX is one of [doxn], for Decimal, Octal, Hex or None --endian={big|little} swap input bytes according the specified order -j, --skip-bytes=BYTES skip BYTES input bytes first -N, --read-bytes=BYTES limit dump to BYTES input bytes -S BYTES, --strings[=BYTES] show only NUL terminated strings of at least BYTES (3) printable characters -t, --format=TYPE select output format or formats -v, --output-duplicates do not use * to mark line suppression -w[BYTES], --width[=BYTES] output BYTES bytes per output line; 32 is implied when BYTES is not specified --traditional accept arguments in third form above --help display this help and exit --version output version information and exit Traditional format specifications may be intermixed; they accumulate: -a same as -t a, select named characters, ignoring high-order bit -b same as -t o1, select octal bytes -c same as -t c, select printable characters or backslash escapes -d same as -t u2, select unsigned decimal 2-byte units -f same as -t fF, select floats -i same as -t dI, select decimal ints -l same as -t dL, select decimal longs -o same as -t o2, select octal 2-byte units -s same as -t d2, select decimal 2-byte units -x same as -t x2, select hexadecimal 2-byte units TYPE is made up of one or more of these specifications: a named character, ignoring high-order bit c printable character or backslash escape d[SIZE] signed decimal, SIZE bytes per integer f[SIZE] floating point, SIZE bytes per float o[SIZE] octal, SIZE bytes per integer u[SIZE] unsigned decimal, SIZE bytes per integer x[SIZE] hexadecimal, SIZE bytes per integer SIZE is a number. For TYPE in [doux], SIZE may also be C for sizeof(char), S for sizeof(short), I for sizeof(int) or L for sizeof(long). If TYPE is f, SIZE may also be F for sizeof(float), D for sizeof(double) or L for sizeof(long double). Adding a z suffix to any type displays printable characters at the end of each output line. BYTES is hex with 0x or 0X prefix, and may have a multiplier suffix: b 512 KB 1000 K 1024 MB 1000*1000 M 1024*1024 and so on for G, T, P, E, Z, Y, R, Q. Binary prefixes can be used, too: KiB=K, MiB=M, and so on. EXAMPLES top od -A x -t x1z -v Display hexdump format output od -A o -t oS -w16 The default output format used by od 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 Full documentation <https://www.gnu.org/software/coreutils/od> or available locally via: info '(coreutils) od 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 OD(1) Pages that refer to this page: scr_dump(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: Convert the first 16 characters in "/dev/random" to a single hexadecimal value Bash Command:<START>head /dev/random -c16 | od -tx1 -w16 | head -n1 | cut -d' ' -f2- | tr -d ' '<END>
Converts all windows line endings to unix line endings
find $(pwd) -type f | xargs -I xxx sed -i 's/\r//g' xxx
['find', 'pwd', 'xargs', 'sed']
Output a Bash command to accomplish the following task. Task: Converts all windows line endings to unix line endings Bash Command:<START>find $(pwd) -type f | xargs -I xxx sed -i 's/\r//g' xxx<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 # 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 # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # sed\n\n> Edit text in a scriptable manner.\n> See also: `awk`, `ed`.\n> More information: <https://www.gnu.org/software/sed/manual/sed.html>.\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed 's/apple/mango/g'`\n\n- Replace all `apple` (extended regex) occurrences with `APPLE` (extended regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed -E 's/(apple)/\U\1/g'`\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in a specific file and overwrite the original file in place:\n\n`sed -i 's/apple/mango/g' {{path/to/file}}`\n\n- Execute a specific script [f]ile and print the result to `stdout`:\n\n`{{command}} | sed -f {{path/to/script.sed}}`\n\n- Print just the first line to `stdout`:\n\n`{{command}} | sed -n '1p'`\n\n- [d]elete the first line of a file:\n\n`sed -i 1d {{path/to/file}}`\n\n- [i]nsert a new line at the first line of a file:\n\n`sed -i '1i\your new line text\' {{path/to/file}}`\n Task: Converts all windows line endings to unix line endings Bash Command:<START>find $(pwd) -type f | xargs -I xxx sed -i 's/\r//g' xxx<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. 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. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. sed(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sed(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND SYNOPSIS | REGULAR EXPRESSIONS | BUGS | AUTHOR | COPYRIGHT | SEE ALSO | COLOPHON SED(1) User Commands SED(1) NAME top sed - stream editor for filtering and transforming text SYNOPSIS top sed [-V] [--version] [--help] [-n] [--quiet] [--silent] [-l N] [--line-length=N] [-u] [--unbuffered] [-E] [-r] [--regexp-extended] [-e script] [--expression=script] [-f script-file] [--file=script-file] [script-if-no-other-script] [file...] DESCRIPTION top Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors. -n, --quiet, --silent suppress automatic printing of pattern space --debug annotate program execution -e script, --expression=script add the script to the commands to be executed -f script-file, --file=script-file add the contents of script-file to the commands to be executed --follow-symlinks follow symlinks when processing in place -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied) -l N, --line-length=N specify the desired line-wrap length for the `l' command --posix disable all GNU extensions. -E, -r, --regexp-extended use extended regular expressions in the script (for portability use POSIX -E). -s, --separate consider files as separate rather than as a single, continuous long stream. --sandbox operate in sandbox mode (disable e/r/w commands). -u, --unbuffered load minimal amounts of data from the input files and flush the output buffers more often -z, --null-data separate lines by NUL characters --help display this help and exit --version output version information and exit If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret. All remaining arguments are names of input files; if no input files are specified, then the standard input is read. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COMMAND SYNOPSIS top This is just a brief synopsis of sed commands to serve as a reminder to those who already know sed; other documentation (such as the texinfo document) must be consulted for fuller descriptions. Zero-address ``commands'' : label Label for b and t commands. #comment The comment extends until the next newline (or the end of a -e script fragment). } The closing bracket of a { } block. Zero- or One- address commands = Print the current line number. a \ text Append text, which has each embedded newline preceded by a backslash. i \ text Insert text, which has each embedded newline preceded by a backslash. q [exit-code] Immediately quit the sed script without processing any more input, except that if auto-print is not disabled the current pattern space will be printed. The exit code argument is a GNU extension. Q [exit-code] Immediately quit the sed script without processing any more input. This is a GNU extension. r filename Append text read from filename. R filename Append a line read from filename. Each invocation of the command reads a line from the file. This is a GNU extension. Commands which accept address ranges { Begin a block of commands (end with a }). b label Branch to label; if label is omitted, branch to end of script. c \ text Replace the selected lines with text, which has each embedded newline preceded by a backslash. d Delete pattern space. Start next cycle. D If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input. h H Copy/append pattern space to hold space. g G Copy/append hold space to pattern space. l List out the current line in a ``visually unambiguous'' form. l width List out the current line in a ``visually unambiguous'' form, breaking it at width characters. This is a GNU extension. n N Read/append the next line of input into the pattern space. p Print the current pattern space. P Print up to the first embedded newline of the current pattern space. s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp. t label If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. T label If no s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. This is a GNU extension. w filename Write the current pattern space to filename. W filename Write the first line of the current pattern space to filename. This is a GNU extension. x Exchange the contents of the hold and pattern spaces. y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding character in dest. Addresses Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address. Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched. After the address (or address-range), and before the command, a ! may be inserted, which specifies that the command shall only be executed if the address (or address-range) does not match. The following address types are supported: number Match only the specified line number (which increments cumulatively across files, unless the -s option is specified on the command line). first~step Match every step'th line starting with line first. For example, ``sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. first can be zero; in this case, sed operates as if it were equal to step. (This is an extension.) $ Match the last line. /regexp/ Match lines matching the regular expression regexp. Matching is performed on the current pattern space, which can be modified with commands such as ``s///''. \cregexpc Match lines matching the regular expression regexp. The c may be any character. GNU sed also supports some special 2-address forms: 0,addr2 Start out in "matched first address" state, until addr2 is found. This is similar to 1,addr2, except that if addr2 matches the very first line of input the 0,addr2 form will be at the end of its range, whereas the 1,addr2 form will still be at the beginning of its range. This works only when addr2 is a regular expression. addr1,+N Will match addr1 and the N lines following addr1. addr1,~N Will match addr1 and the lines following addr1 until the next line whose input line number is a multiple of N. REGULAR EXPRESSIONS top POSIX.2 BREs should be supported, but they aren't completely because of performance problems. The \n sequence in a regular expression matches the newline character, and similarly for \a, \t, and other sequences. The -E option switches to using extended regular expressions instead; it has been supported for years by GNU sed, and is now included in POSIX. BUGS top E-mail bug reports to bug-sed@gnu.org. Also, please include the output of ``sed --version'' in the body of your report if at all possible. AUTHOR top Written by Jay Fenlason, Tom Lord, Ken Pizzini, Paolo Bonzini, Jim Meyering, and Assaf Gordon. This sed program was built with SELinux support. SELinux is enabled on this system. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COPYRIGHT top Copyright 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top awk(1), ed(1), grep(1), tr(1), perlre(1), sed.info, any of various books on sed, the sed FAQ (http://sed.sf.net/grabbag/tutorials/sedfaq.txt), http://sed.sf.net/grabbag/. The full documentation for sed is maintained as a Texinfo manual. If the info and sed programs are properly installed at your site, the command info sed should give you access to the complete manual. COLOPHON top This page is part of the sed (stream-oriented editor) project. Information about the project can be found at http://www.gnu.org/software/sed/. If you have a bug report for this manual page, send it to bug-sed@gnu.org. This page was obtained from the tarball sed-4.9.tar.gz fetched from https://www.gnu.org/software/sed/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU sed 4.9 November 2022 SED(1) Pages that refer to this page: gawk(1), grep(1), iostat2pcp(1), pmdaopenmetrics(1), pmlogrewrite(1), sheet2pcp(1), cpuset(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Converts all windows line endings to unix line endings Bash Command:<START>find $(pwd) -type f | xargs -I xxx sed -i 's/\r//g' xxx<END>
Copies ""$project_dir"/iTunesArtwork", to the 'Payload/iTunesArtwork', rewriting files if necessary.
cp -f "$project_dir"/iTunesArtwork Payload/iTunesArtwork
['cp']
Output a Bash command to accomplish the following task. Task: Copies ""$project_dir"/iTunesArtwork", to the 'Payload/iTunesArtwork', rewriting files if necessary. Bash Command:<START>cp -f "$project_dir"/iTunesArtwork Payload/iTunesArtwork<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies ""$project_dir"/iTunesArtwork", to the 'Payload/iTunesArtwork', rewriting files if necessary. Bash Command:<START>cp -f "$project_dir"/iTunesArtwork Payload/iTunesArtwork<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies ""$project_dir"/iTunesArtwork", to the 'Payload/iTunesArtwork', rewriting files if necessary. Bash Command:<START>cp -f "$project_dir"/iTunesArtwork Payload/iTunesArtwork<END>
Copies ${FILE} to COLLECT folder with unique name formatted like 'job_XXXXXXXXX'.
cp "${FILE}" "COLLECT/$(mktemp job_XXXXXXXXX)"
['mktemp', 'cp']
Output a Bash command to accomplish the following task. Task: Copies ${FILE} to COLLECT folder with unique name formatted like 'job_XXXXXXXXX'. Bash Command:<START>cp "${FILE}" "COLLECT/$(mktemp job_XXXXXXXXX)"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # mktemp\n\n> Create a temporary file or directory.\n> More information: <https://www.gnu.org/software/coreutils/mktemp>.\n\n- Create an empty temporary file and print its absolute path:\n\n`mktemp`\n\n- Use a custom directory (defaults to `$TMPDIR`, or `/tmp`):\n\n`mktemp --tmpdir={{/path/to/tempdir}}`\n\n- Use a custom path template (`X`s are replaced with random alphanumeric characters):\n\n`mktemp {{/tmp/example.XXXXXXXX}}`\n\n- Use a custom file name template:\n\n`mktemp -t {{example.XXXXXXXX}}`\n\n- Create an empty temporary file with the given suffix and print its absolute path:\n\n`mktemp --suffix {{.ext}}`\n\n- Create an empty temporary directory and print its absolute path:\n\n`mktemp --directory`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies ${FILE} to COLLECT folder with unique name formatted like 'job_XXXXXXXXX'. Bash Command:<START>cp "${FILE}" "COLLECT/$(mktemp job_XXXXXXXXX)"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: mktemp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training mktemp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON MKTEMP(1) User Commands MKTEMP(1) NAME top mktemp - create a temporary file or directory SYNOPSIS top mktemp [OPTION]... [TEMPLATE] DESCRIPTION top Create a temporary file or directory, safely, and print its name. TEMPLATE must contain at least 3 consecutive 'X's in last component. If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied. Files are created u+rw, and directories u+rwx, minus umask restrictions. -d, --directory create a directory, not a file -u, --dry-run do not create anything; merely print a name (unsafe) -q, --quiet suppress diagnostics about file/dir-creation failure --suffix=SUFF append SUFF to TEMPLATE; SUFF must not contain a slash. This option is implied if TEMPLATE does not end in X -p DIR, --tmpdir[=DIR] interpret TEMPLATE relative to DIR; if DIR is not specified, use $TMPDIR if set, else /tmp. With this option, TEMPLATE must not be an absolute name; unlike with -t, TEMPLATE may contain slashes, but mktemp creates only the final component -t interpret TEMPLATE as a single file name component, relative to a directory: $TMPDIR, if set; else the directory specified via -p; else /tmp [deprecated] --help display this help and exit --version output version information and exit AUTHOR top Written by Jim Meyering and Eric Blake. 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 mkstemp(3), mkdtemp(3), mktemp(3) Full documentation <https://www.gnu.org/software/coreutils/mktemp> or available locally via: info '(coreutils) mktemp 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 MKTEMP(1) Pages that refer to this page: mkdtemp(3), mktemp(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. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies ${FILE} to COLLECT folder with unique name formatted like 'job_XXXXXXXXX'. Bash Command:<START>cp "${FILE}" "COLLECT/$(mktemp job_XXXXXXXXX)"<END>
Copies '[MacVim_source_folder]/src/MacVim/mvim' to the '/usr/local/bin', printing info message on each operation.
cp -v [MacVim_source_folder]/src/MacVim/mvim /usr/local/bin
['cp']
Output a Bash command to accomplish the following task. Task: Copies '[MacVim_source_folder]/src/MacVim/mvim' to the '/usr/local/bin', printing info message on each operation. Bash Command:<START>cp -v [MacVim_source_folder]/src/MacVim/mvim /usr/local/bin<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies '[MacVim_source_folder]/src/MacVim/mvim' to the '/usr/local/bin', printing info message on each operation. Bash Command:<START>cp -v [MacVim_source_folder]/src/MacVim/mvim /usr/local/bin<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies '[MacVim_source_folder]/src/MacVim/mvim' to the '/usr/local/bin', printing info message on each operation. Bash Command:<START>cp -v [MacVim_source_folder]/src/MacVim/mvim /usr/local/bin<END>
Copies 'libgtest_main.so' and 'libgtest.so' to '/usr/lib/', preserving all attributes, and copying symlinks as symlinks, without following in source files.
sudo cp -a libgtest_main.so libgtest.so /usr/lib/
['cp', 'sudo']
Output a Bash command to accomplish the following task. Task: Copies 'libgtest_main.so' and 'libgtest.so' to '/usr/lib/', preserving all attributes, and copying symlinks as symlinks, without following in source files. Bash Command:<START>sudo cp -a libgtest_main.so libgtest.so /usr/lib/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n # sudo\n\n> Executes a single command as the superuser or another user.\n> More information: <https://www.sudo.ws/sudo.html>.\n\n- Run a command as the superuser:\n\n`sudo {{less /var/log/syslog}}`\n\n- Edit a file as the superuser with your default editor:\n\n`sudo --edit {{/etc/fstab}}`\n\n- Run a command as another user and/or group:\n\n`sudo --user={{user}} --group={{group}} {{id -a}}`\n\n- Repeat the last command prefixed with `sudo` (only in Bash, Zsh, etc.):\n\n`sudo !!`\n\n- Launch the default shell with superuser privileges and run login-specific files (`.profile`, `.bash_profile`, etc.):\n\n`sudo --login`\n\n- Launch the default shell with superuser privileges without changing the environment:\n\n`sudo --shell`\n\n- Launch the default shell as the specified user, loading the user's environment and reading login-specific files (`.profile`, `.bash_profile`, etc.):\n\n`sudo --login --user={{user}}`\n\n- List the allowed (and forbidden) commands for the invoking user:\n\n`sudo --list`\n Task: Copies 'libgtest_main.so' and 'libgtest.so' to '/usr/lib/', preserving all attributes, and copying symlinks as symlinks, without following in source files. Bash Command:<START>sudo cp -a libgtest_main.so libgtest.so /usr/lib/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. sudo(8) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sudo(8) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND EXECUTION | EXIT VALUE | SECURITY NOTES | ENVIRONMENT | FILES | EXAMPLES | DIAGNOSTICS | SEE ALSO | HISTORY | AUTHORS | CAVEATS | BUGS | SUPPORT | DISCLAIMER | COLOPHON SUDO(8) System Manager's Manual SUDO(8) NAME top sudo, sudoedit execute a command as another user SYNOPSIS top sudo -h | -K | -k | -V sudo -v [-ABkNnS] [-g group] [-h host] [-p prompt] [-u user] sudo -l [-ABkNnS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command [arg ...]] sudo [-ABbEHnPS] [-C num] [-D directory] [-g group] [-h host] [-p prompt] [-R directory] [-T timeout] [-u user] [VAR=value] [-i | -s] [command [arg ...]] sudoedit [-ABkNnS] [-C num] [-D directory] [-g group] [-h host] [-p prompt] [-R directory] [-T timeout] [-u user] file ... DESCRIPTION top allows a permitted user to execute a command as the superuser or another user, as specified by the security policy. The invoking user's real (not effective) user-ID is used to determine the user name with which to query the security policy. supports a plugin architecture for security policies, auditing, and input/output logging. Third parties can develop and distribute their own plugins to work seamlessly with the front- end. The default security policy is sudoers, which is configured via the file /etc/sudoers, or via LDAP. See the Plugins section for more information. The security policy determines what privileges, if any, a user has to run . The policy may require that users authenticate themselves with a password or another authentication mechanism. If authentication is required, will exit if the user's password is not entered within a configurable time limit. This limit is policy-specific; the default password prompt timeout for the sudoers security policy is 5 minutes. Security policies may support credential caching to allow the user to run again for a period of time without requiring authentication. By default, the sudoers policy caches credentials on a per-terminal basis for 5 minutes. See the timestamp_type and timestamp_timeout options in sudoers(5) for more information. By running with the -v option, a user can update the cached credentials without running a command. On systems where is the primary method of gaining superuser privileges, it is imperative to avoid syntax errors in the security policy configuration files. For the default security policy, sudoers(5), changes to the configuration files should be made using the visudo(8) utility which will ensure that no syntax errors are introduced. When invoked as sudoedit, the -e option (described below), is implied. Security policies and audit plugins may log successful and failed attempts to run . If an I/O plugin is configured, the running command's input and output may be logged as well. The options are as follows: -A, --askpass Normally, if requires a password, it will read it from the user's terminal. If the -A (askpass) option is specified, a (possibly graphical) helper program is executed to read the user's password and output the password to the standard output. If the SUDO_ASKPASS environment variable is set, it specifies the path to the helper program. Otherwise, if sudo.conf(5) contains a line specifying the askpass program, that value will be used. For example: # Path to askpass helper program Path askpass /usr/X11R6/bin/ssh-askpass If no askpass program is available, will exit with an error. -B, --bell Ring the bell as part of the password prompt when a terminal is present. This option has no effect if an askpass program is used. -b, --background Run the given command in the background. It is not possible to use shell job control to manipulate background processes started by . Most interactive commands will fail to work properly in background mode. -C num, --close-from=num Close all file descriptors greater than or equal to num before executing a command. Values less than three are not permitted. By default, will close all open file descriptors other than standard input, standard output, and standard error when executing a command. The security policy may restrict the user's ability to use this option. The sudoers policy only permits use of the -C option when the administrator has enabled the closefrom_override option. -D directory, --chdir=directory Run the command in the specified directory instead of the current working directory. The security policy may return an error if the user does not have permission to specify the working directory. -E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment. --preserve-env=list Indicates to the security policy that the user wishes to add the comma-separated list of environment variables to those preserved from the user's environment. The security policy may return an error if the user does not have permission to preserve the environment. This option may be specified multiple times. -e, --edit Edit one or more files instead of running a command. In lieu of a path name, the string "sudoedit" is used when consulting the security policy. If the user is authorized by the policy, the following steps are taken: 1. Temporary copies are made of the files to be edited with the owner set to the invoking user. 2. The editor specified by the policy is run to edit the temporary files. The sudoers policy uses the SUDO_EDITOR, VISUAL and EDITOR environment variables (in that order). If none of SUDO_EDITOR, VISUAL or EDITOR are set, the first program listed in the editor sudoers(5) option is used. 3. If they have been modified, the temporary files are copied back to their original location and the temporary versions are removed. To help prevent the editing of unauthorized files, the following restrictions are enforced unless explicitly allowed by the security policy: Symbolic links may not be edited (version 1.8.15 and higher). Symbolic links along the path to be edited are not followed when the parent directory is writable by the invoking user unless that user is root (version 1.8.16 and higher). Files located in a directory that is writable by the invoking user may not be edited unless that user is root (version 1.8.16 and higher). Users are never allowed to edit device special files. If the specified file does not exist, it will be created. Unlike most commands run by sudo, the editor is run with the invoking user's environment unmodified. If the temporary file becomes empty after editing, the user will be prompted before it is installed. If, for some reason, is unable to update a file with its edited version, the user will receive a warning and the edited copy will remain in a temporary file. -g group, --group=group Run the command with the primary group set to group instead of the primary group specified by the target user's password database entry. The group may be either a group name or a numeric group-ID (GID) prefixed with the # character (e.g., #0 for GID 0). When running a command as a GID, many shells require that the # be escaped with a backslash (\). If no -u option is specified, the command will be run as the invoking user. In either case, the primary group will be set to group. The sudoers policy permits any of the target user's groups to be specified via the -g option as long as the -P option is not in use. -H, --set-home Request that the security policy set the HOME environment variable to the home directory specified by the target user's password database entry. Depending on the policy, this may be the default behavior. -h, --help Display a short help message to the standard output and exit. -h host, --host=host Run the command on the specified host if the security policy plugin supports remote commands. The sudoers plugin does not currently support running remote commands. This may also be used in conjunction with the -l option to list a user's privileges for the remote host. -i, --login Run the shell specified by the target user's password database entry as a login shell. This means that login- specific resource files such as .profile, .bash_profile, or .login will be read by the shell. If a command is specified, it is passed to the shell as a simple command using the -c option. The command and any args are concatenated, separated by spaces, after escaping each character (including white space) with a backslash (\) except for alphanumerics, underscores, hyphens, and dollar signs. If no command is specified, an interactive shell is executed. attempts to change to that user's home directory before running the shell. The command is run with an environment similar to the one a user would receive at log in. Most shells behave differently when a command is specified as compared to an interactive session; consult the shell's manual for details. The Command environment section in the sudoers(5) manual documents how the -i option affects the environment in which a command is run when the sudoers policy is in use. -K, --remove-timestamp Similar to the -k option, except that it removes every cached credential for the user, regardless of the terminal or parent process ID. The next time is run, a password must be entered if the security policy requires authentication. It is not possible to use the -K option in conjunction with a command or other option. This option does not require a password. Not all security policies support credential caching. -k, --reset-timestamp When used without a command, invalidates the user's cached credentials for the current session. The next time is run in the session, a password must be entered if the security policy requires authentication. By default, the sudoers policy uses a separate record in the credential cache for each terminal (or parent process ID if no terminal is present). This prevents the -k option from interfering with commands run in a different terminal session. See the timestamp_type option in sudoers(5) for more information. This option does not require a password, and was added to allow a user to revoke permissions from a .logout file. When used in conjunction with a command or an option that may require a password, this option will cause to ignore the user's cached credentials. As a result, will prompt for a password (if one is required by the security policy) and will not update the user's cached credentials. Not all security policies support credential caching. -l, --list If no command is specified, list the privileges for the invoking user (or the user specified by the -U option) on the current host. A longer list format is used if this option is specified multiple times and the security policy supports a verbose output format. If a command is specified and is permitted by the security policy for the invoking user (or the, user specified by the -U option) on the current host, the fully-qualified path to the command is displayed along with any args. If -l is specified more than once (and the security policy supports it), the matching rule is displayed in a verbose format along with the command. If a command is specified but not allowed by the policy, will exit with a status value of 1. -N, --no-update Do not update the user's cached credentials, even if the user successfully authenticates. Unlike the -k flag, existing cached credentials are used if they are valid. To detect when the user's cached credentials are valid (or when no authentication is required), the following can be used: sudo -Nnv Not all security policies support credential caching. -n, --non-interactive Avoid prompting the user for input of any kind. If a password is required for the command to run, will display an error message and exit. -P, --preserve-groups Preserve the invoking user's group vector unaltered. By default, the sudoers policy will initialize the group vector to the list of groups the target user is a member of. The real and effective group-IDs, however, are still set to match the target user. -p prompt, --prompt=prompt Use a custom password prompt with optional escape sequences. The following percent (%) escape sequences are supported by the sudoers policy: %H expanded to the host name including the domain name (only if the machine's host name is fully qualified or the fqdn option is set in sudoers(5)) %h expanded to the local host name without the domain name %p expanded to the name of the user whose password is being requested (respects the rootpw, targetpw, and runaspw flags in sudoers(5)) %U expanded to the login name of the user the command will be run as (defaults to root unless the -u option is also specified) %u expanded to the invoking user's login name %% two consecutive % characters are collapsed into a single % character The custom prompt will override the default prompt specified by either the security policy or the SUDO_PROMPT environment variable. On systems that use PAM, the custom prompt will also override the prompt specified by a PAM module unless the passprompt_override flag is disabled in sudoers. -R directory, --chroot=directory Change to the specified root directory (see chroot(8)) before running the command. The security policy may return an error if the user does not have permission to specify the root directory. -S, --stdin Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. -s, --shell Run the shell specified by the SHELL environment variable if it is set or the shell specified by the invoking user's password database entry. If a command is specified, it is passed to the shell as a simple command using the -c option. The command and any args are concatenated, separated by spaces, after escaping each character (including white space) with a backslash (\) except for alphanumerics, underscores, hyphens, and dollar signs. If no command is specified, an interactive shell is executed. Most shells behave differently when a command is specified as compared to an interactive session; consult the shell's manual for details. -U user, --other-user=user Used in conjunction with the -l option to list the privileges for user instead of for the invoking user. The security policy may restrict listing other users' privileges. When using the sudoers policy, the -U option is restricted to the root user and users with either the list priviege for the specified user or the ability to run any command as root or user on the current host. -T timeout, --command-timeout=timeout Used to set a timeout for the command. If the timeout expires before the command has exited, the command will be terminated. The security policy may restrict the user's ability to set timeouts. The sudoers policy requires that user-specified timeouts be explicitly enabled. -u user, --user=user Run the command as a user other than the default target user (usually root). The user may be either a user name or a numeric user-ID (UID) prefixed with the # character (e.g., #0 for UID 0). When running commands as a UID, many shells require that the # be escaped with a backslash (\). Some security policies may restrict UIDs to those listed in the password database. The sudoers policy allows UIDs that are not in the password database as long as the targetpw option is not set. Other security policies may not support this. -V, --version Print the version string as well as the version string of any configured plugins. If the invoking user is already root, the -V option will display the options passed to configure when was built; plugins may display additional information such as default options. -v, --validate Update the user's cached credentials, authenticating the user if necessary. For the sudoers plugin, this extends the timeout for another 5 minutes by default, but does not run a command. Not all security policies support cached credentials. -- The -- is used to delimit the end of the options. Subsequent options are passed to the command. Options that take a value may only be specified once unless otherwise indicated in the description. This is to help guard against problems caused by poorly written scripts that invoke sudo with user-controlled input. Environment variables to be set for the command may also be passed as options to in the form VAR=value, for example LD_LIBRARY_PATH=/usr/local/pkg/lib. Environment variables may be subject to restrictions imposed by the security policy plugin. The sudoers policy subjects environment variables passed as options to the same restrictions as existing environment variables with one important difference. If the setenv option is set in sudoers, the command to be run has the SETENV tag set or the command matched is ALL, the user may set variables that would otherwise be forbidden. See sudoers(5) for more information. COMMAND EXECUTION top When executes a command, the security policy specifies the execution environment for the command. Typically, the real and effective user and group and IDs are set to match those of the target user, as specified in the password database, and the group vector is initialized based on the group database (unless the -P option was specified). The following parameters may be specified by security policy: real and effective user-ID real and effective group-ID supplementary group-IDs the environment list current working directory file creation mode mask (umask) scheduling priority (aka nice value) Process model There are two distinct ways can run a command. If an I/O logging plugin is configured to log terminal I/O, or if the security policy explicitly requests it, a new pseudo-terminal (pty) is allocated and fork(2) is used to create a second process, referred to as the monitor. The monitor creates a new terminal session with itself as the leader and the pty as its controlling terminal, calls fork(2) again, sets up the execution environment as described above, and then uses the execve(2) system call to run the command in the child process. The monitor exists to relay job control signals between the user's terminal and the pty the command is being run in. This makes it possible to suspend and resume the command normally. Without the monitor, the command would be in what POSIX terms an orphaned process group and it would not receive any job control signals from the kernel. When the command exits or is terminated by a signal, the monitor passes the command's exit status to the main process and exits. After receiving the command's exit status, the main process passes the command's exit status to the security policy's close function, as well as the close function of any configured audit plugin, and exits. This mode is the default for sudo versions 1.9.14 and above when using the sudoers policy. If no pty is used, calls fork(2), sets up the execution environment as described above, and uses the execve(2) system call to run the command in the child process. The main process waits until the command has completed, then passes the command's exit status to the security policy's close function, as well as the close function of any configured audit plugins, and exits. As a special case, if the policy plugin does not define a close function, will execute the command directly instead of calling fork(2) first. The sudoers policy plugin will only define a close function when I/O logging is enabled, a pty is required, an SELinux role is specified, the command has an associated timeout, or the pam_session or pam_setcred options are enabled. Both pam_session and pam_setcred are enabled by default on systems using PAM. This mode is the default for sudo versions prior to 1.9.14 when using the sudoers policy. On systems that use PAM, the security policy's close function is responsible for closing the PAM session. It may also log the command's exit status. Signal handling When the command is run as a child of the process, will relay signals it receives to the command. The SIGINT and SIGQUIT signals are only relayed when the command is being run in a new pty or when the signal was sent by a user process, not the kernel. This prevents the command from receiving SIGINT twice each time the user enters control-C. Some signals, such as SIGSTOP and SIGKILL, cannot be caught and thus will not be relayed to the command. As a general rule, SIGTSTP should be used instead of SIGSTOP when you wish to suspend a command being run by . As a special case, will not relay signals that were sent by the command it is running. This prevents the command from accidentally killing itself. On some systems, the reboot(8) utility sends SIGTERM to all non-system processes other than itself before rebooting the system. This prevents from relaying the SIGTERM signal it received back to reboot(8), which might then exit before the system was actually rebooted, leaving it in a half-dead state similar to single user mode. Note, however, that this check only applies to the command run by and not any other processes that the command may create. As a result, running a script that calls reboot(8) or shutdown(8) via may cause the system to end up in this undefined state unless the reboot(8) or shutdown(8) are run using the exec() family of functions instead of system() (which interposes a shell between the command and the calling process). Plugins Plugins may be specified via Plugin directives in the sudo.conf(5) file. They may be loaded as dynamic shared objects (on systems that support them), or compiled directly into the binary. If no sudo.conf(5) file is present, or if it doesn't contain any Plugin lines, will use sudoers(5) for the policy, auditing, and I/O logging plugins. See the sudo.conf(5) manual for details of the /etc/sudo.conf file and the sudo_plugin(5) manual for more information about the plugin architecture. EXIT VALUE top Upon successful execution of a command, the exit status from will be the exit status of the program that was executed. If the command terminated due to receipt of a signal, will send itself the same signal that terminated the command. If the -l option was specified without a command, will exit with a value of 0 if the user is allowed to run and they authenticated successfully (as required by the security policy). If a command is specified with the -l option, the exit value will only be 0 if the command is permitted by the security policy, otherwise it will be 1. If there is an authentication failure, a configuration/permission problem, or if the given command cannot be executed, exits with a value of 1. In the latter case, the error string is printed to the standard error. If cannot stat(2) one or more entries in the user's PATH, an error is printed to the standard error. (If the directory does not exist or if it is not really a directory, the entry is ignored and no error is printed.) This should not happen under normal circumstances. The most common reason for stat(2) to return permission denied is if you are running an automounter and one of the directories in your PATH is on a machine that is currently unreachable. SECURITY NOTES top tries to be safe when executing external commands. To prevent command spoofing, checks "." and "" (both denoting current directory) last when searching for a command in the user's PATH (if one or both are in the PATH). Depending on the security policy, the user's PATH environment variable may be modified, replaced, or passed unchanged to the program that executes. Users should never be granted privileges to execute files that are writable by the user or that reside in a directory that is writable by the user. If the user can modify or replace the command there is no way to limit what additional commands they can run. By default, will only log the command it explicitly runs. If a user runs a command such as sudo su or sudo sh, subsequent commands run from that shell are not subject to sudo's security policy. The same is true for commands that offer shell escapes (including most editors). If I/O logging is enabled, subsequent commands will have their input and/or output logged, but there will not be traditional logs for those commands. Because of this, care must be taken when giving users access to commands via to verify that the command does not inadvertently give the user an effective root shell. For information on ways to address this, see the Preventing shell escapes section in sudoers(5). To prevent the disclosure of potentially sensitive information, disables core dumps by default while it is executing (they are re-enabled for the command that is run). This historical practice dates from a time when most operating systems allowed set-user-ID processes to dump core by default. To aid in debugging crashes, you may wish to re-enable core dumps by setting disable_coredump to false in the sudo.conf(5) file as follows: Set disable_coredump false See the sudo.conf(5) manual for more information. ENVIRONMENT top utilizes the following environment variables. The security policy has control over the actual content of the command's environment. EDITOR Default editor to use in -e (sudoedit) mode if neither SUDO_EDITOR nor VISUAL is set. MAIL Set to the mail spool of the target user when the -i option is specified, or when env_reset is enabled in sudoers (unless MAIL is present in the env_keep list). HOME Set to the home directory of the target user when the -i or -H options are specified, when the -s option is specified and set_home is set in sudoers, when always_set_home is enabled in sudoers, or when env_reset is enabled in sudoers and HOME is not present in the env_keep list. LOGNAME Set to the login name of the target user when the -i option is specified, when the set_logname option is enabled in sudoers, or when the env_reset option is enabled in sudoers (unless LOGNAME is present in the env_keep list). PATH May be overridden by the security policy. SHELL Used to determine shell to run with -s option. SUDO_ASKPASS Specifies the path to a helper program used to read the password if no terminal is available or if the -A option is specified. SUDO_COMMAND Set to the command run by sudo, including any args. The args are truncated at 4096 characters to prevent a potential execution error. SUDO_EDITOR Default editor to use in -e (sudoedit) mode. SUDO_GID Set to the group-ID of the user who invoked sudo. SUDO_PROMPT Used as the default password prompt unless the -p option was specified. SUDO_PS1 If set, PS1 will be set to its value for the program being run. SUDO_UID Set to the user-ID of the user who invoked sudo. SUDO_USER Set to the login name of the user who invoked sudo. USER Set to the same value as LOGNAME, described above. VISUAL Default editor to use in -e (sudoedit) mode if SUDO_EDITOR is not set. FILES top /etc/sudo.conf front-end configuration EXAMPLES top The following examples assume a properly configured security policy. To get a file listing of an unreadable directory: $ sudo ls /usr/local/protected To list the home directory of user yaz on a machine where the file system holding ~yaz is not exported as root: $ sudo -u yaz ls ~yaz To edit the index.html file as user www: $ sudoedit -u www ~www/htdocs/index.html To view system logs only accessible to root and users in the adm group: $ sudo -g adm more /var/log/syslog To run an editor as jim with a different primary group: $ sudoedit -u jim -g audio ~jim/sound.txt To shut down a machine: $ sudo shutdown -r +15 "quick reboot" To make a usage listing of the directories in the /home partition. The commands are run in a sub-shell to allow the cd command and file redirection to work. $ sudo sh -c "cd /home ; du -s * | sort -rn > USAGE" DIAGNOSTICS top Error messages produced by include: editing files in a writable directory is not permitted By default, sudoedit does not permit editing a file when any of the parent directories are writable by the invoking user. This avoids a race condition that could allow the user to overwrite an arbitrary file. See the sudoedit_checkdir option in sudoers(5) for more information. editing symbolic links is not permitted By default, sudoedit does not follow symbolic links when opening files. See the sudoedit_follow option in sudoers(5) for more information. effective uid is not 0, is sudo installed setuid root? was not run with root privileges. The binary must be owned by the root user and have the set-user-ID bit set. Also, it must not be located on a file system mounted with the nosuid option or on an NFS file system that maps uid 0 to an unprivileged uid. effective uid is not 0, is sudo on a file system with the 'nosuid' option set or an NFS file system without root privileges? was not run with root privileges. The binary has the proper owner and permissions but it still did not run with root privileges. The most common reason for this is that the file system the binary is located on is mounted with the nosuid option or it is an NFS file system that maps uid 0 to an unprivileged uid. fatal error, unable to load plugins An error occurred while loading or initializing the plugins specified in sudo.conf(5). invalid environment variable name One or more environment variable names specified via the -E option contained an equal sign (=). The arguments to the -E option should be environment variable names without an associated value. no password was provided When tried to read the password, it did not receive any characters. This may happen if no terminal is available (or the -S option is specified) and the standard input has been redirected from /dev/null. a terminal is required to read the password needs to read the password but there is no mechanism available for it to do so. A terminal is not present to read the password from, has not been configured to read from the standard input, the -S option was not used, and no askpass helper has been specified either via the sudo.conf(5) file or the SUDO_ASKPASS environment variable. no writable temporary directory found sudoedit was unable to find a usable temporary directory in which to store its intermediate files. The no new privileges flag is set, which prevents sudo from running as root. was run by a process that has the Linux no new privileges flag is set. This causes the set-user-ID bit to be ignored when running an executable, which will prevent from functioning. The most likely cause for this is running within a container that sets this flag. Check the documentation to see if it is possible to configure the container such that the flag is not set. sudo must be owned by uid 0 and have the setuid bit set was not run with root privileges. The binary does not have the correct owner or permissions. It must be owned by the root user and have the set-user-ID bit set. sudoedit is not supported on this platform It is only possible to run sudoedit on systems that support setting the effective user-ID. timed out reading password The user did not enter a password before the password timeout (5 minutes by default) expired. you do not exist in the passwd database Your user-ID does not appear in the system passwd database. you may not specify environment variables in edit mode It is only possible to specify environment variables when running a command. When editing a file, the editor is run with the user's environment unmodified. SEE ALSO top su(1), stat(2), login_cap(3), passwd(5), sudo.conf(5), sudo_plugin(5), sudoers(5), sudoers_timestamp(5), sudoreplay(8), visudo(8) HISTORY top See the HISTORY.md file in the distribution (https://www.sudo.ws/about/history/) for a brief history of sudo. AUTHORS top Many people have worked on over the years; this version consists of code written primarily by: Todd C. Miller See the CONTRIBUTORS.md file in the distribution (https://www.sudo.ws/about/contributors/) for an exhaustive list of people who have contributed to . CAVEATS top There is no easy way to prevent a user from gaining a root shell if that user is allowed to run arbitrary commands via . Also, many programs (such as editors) allow the user to run commands via shell escapes, thus avoiding sudo's checks. However, on most systems it is possible to prevent shell escapes with the sudoers(5) plugin's noexec functionality. It is not meaningful to run the cd command directly via sudo, e.g., $ sudo cd /usr/local/protected since when the command exits the parent process (your shell) will still be the same. The -D option can be used to run a command in a specific directory. Running shell scripts via can expose the same kernel bugs that make set-user-ID shell scripts unsafe on some operating systems (if your OS has a /dev/fd/ directory, set-user-ID shell scripts are generally safe). BUGS top If you believe you have found a bug in , you can submit a bug report at https://bugzilla.sudo.ws/ SUPPORT top Limited free support is available via the sudo-users mailing list, see https://www.sudo.ws/mailman/listinfo/sudo-users to subscribe or search the archives. DISCLAIMER top is provided AS IS and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. See the LICENSE.md file distributed with or https://www.sudo.ws/about/license/ for complete details. COLOPHON top This page is part of the sudo (execute a command as another user) project. Information about the project can be found at https://www.sudo.ws/. If you have a bug report for this manual page, see https://bugzilla.sudo.ws/. This page was obtained from the project's upstream Git repository https://github.com/sudo-project/sudo on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-12-21.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org Sudo 1.9.15p4 August 9, 2023 SUDO(8) Pages that refer to this page: homectl(1), journalctl(1), localectl(1), loginctl(1), machinectl(1), portablectl(1), setpriv(1), systemctl(1), systemd(1), systemd-analyze(1), systemd-ask-password(1), systemd-inhibit(1), systemd-nspawn(1), systemd-vmspawn(1), timedatectl(1), uid0(1), userdbctl(1), nsswitch.conf(5), credentials(7), systemd-tmpfiles(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: Copies 'libgtest_main.so' and 'libgtest.so' to '/usr/lib/', preserving all attributes, and copying symlinks as symlinks, without following in source files. Bash Command:<START>sudo cp -a libgtest_main.so libgtest.so /usr/lib/<END>
Copies 'src' to 'dest' preserving overwriting the existing files.
cp -n src dest
['cp']
Output a Bash command to accomplish the following task. Task: Copies 'src' to 'dest' preserving overwriting the existing files. Bash Command:<START>cp -n src dest<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies 'src' to 'dest' preserving overwriting the existing files. Bash Command:<START>cp -n src dest<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies 'src' to 'dest' preserving overwriting the existing files. Bash Command:<START>cp -n src dest<END>
Copies all files like "*FooBar*" under the current directory to the '~/foo/bar' directory.
find . -name '*FoooBar*' | sed 's/.*/"&"/' | xargs cp ~/foo/bar
['find', 'xargs', 'sed', 'cp']
Output a Bash command to accomplish the following task. Task: Copies all files like "*FooBar*" under the current directory to the '~/foo/bar' directory. Bash Command:<START>find . -name '*FoooBar*' | sed 's/.*/"&"/' | xargs cp ~/foo/bar<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # sed\n\n> Edit text in a scriptable manner.\n> See also: `awk`, `ed`.\n> More information: <https://www.gnu.org/software/sed/manual/sed.html>.\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed 's/apple/mango/g'`\n\n- Replace all `apple` (extended regex) occurrences with `APPLE` (extended regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed -E 's/(apple)/\U\1/g'`\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in a specific file and overwrite the original file in place:\n\n`sed -i 's/apple/mango/g' {{path/to/file}}`\n\n- Execute a specific script [f]ile and print the result to `stdout`:\n\n`{{command}} | sed -f {{path/to/script.sed}}`\n\n- Print just the first line to `stdout`:\n\n`{{command}} | sed -n '1p'`\n\n- [d]elete the first line of a file:\n\n`sed -i 1d {{path/to/file}}`\n\n- [i]nsert a new line at the first line of a file:\n\n`sed -i '1i\your new line text\' {{path/to/file}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies all files like "*FooBar*" under the current directory to the '~/foo/bar' directory. Bash Command:<START>find . -name '*FoooBar*' | sed 's/.*/"&"/' | xargs cp ~/foo/bar<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. sed(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sed(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND SYNOPSIS | REGULAR EXPRESSIONS | BUGS | AUTHOR | COPYRIGHT | SEE ALSO | COLOPHON SED(1) User Commands SED(1) NAME top sed - stream editor for filtering and transforming text SYNOPSIS top sed [-V] [--version] [--help] [-n] [--quiet] [--silent] [-l N] [--line-length=N] [-u] [--unbuffered] [-E] [-r] [--regexp-extended] [-e script] [--expression=script] [-f script-file] [--file=script-file] [script-if-no-other-script] [file...] DESCRIPTION top Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors. -n, --quiet, --silent suppress automatic printing of pattern space --debug annotate program execution -e script, --expression=script add the script to the commands to be executed -f script-file, --file=script-file add the contents of script-file to the commands to be executed --follow-symlinks follow symlinks when processing in place -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied) -l N, --line-length=N specify the desired line-wrap length for the `l' command --posix disable all GNU extensions. -E, -r, --regexp-extended use extended regular expressions in the script (for portability use POSIX -E). -s, --separate consider files as separate rather than as a single, continuous long stream. --sandbox operate in sandbox mode (disable e/r/w commands). -u, --unbuffered load minimal amounts of data from the input files and flush the output buffers more often -z, --null-data separate lines by NUL characters --help display this help and exit --version output version information and exit If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret. All remaining arguments are names of input files; if no input files are specified, then the standard input is read. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COMMAND SYNOPSIS top This is just a brief synopsis of sed commands to serve as a reminder to those who already know sed; other documentation (such as the texinfo document) must be consulted for fuller descriptions. Zero-address ``commands'' : label Label for b and t commands. #comment The comment extends until the next newline (or the end of a -e script fragment). } The closing bracket of a { } block. Zero- or One- address commands = Print the current line number. a \ text Append text, which has each embedded newline preceded by a backslash. i \ text Insert text, which has each embedded newline preceded by a backslash. q [exit-code] Immediately quit the sed script without processing any more input, except that if auto-print is not disabled the current pattern space will be printed. The exit code argument is a GNU extension. Q [exit-code] Immediately quit the sed script without processing any more input. This is a GNU extension. r filename Append text read from filename. R filename Append a line read from filename. Each invocation of the command reads a line from the file. This is a GNU extension. Commands which accept address ranges { Begin a block of commands (end with a }). b label Branch to label; if label is omitted, branch to end of script. c \ text Replace the selected lines with text, which has each embedded newline preceded by a backslash. d Delete pattern space. Start next cycle. D If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input. h H Copy/append pattern space to hold space. g G Copy/append hold space to pattern space. l List out the current line in a ``visually unambiguous'' form. l width List out the current line in a ``visually unambiguous'' form, breaking it at width characters. This is a GNU extension. n N Read/append the next line of input into the pattern space. p Print the current pattern space. P Print up to the first embedded newline of the current pattern space. s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp. t label If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. T label If no s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. This is a GNU extension. w filename Write the current pattern space to filename. W filename Write the first line of the current pattern space to filename. This is a GNU extension. x Exchange the contents of the hold and pattern spaces. y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding character in dest. Addresses Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address. Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched. After the address (or address-range), and before the command, a ! may be inserted, which specifies that the command shall only be executed if the address (or address-range) does not match. The following address types are supported: number Match only the specified line number (which increments cumulatively across files, unless the -s option is specified on the command line). first~step Match every step'th line starting with line first. For example, ``sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. first can be zero; in this case, sed operates as if it were equal to step. (This is an extension.) $ Match the last line. /regexp/ Match lines matching the regular expression regexp. Matching is performed on the current pattern space, which can be modified with commands such as ``s///''. \cregexpc Match lines matching the regular expression regexp. The c may be any character. GNU sed also supports some special 2-address forms: 0,addr2 Start out in "matched first address" state, until addr2 is found. This is similar to 1,addr2, except that if addr2 matches the very first line of input the 0,addr2 form will be at the end of its range, whereas the 1,addr2 form will still be at the beginning of its range. This works only when addr2 is a regular expression. addr1,+N Will match addr1 and the N lines following addr1. addr1,~N Will match addr1 and the lines following addr1 until the next line whose input line number is a multiple of N. REGULAR EXPRESSIONS top POSIX.2 BREs should be supported, but they aren't completely because of performance problems. The \n sequence in a regular expression matches the newline character, and similarly for \a, \t, and other sequences. The -E option switches to using extended regular expressions instead; it has been supported for years by GNU sed, and is now included in POSIX. BUGS top E-mail bug reports to bug-sed@gnu.org. Also, please include the output of ``sed --version'' in the body of your report if at all possible. AUTHOR top Written by Jay Fenlason, Tom Lord, Ken Pizzini, Paolo Bonzini, Jim Meyering, and Assaf Gordon. This sed program was built with SELinux support. SELinux is enabled on this system. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COPYRIGHT top Copyright 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top awk(1), ed(1), grep(1), tr(1), perlre(1), sed.info, any of various books on sed, the sed FAQ (http://sed.sf.net/grabbag/tutorials/sedfaq.txt), http://sed.sf.net/grabbag/. The full documentation for sed is maintained as a Texinfo manual. If the info and sed programs are properly installed at your site, the command info sed should give you access to the complete manual. COLOPHON top This page is part of the sed (stream-oriented editor) project. Information about the project can be found at http://www.gnu.org/software/sed/. If you have a bug report for this manual page, send it to bug-sed@gnu.org. This page was obtained from the tarball sed-4.9.tar.gz fetched from https://www.gnu.org/software/sed/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU sed 4.9 November 2022 SED(1) Pages that refer to this page: gawk(1), grep(1), iostat2pcp(1), pmdaopenmetrics(1), pmlogrewrite(1), sheet2pcp(1), cpuset(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies all files like "*FooBar*" under the current directory to the '~/foo/bar' directory. Bash Command:<START>find . -name '*FoooBar*' | sed 's/.*/"&"/' | xargs cp ~/foo/bar<END>
Copies all files like "*FooBar*" under the current directory to the '~/foobar' directory.
find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +
['find', 'cp']
Output a Bash command to accomplish the following task. Task: Copies all files like "*FooBar*" under the current directory to the '~/foobar' directory. Bash Command:<START>find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies all files like "*FooBar*" under the current directory to the '~/foobar' directory. Bash Command:<START>find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies all files like "*FooBar*" under the current directory to the '~/foobar' directory. Bash Command:<START>find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +<END>
Copies all files like "*foo*" under the current directory to the '/your/dest' directory.
find . -name "*foo*" | sed -e "s/'/\\\'/g" -e 's/"/\\"/g' -e 's/ /\\ /g' | xargs cp /your/dest
['find', 'xargs', 'sed', 'cp']
Output a Bash command to accomplish the following task. Task: Copies all files like "*foo*" under the current directory to the '/your/dest' directory. Bash Command:<START>find . -name "*foo*" | sed -e "s/'/\\\'/g" -e 's/"/\\"/g' -e 's/ /\\ /g' | xargs cp /your/dest<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # sed\n\n> Edit text in a scriptable manner.\n> See also: `awk`, `ed`.\n> More information: <https://www.gnu.org/software/sed/manual/sed.html>.\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed 's/apple/mango/g'`\n\n- Replace all `apple` (extended regex) occurrences with `APPLE` (extended regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed -E 's/(apple)/\U\1/g'`\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in a specific file and overwrite the original file in place:\n\n`sed -i 's/apple/mango/g' {{path/to/file}}`\n\n- Execute a specific script [f]ile and print the result to `stdout`:\n\n`{{command}} | sed -f {{path/to/script.sed}}`\n\n- Print just the first line to `stdout`:\n\n`{{command}} | sed -n '1p'`\n\n- [d]elete the first line of a file:\n\n`sed -i 1d {{path/to/file}}`\n\n- [i]nsert a new line at the first line of a file:\n\n`sed -i '1i\your new line text\' {{path/to/file}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies all files like "*foo*" under the current directory to the '/your/dest' directory. Bash Command:<START>find . -name "*foo*" | sed -e "s/'/\\\'/g" -e 's/"/\\"/g' -e 's/ /\\ /g' | xargs cp /your/dest<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. sed(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sed(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND SYNOPSIS | REGULAR EXPRESSIONS | BUGS | AUTHOR | COPYRIGHT | SEE ALSO | COLOPHON SED(1) User Commands SED(1) NAME top sed - stream editor for filtering and transforming text SYNOPSIS top sed [-V] [--version] [--help] [-n] [--quiet] [--silent] [-l N] [--line-length=N] [-u] [--unbuffered] [-E] [-r] [--regexp-extended] [-e script] [--expression=script] [-f script-file] [--file=script-file] [script-if-no-other-script] [file...] DESCRIPTION top Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors. -n, --quiet, --silent suppress automatic printing of pattern space --debug annotate program execution -e script, --expression=script add the script to the commands to be executed -f script-file, --file=script-file add the contents of script-file to the commands to be executed --follow-symlinks follow symlinks when processing in place -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied) -l N, --line-length=N specify the desired line-wrap length for the `l' command --posix disable all GNU extensions. -E, -r, --regexp-extended use extended regular expressions in the script (for portability use POSIX -E). -s, --separate consider files as separate rather than as a single, continuous long stream. --sandbox operate in sandbox mode (disable e/r/w commands). -u, --unbuffered load minimal amounts of data from the input files and flush the output buffers more often -z, --null-data separate lines by NUL characters --help display this help and exit --version output version information and exit If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret. All remaining arguments are names of input files; if no input files are specified, then the standard input is read. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COMMAND SYNOPSIS top This is just a brief synopsis of sed commands to serve as a reminder to those who already know sed; other documentation (such as the texinfo document) must be consulted for fuller descriptions. Zero-address ``commands'' : label Label for b and t commands. #comment The comment extends until the next newline (or the end of a -e script fragment). } The closing bracket of a { } block. Zero- or One- address commands = Print the current line number. a \ text Append text, which has each embedded newline preceded by a backslash. i \ text Insert text, which has each embedded newline preceded by a backslash. q [exit-code] Immediately quit the sed script without processing any more input, except that if auto-print is not disabled the current pattern space will be printed. The exit code argument is a GNU extension. Q [exit-code] Immediately quit the sed script without processing any more input. This is a GNU extension. r filename Append text read from filename. R filename Append a line read from filename. Each invocation of the command reads a line from the file. This is a GNU extension. Commands which accept address ranges { Begin a block of commands (end with a }). b label Branch to label; if label is omitted, branch to end of script. c \ text Replace the selected lines with text, which has each embedded newline preceded by a backslash. d Delete pattern space. Start next cycle. D If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input. h H Copy/append pattern space to hold space. g G Copy/append hold space to pattern space. l List out the current line in a ``visually unambiguous'' form. l width List out the current line in a ``visually unambiguous'' form, breaking it at width characters. This is a GNU extension. n N Read/append the next line of input into the pattern space. p Print the current pattern space. P Print up to the first embedded newline of the current pattern space. s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp. t label If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. T label If no s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. This is a GNU extension. w filename Write the current pattern space to filename. W filename Write the first line of the current pattern space to filename. This is a GNU extension. x Exchange the contents of the hold and pattern spaces. y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding character in dest. Addresses Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address. Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched. After the address (or address-range), and before the command, a ! may be inserted, which specifies that the command shall only be executed if the address (or address-range) does not match. The following address types are supported: number Match only the specified line number (which increments cumulatively across files, unless the -s option is specified on the command line). first~step Match every step'th line starting with line first. For example, ``sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. first can be zero; in this case, sed operates as if it were equal to step. (This is an extension.) $ Match the last line. /regexp/ Match lines matching the regular expression regexp. Matching is performed on the current pattern space, which can be modified with commands such as ``s///''. \cregexpc Match lines matching the regular expression regexp. The c may be any character. GNU sed also supports some special 2-address forms: 0,addr2 Start out in "matched first address" state, until addr2 is found. This is similar to 1,addr2, except that if addr2 matches the very first line of input the 0,addr2 form will be at the end of its range, whereas the 1,addr2 form will still be at the beginning of its range. This works only when addr2 is a regular expression. addr1,+N Will match addr1 and the N lines following addr1. addr1,~N Will match addr1 and the lines following addr1 until the next line whose input line number is a multiple of N. REGULAR EXPRESSIONS top POSIX.2 BREs should be supported, but they aren't completely because of performance problems. The \n sequence in a regular expression matches the newline character, and similarly for \a, \t, and other sequences. The -E option switches to using extended regular expressions instead; it has been supported for years by GNU sed, and is now included in POSIX. BUGS top E-mail bug reports to bug-sed@gnu.org. Also, please include the output of ``sed --version'' in the body of your report if at all possible. AUTHOR top Written by Jay Fenlason, Tom Lord, Ken Pizzini, Paolo Bonzini, Jim Meyering, and Assaf Gordon. This sed program was built with SELinux support. SELinux is enabled on this system. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COPYRIGHT top Copyright 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top awk(1), ed(1), grep(1), tr(1), perlre(1), sed.info, any of various books on sed, the sed FAQ (http://sed.sf.net/grabbag/tutorials/sedfaq.txt), http://sed.sf.net/grabbag/. The full documentation for sed is maintained as a Texinfo manual. If the info and sed programs are properly installed at your site, the command info sed should give you access to the complete manual. COLOPHON top This page is part of the sed (stream-oriented editor) project. Information about the project can be found at http://www.gnu.org/software/sed/. If you have a bug report for this manual page, send it to bug-sed@gnu.org. This page was obtained from the tarball sed-4.9.tar.gz fetched from https://www.gnu.org/software/sed/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU sed 4.9 November 2022 SED(1) Pages that refer to this page: gawk(1), grep(1), iostat2pcp(1), pmdaopenmetrics(1), pmlogrewrite(1), sheet2pcp(1), cpuset(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies all files like "*foo*" under the current directory to the '/your/dest' directory. Bash Command:<START>find . -name "*foo*" | sed -e "s/'/\\\'/g" -e 's/"/\\"/g' -e 's/ /\\ /g' | xargs cp /your/dest<END>
Copies all files like '*.txt' under the current directory to the './tmp/' directory.
find . -type f -name '*.txt' | sed 's/'"'"'/\'"'"'/g' | sed 's/.*/"&"/' | xargs -I{} cp -v {} ./tmp/
['find', 'xargs', 'sed', 'cp']
Output a Bash command to accomplish the following task. Task: Copies all files like '*.txt' under the current directory to the './tmp/' directory. Bash Command:<START>find . -type f -name '*.txt' | sed 's/'"'"'/\'"'"'/g' | sed 's/.*/"&"/' | xargs -I{} cp -v {} ./tmp/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # sed\n\n> Edit text in a scriptable manner.\n> See also: `awk`, `ed`.\n> More information: <https://www.gnu.org/software/sed/manual/sed.html>.\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed 's/apple/mango/g'`\n\n- Replace all `apple` (extended regex) occurrences with `APPLE` (extended regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed -E 's/(apple)/\U\1/g'`\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in a specific file and overwrite the original file in place:\n\n`sed -i 's/apple/mango/g' {{path/to/file}}`\n\n- Execute a specific script [f]ile and print the result to `stdout`:\n\n`{{command}} | sed -f {{path/to/script.sed}}`\n\n- Print just the first line to `stdout`:\n\n`{{command}} | sed -n '1p'`\n\n- [d]elete the first line of a file:\n\n`sed -i 1d {{path/to/file}}`\n\n- [i]nsert a new line at the first line of a file:\n\n`sed -i '1i\your new line text\' {{path/to/file}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies all files like '*.txt' under the current directory to the './tmp/' directory. Bash Command:<START>find . -type f -name '*.txt' | sed 's/'"'"'/\'"'"'/g' | sed 's/.*/"&"/' | xargs -I{} cp -v {} ./tmp/<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. sed(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sed(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND SYNOPSIS | REGULAR EXPRESSIONS | BUGS | AUTHOR | COPYRIGHT | SEE ALSO | COLOPHON SED(1) User Commands SED(1) NAME top sed - stream editor for filtering and transforming text SYNOPSIS top sed [-V] [--version] [--help] [-n] [--quiet] [--silent] [-l N] [--line-length=N] [-u] [--unbuffered] [-E] [-r] [--regexp-extended] [-e script] [--expression=script] [-f script-file] [--file=script-file] [script-if-no-other-script] [file...] DESCRIPTION top Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors. -n, --quiet, --silent suppress automatic printing of pattern space --debug annotate program execution -e script, --expression=script add the script to the commands to be executed -f script-file, --file=script-file add the contents of script-file to the commands to be executed --follow-symlinks follow symlinks when processing in place -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied) -l N, --line-length=N specify the desired line-wrap length for the `l' command --posix disable all GNU extensions. -E, -r, --regexp-extended use extended regular expressions in the script (for portability use POSIX -E). -s, --separate consider files as separate rather than as a single, continuous long stream. --sandbox operate in sandbox mode (disable e/r/w commands). -u, --unbuffered load minimal amounts of data from the input files and flush the output buffers more often -z, --null-data separate lines by NUL characters --help display this help and exit --version output version information and exit If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret. All remaining arguments are names of input files; if no input files are specified, then the standard input is read. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COMMAND SYNOPSIS top This is just a brief synopsis of sed commands to serve as a reminder to those who already know sed; other documentation (such as the texinfo document) must be consulted for fuller descriptions. Zero-address ``commands'' : label Label for b and t commands. #comment The comment extends until the next newline (or the end of a -e script fragment). } The closing bracket of a { } block. Zero- or One- address commands = Print the current line number. a \ text Append text, which has each embedded newline preceded by a backslash. i \ text Insert text, which has each embedded newline preceded by a backslash. q [exit-code] Immediately quit the sed script without processing any more input, except that if auto-print is not disabled the current pattern space will be printed. The exit code argument is a GNU extension. Q [exit-code] Immediately quit the sed script without processing any more input. This is a GNU extension. r filename Append text read from filename. R filename Append a line read from filename. Each invocation of the command reads a line from the file. This is a GNU extension. Commands which accept address ranges { Begin a block of commands (end with a }). b label Branch to label; if label is omitted, branch to end of script. c \ text Replace the selected lines with text, which has each embedded newline preceded by a backslash. d Delete pattern space. Start next cycle. D If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input. h H Copy/append pattern space to hold space. g G Copy/append hold space to pattern space. l List out the current line in a ``visually unambiguous'' form. l width List out the current line in a ``visually unambiguous'' form, breaking it at width characters. This is a GNU extension. n N Read/append the next line of input into the pattern space. p Print the current pattern space. P Print up to the first embedded newline of the current pattern space. s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp. t label If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. T label If no s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. This is a GNU extension. w filename Write the current pattern space to filename. W filename Write the first line of the current pattern space to filename. This is a GNU extension. x Exchange the contents of the hold and pattern spaces. y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding character in dest. Addresses Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address. Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched. After the address (or address-range), and before the command, a ! may be inserted, which specifies that the command shall only be executed if the address (or address-range) does not match. The following address types are supported: number Match only the specified line number (which increments cumulatively across files, unless the -s option is specified on the command line). first~step Match every step'th line starting with line first. For example, ``sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. first can be zero; in this case, sed operates as if it were equal to step. (This is an extension.) $ Match the last line. /regexp/ Match lines matching the regular expression regexp. Matching is performed on the current pattern space, which can be modified with commands such as ``s///''. \cregexpc Match lines matching the regular expression regexp. The c may be any character. GNU sed also supports some special 2-address forms: 0,addr2 Start out in "matched first address" state, until addr2 is found. This is similar to 1,addr2, except that if addr2 matches the very first line of input the 0,addr2 form will be at the end of its range, whereas the 1,addr2 form will still be at the beginning of its range. This works only when addr2 is a regular expression. addr1,+N Will match addr1 and the N lines following addr1. addr1,~N Will match addr1 and the lines following addr1 until the next line whose input line number is a multiple of N. REGULAR EXPRESSIONS top POSIX.2 BREs should be supported, but they aren't completely because of performance problems. The \n sequence in a regular expression matches the newline character, and similarly for \a, \t, and other sequences. The -E option switches to using extended regular expressions instead; it has been supported for years by GNU sed, and is now included in POSIX. BUGS top E-mail bug reports to bug-sed@gnu.org. Also, please include the output of ``sed --version'' in the body of your report if at all possible. AUTHOR top Written by Jay Fenlason, Tom Lord, Ken Pizzini, Paolo Bonzini, Jim Meyering, and Assaf Gordon. This sed program was built with SELinux support. SELinux is enabled on this system. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COPYRIGHT top Copyright 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top awk(1), ed(1), grep(1), tr(1), perlre(1), sed.info, any of various books on sed, the sed FAQ (http://sed.sf.net/grabbag/tutorials/sedfaq.txt), http://sed.sf.net/grabbag/. The full documentation for sed is maintained as a Texinfo manual. If the info and sed programs are properly installed at your site, the command info sed should give you access to the complete manual. COLOPHON top This page is part of the sed (stream-oriented editor) project. Information about the project can be found at http://www.gnu.org/software/sed/. If you have a bug report for this manual page, send it to bug-sed@gnu.org. This page was obtained from the tarball sed-4.9.tar.gz fetched from https://www.gnu.org/software/sed/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU sed 4.9 November 2022 SED(1) Pages that refer to this page: gawk(1), grep(1), iostat2pcp(1), pmdaopenmetrics(1), pmlogrewrite(1), sheet2pcp(1), cpuset(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies all files like '*.txt' under the current directory to the './tmp/' directory. Bash Command:<START>find . -type f -name '*.txt' | sed 's/'"'"'/\'"'"'/g' | sed 's/.*/"&"/' | xargs -I{} cp -v {} ./tmp/<END>
Copies all files like 'lib*.so' to '~/usr/gtest/lib/' directory.
cp lib*.so ~/usr/gtest/lib
['cp']
Output a Bash command to accomplish the following task. Task: Copies all files like 'lib*.so' to '~/usr/gtest/lib/' directory. Bash Command:<START>cp lib*.so ~/usr/gtest/lib<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies all files like 'lib*.so' to '~/usr/gtest/lib/' directory. Bash Command:<START>cp lib*.so ~/usr/gtest/lib<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies all files like 'lib*.so' to '~/usr/gtest/lib/' directory. Bash Command:<START>cp lib*.so ~/usr/gtest/lib<END>
Copies all files under the current directory but ones with '*/not-from-here/*' in path to the '/dest/' directory.
find . -type f -not -iname '*/not-from-here/*' -exec cp '{}' '/dest/{}' ';'
['find', 'cp']
Output a Bash command to accomplish the following task. Task: Copies all files under the current directory but ones with '*/not-from-here/*' in path to the '/dest/' directory. Bash Command:<START>find . -type f -not -iname '*/not-from-here/*' -exec cp '{}' '/dest/{}' ';'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies all files under the current directory but ones with '*/not-from-here/*' in path to the '/dest/' directory. Bash Command:<START>find . -type f -not -iname '*/not-from-here/*' -exec cp '{}' '/dest/{}' ';'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies all files under the current directory but ones with '*/not-from-here/*' in path to the '/dest/' directory. Bash Command:<START>find . -type f -not -iname '*/not-from-here/*' -exec cp '{}' '/dest/{}' ';'<END>
Copies all files under the current directory like any-cased '*foobar*' to the '~/foo/bar' directory.
find . -iname "*foobar*" -exec cp "{}" ~/foo/bar \;
['find', 'cp']
Output a Bash command to accomplish the following task. Task: Copies all files under the current directory like any-cased '*foobar*' to the '~/foo/bar' directory. Bash Command:<START>find . -iname "*foobar*" -exec cp "{}" ~/foo/bar \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies all files under the current directory like any-cased '*foobar*' to the '~/foo/bar' directory. Bash Command:<START>find . -iname "*foobar*" -exec cp "{}" ~/foo/bar \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies all files under the current directory like any-cased '*foobar*' to the '~/foo/bar' directory. Bash Command:<START>find . -iname "*foobar*" -exec cp "{}" ~/foo/bar \;<END>
Copies all files with "FooBar" in the path under the current directory to the '~/foo/bar' directory.
find . | grep FooBar | xargs -I{} cp {} ~/foo/bar
['find', 'xargs', 'grep', 'cp']
Output a Bash command to accomplish the following task. Task: Copies all files with "FooBar" in the path under the current directory to the '~/foo/bar' directory. Bash Command:<START>find . | grep FooBar | xargs -I{} cp {} ~/foo/bar<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 # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies all files with "FooBar" in the path under the current directory to the '~/foo/bar' directory. Bash Command:<START>find . | grep FooBar | xargs -I{} cp {} ~/foo/bar<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. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies all files with "FooBar" in the path under the current directory to the '~/foo/bar' directory. Bash Command:<START>find . | grep FooBar | xargs -I{} cp {} ~/foo/bar<END>
Copies defined file to the target folder without overwriting existing files.
cp -n
['cp']
Output a Bash command to accomplish the following task. Task: Copies defined file to the target folder without overwriting existing files. Bash Command:<START>cp -n<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies defined file to the target folder without overwriting existing files. Bash Command:<START>cp -n<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies defined file to the target folder without overwriting existing files. Bash Command:<START>cp -n<END>
Copies file '/boot/config-`uname -r`' to the '.config', printing info message and prompting before owerwriting files.
cp -vi /boot/config-`uname -r` .config
['cp', 'uname']
Output a Bash command to accomplish the following task. Task: Copies file '/boot/config-`uname -r`' to the '.config', printing info message and prompting before owerwriting files. Bash Command:<START>cp -vi /boot/config-`uname -r` .config<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n # 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: Copies file '/boot/config-`uname -r`' to the '.config', printing info message and prompting before owerwriting files. Bash Command:<START>cp -vi /boot/config-`uname -r` .config<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. 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: Copies file '/boot/config-`uname -r`' to the '.config', printing info message and prompting before owerwriting files. Bash Command:<START>cp -vi /boot/config-`uname -r` .config<END>
Copies file 'file.dat' to each top-level directory in the current directory.
ls | xargs -n 1 cp -i file.dat
['ls', 'xargs', 'cp']
Output a Bash command to accomplish the following task. Task: Copies file 'file.dat' to each top-level directory in the current directory. Bash Command:<START>ls | xargs -n 1 cp -i file.dat<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 # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies file 'file.dat' to each top-level directory in the current directory. Bash Command:<START>ls | xargs -n 1 cp -i file.dat<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. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies file 'file.dat' to each top-level directory in the current directory. Bash Command:<START>ls | xargs -n 1 cp -i file.dat<END>
Copies file 'file.txt' to each top-level directory in the current directory.
ls -d */ | xargs -iA cp file.txt A
['ls', 'xargs', 'cp']
Output a Bash command to accomplish the following task. Task: Copies file 'file.txt' to each top-level directory in the current directory. Bash Command:<START>ls -d */ | xargs -iA cp file.txt A<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 # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies file 'file.txt' to each top-level directory in the current directory. Bash Command:<START>ls -d */ | xargs -iA cp file.txt A<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. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies file 'file.txt' to each top-level directory in the current directory. Bash Command:<START>ls -d */ | xargs -iA cp file.txt A<END>
Copies file 'file1' to each of directories 'dir1', 'dir2', 'dir3'.
echo dir1 dir2 dir3 | xargs -n 1 cp file1
['xargs', 'cp', 'echo']
Output a Bash command to accomplish the following task. Task: Copies file 'file1' to each of directories 'dir1', 'dir2', 'dir3'. Bash Command:<START>echo dir1 dir2 dir3 | xargs -n 1 cp file1<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n # 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: Copies file 'file1' to each of directories 'dir1', 'dir2', 'dir3'. Bash Command:<START>echo dir1 dir2 dir3 | xargs -n 1 cp file1<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. 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: Copies file 'file1' to each of directories 'dir1', 'dir2', 'dir3'. Bash Command:<START>echo dir1 dir2 dir3 | xargs -n 1 cp file1<END>
Copies file 'fileName.txt' to each of directories listed in the 'allFolders.txt' list.
cat allFolders.txt | xargs -n 1 cp fileName.txt
['cat', 'xargs', 'cp']
Output a Bash command to accomplish the following task. Task: Copies file 'fileName.txt' to each of directories listed in the 'allFolders.txt' list. Bash Command:<START>cat allFolders.txt | xargs -n 1 cp fileName.txt<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 # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies file 'fileName.txt' to each of directories listed in the 'allFolders.txt' list. Bash Command:<START>cat allFolders.txt | xargs -n 1 cp fileName.txt<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. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies file 'fileName.txt' to each of directories listed in the 'allFolders.txt' list. Bash Command:<START>cat allFolders.txt | xargs -n 1 cp fileName.txt<END>
Copies file 'index.html' to each top-level directory in the current directory beginning with 'd'.
find . -mindepth 1 -maxdepth 1 -type d| grep \/a |xargs -n 1 cp -i index.html
['find', 'xargs', 'grep', 'cp']
Output a Bash command to accomplish the following task. Task: Copies file 'index.html' to each top-level directory in the current directory beginning with 'd'. Bash Command:<START>find . -mindepth 1 -maxdepth 1 -type d| grep \/a |xargs -n 1 cp -i index.html<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 # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies file 'index.html' to each top-level directory in the current directory beginning with 'd'. Bash Command:<START>find . -mindepth 1 -maxdepth 1 -type d| grep \/a |xargs -n 1 cp -i index.html<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. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies file 'index.html' to each top-level directory in the current directory beginning with 'd'. Bash Command:<START>find . -mindepth 1 -maxdepth 1 -type d| grep \/a |xargs -n 1 cp -i index.html<END>
Copies file 'index.html' to each top-level directory in the current directory.
find . -mindepth 1 -maxdepth 1 -type d| xargs -n 1 cp -i index.html
['find', 'xargs', 'cp']
Output a Bash command to accomplish the following task. Task: Copies file 'index.html' to each top-level directory in the current directory. Bash Command:<START>find . -mindepth 1 -maxdepth 1 -type d| xargs -n 1 cp -i index.html<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies file 'index.html' to each top-level directory in the current directory. Bash Command:<START>find . -mindepth 1 -maxdepth 1 -type d| xargs -n 1 cp -i index.html<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified immediately after the last path name. The five `real' options -H, -L, -P, -D and -O must appear before the first path name, if at all. A double dash -- could theoretically be used to signal that any remaining arguments are not options, but this does not really work due to the way find determines the end of the following path arguments: it does that by reading until an expression argument comes (which also starts with a `-'). Now, if a path argument would start with a `-', then find would treat it as expression argument instead. Thus, to ensure that all start points are taken as such, and especially to prevent that wildcard patterns expanded by the calling shell are not mistakenly treated as expression arguments, it is generally safer to prefix wildcards or dubious path names with either `./' or to use absolute path names starting with '/'. Alternatively, it is generally safe though non-portable to use the GNU option -files0-from to pass arbitrary starting points to find. -P Never follow symbolic links. This is the default behaviour. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched. When the -L option is in effect, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself (unless the symbolic link is broken). Actions that can cause symbolic links to become broken while find is executing (for example -delete) can give rise to confusing behaviour. Using -L causes the -lname and -ilname predicates always to return false. -H Do not follow symbolic links, except while processing the command line arguments. When find examines or prints information about files, the information used shall be taken from the properties of the symbolic link itself. The only exception to this behaviour is when a file specified on the command line is a symbolic link, and the link can be resolved. For that situation, the information used is taken from whatever the link points to (that is, the link is followed). The information about the link itself is used as a fallback if the file pointed to by the symbolic link cannot be examined. If -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the others; the last one appearing on the command line takes effect. Since it is the default, the -P option should be considered to be in effect unless either -H or -L is specified. GNU find frequently stats files during the processing of the command line itself, before any searching has begun. These options also affect how those arguments are processed. Specifically, there are a number of tests that compare files listed on the command line against a file we are currently considering. In each case, the file specified on the command line will have been examined and some of its properties will have been saved. If the named file is in fact a symbolic link, and the -P option is in effect (or if neither -H nor -L were specified), the information used for the comparison will be taken from the properties of the symbolic link. Otherwise, it will be taken from the properties of the file the link points to. If find cannot follow the link (for example because it has insufficient privileges or the link points to a nonexistent file) the properties of the link itself will be used. When the -H or -L options are in effect, any symbolic links listed as the argument of -newer will be dereferenced, and the timestamp will be taken from the file to which the symbolic link points. The same consideration applies to -newerXY, -anewer and -cnewer. The -follow option has a similar effect to -L, though it takes effect at the point where it appears (that is, if -L is not used but -follow is, any symbolic links appearing after -follow on the command line will be dereferenced, and those before it will not). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. rates Prints a summary indicating how often each predicate succeeded or failed. search Navigate the directory tree verbosely. stat Print messages as files are examined with the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser is enabled. The order of tests is modified so that cheap (i.e. fast) tests are performed first and more expensive ones are performed later, if necessary. Within each cost band, predicates are evaluated earlier or later according to whether they are likely to succeed or not. For -o, predicates which are likely to succeed are evaluated earlier, and for -a, predicates which are likely to fail are evaluated earlier. The cost-based optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, robust and effective may be enabled at lower optimisation levels over time. However, the default behaviour (i.e. optimisation level 1) will not be changed in the 4.3.x release series. The findutils test suite runs all the tests on find at each optimisation level and ensures that the result is the same. EXPRESSION top The part of the command line after the list of starting points is the expression. This is a kind of query specification describing how we match files and what we do with the files that were matched. An expression is composed of a sequence of things: Tests Tests return a true or false value, usually on the basis of some property of a file we are considering. The -empty test for example is true only when the current file is empty. Actions Actions have side effects (such as printing something on the standard output) and return either true or false, usually based on whether or not they are successful. The -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should be specified on the command-line after the list of start points, just before the first test, positional option or action. If you specify a global option in some other place, find will issue a warning message explaining that this can be confusing. The global options occur after the list of start points, and so are not the same kind of option as -L, for example. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be issued. This also applies to files or directories whose names are given on the command line. This option takes effect at the time the command line is read, which means that you cannot search one part of the filesystem with this option on and part of it with this option off (if you need to do that, you will need to issue two find commands instead, one with the option and one without it). Furthermore, find with the -ignore_readdir_race option will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, and the return code of the -delete action will be true. -maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the starting-points. Using -maxdepth 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison between the file currently being examined and some reference file specified on the command line. When these tests are used, the interpretation of the reference file is determined by the options -H, -L and -P and any previous -follow, but the reference file is only examined once, at the time the command line is parsed. If the reference file cannot be examined (for example, the stat(2) system call fails for it), an error message is issued, and find exits with a nonzero status. A numeric argument n can be specified to tests (like -amin, -mtime, -gid, -inum, -links, -size, -uid and -used) as +n for greater than n, -n for less than n, n for exactly n. Supported tests: -amin n File was last accessed less than, more than or exactly n minutes ago. -anewer reference Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -mmin n File's data was last modified less than, more than or exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. For this reason -exec my- command ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir. The same applies to having entries in PATH which are empty or which are not absolute directory names. If any invocation with the `+' form returns a non-zero value as exit status, then find returns a non-zero exit status. If find encounters an error, this can sometimes cause an immediate exit, so some pending commands may not be run at all. The result of the action depends on whether the + or the ; variant is being used; -execdir command {} + always returns true, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are handled specially; they refer to the standard output and standard error output, respectively. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (Sunday..Saturday) b locale's abbreviated month name (Jan..Dec) B locale's full month name, variable length (January..December) c locale's date and time (Sat Nov 04 12:02:33 EST 1989). The format is the same as for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of directories which contain entries which are hard links to an ancestor will often be lower than they otherwise should be. This can mean that GNU find will sometimes optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic message. Although this behaviour may be somewhat confusing, it is unlikely that anybody actually depends on this behaviour. If the leaf optimisation has been turned off with -noleaf, the directory entry will always be examined and the diagnostic message will be issued where it is appropriate. Symbolic links cannot be used to create filesystem cycles as such, but if the -L option or the -follow option is in use, a diagnostic message is issued when find encounters a loop of symbolic links. As with loops containing hard links, the leaf optimisation will often mean that find knows that it doesn't need to call stat() or chdir() on the symbolic link, so this diagnostic is frequently not necessary. The -d option is supported for compatibility with various BSD systems, but you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also affect which characters are considered to be unprintable when filenames are printed; see the section UNUSUAL FILENAMES. LC_MESSAGES Determines the locale to be used for internationalised messages. If the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are diagnostics and must result in a non-zero exit status. When POSIXLY_CORRECT is not set, -perm +zzz is treated just like -perm /zzz if +zzz is not a valid symbolic mode. When POSIXLY_CORRECT is set, such constructs are treated as an error. When POSIXLY_CORRECT is set, the response to the prompt made by the -ok action is interpreted according to the system's message catalogue, as opposed to according to find's own message translations. TZ Affects the time zone used for some of the time-related format directives of -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-execdir ... +` syntax for performance and security reasons. Traversing the filesystem just once - for 2 different actions Traverse the filesystem just once, listing set-user-ID files and directories into /root/suid.txt and large files into /root/big.txt. $ find / \ \( -perm -4000 -fprintf /root/suid.txt '%#m %u %p\n' \) , \ \( -size +100M -fprintf /root/big.txt '%-10s %p\n' \) This example uses the line-continuation character '\' on the first two lines to instruct the shell to continue reading the command on the next line. Searching files by age Search for files in your home directory which have been modified in the last twenty-four hours. $ find $HOME -mtime 0 This command works this way because the time since each file was last modified is divided by 24 hours and any remainder is discarded. That means that to match -mtime 0, a file will have to have a modification in the past which is less than 24 hours ago. Searching files by permissions Search for files which are executable but not readable. $ find /sbin /usr/sbin -executable \! -readable -print Search for files which have read and write permission for their owner, and group, but which other users can read but not write to. $ find . -perm 664 Files which meet these criteria but have other permissions bits set (for example if someone can execute the file) will not be matched. Search for files which have read and write permission for their owner and group, and which other users can read, without regard to the presence of any extra permission bits (for example the executable bit). $ find . -perm -664 This will match a file which has mode 0777, for example. Search for files which are writable by somebody (their owner, or their group, or anybody else). $ find . -perm /222 Search for files which are writable by either their owner or their group. $ find . -perm /220 $ find . -perm /u+w,g+w $ find . -perm /u=w,g=w All three of these commands do the same thing, but the first one uses the octal representation of the file mode, and the other two use the symbolic form. The files don't have to be writable by both the owner and group to be matched; either will do. Search for files which are writable by both their owner and their group. $ find . -perm -220 $ find . -perm -g+w,u+w Both these commands do the same thing. A more elaborate search on permissions. $ find . -perm -444 -perm /222 \! -perm /111 $ find . -perm -a+r -perm /a+w \! -perm /a+x These two commands both search for files that are readable for everybody (-perm -444 or -perm -a+r), have at least one write bit set (-perm /222 or -perm /a+w) but are not executable for anybody (! -perm /111 or ! -perm /a+x respectively). Pruning - omitting files and subdirectories Copy the contents of /source-dir to /dest-dir, but omit files and directories named .snapshot (and anything in them). It also omits files or directories whose name ends in `~', but not their contents. $ cd /source-dir $ find . -name .snapshot -prune -o \( \! -name '*~' -print0 \) \ | cpio -pmd0 /dest-dir The construct -prune -o \( ... -print0 \) is quite common. The idea here is that the expression before -prune matches things which are to be pruned. However, the -prune action itself returns true, so the following -o ensures that the right hand side is evaluated only for those directories which didn't get pruned (the contents of the pruned directories are not even visited, so their contents are irrelevant). The expression on the right hand side of the -o is in parentheses only for clarity. It emphasises that the -print0 action takes place only for things that didn't have -prune applied to them. Because the default `and' condition between tests binds more tightly than -o, this is the default anyway, but the parentheses help to show what is going on. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the directory /tmp passing these types as a comma-separated list (GNU extension), which is otherwise equivalent to the longer, yet more portable: $ find /tmp \( -type f -o -type d -o -type l \) Search for files with the particular name needle and stop immediately when we find the first one. $ find / -name needle -print -quit Demonstrate the interpretation of the %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top find exits with status 0 if all files are processed successfully, greater than 0 if errors occur. This is deliberately a very broad description, but if the return value is non-zero, you should not rely on the correctness of the results of find. When some error occurs, find may stop immediately, without completing all the actions specified. For example, some starting points may not have been examined or some pending program invocations for -exec ... {} + or -execdir ... {} + may not have been performed. HISTORY top A find program appeared in Version 5 Unix as part of the Programmer's Workbench project and was written by Dick Haight. Doug McIlroy's A Research UNIX Reader: Annotated Excerpts from the Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. GNU find was originally written by Eric Decker, with enhancements by David MacKenzie, Jay Plett, and Tim Wood. The idea for find -print0 and xargs -0 came from Dan Bernstein. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the resulting file names in the command line to find like this: find . -name frcode.c locate.c word_io.c -print That command is of course not going to work, because the -name predicate allows exactly only one pattern as argument. Instead of doing things this way, you should enclose the pattern in quotes or escape the wildcard, thus allowing find to use the pattern with the wildcard during the search for file name matching instead of file names expanded by the parent shell: $ find . -name '*.c' -print $ find . -name \*.c -print BUGS top There are security problems inherent in the behaviour that the POSIX standard specifies for find, which therefore cannot be fixed. For example, the -exec action is inherently insecure, and -execdir should be used instead. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 1990-2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top chmod(1), locate(1), ls(1), updatedb(1), xargs(1), lstat(2), stat(2), ctime(3) fnmatch(3), printf(3), strftime(3), locatedb(5), regex(7) Full documentation <https://www.gnu.org/software/findutils/find> or available locally via: info find COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top GNU findutils online help: <https://www.gnu.org/software/findutils/#get-help> Report any translation bugs to <https://translationproject.org/team/> Report any other issue via the form at the GNU Savannah bug tracker: <https://savannah.gnu.org/bugs/?group=findutils> General topics about the GNU findutils package are discussed at the bug-findutils mailing list: <https://lists.gnu.org/mailman/listinfo/bug-findutils> COPYRIGHT top Copyright 19902023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies file 'index.html' to each top-level directory in the current directory. Bash Command:<START>find . -mindepth 1 -maxdepth 1 -type d| xargs -n 1 cp -i index.html<END>
Copies file 'test' to each of directories like './fs*/*'.
echo ./fs*/* | xargs -n 1 cp test
['xargs', 'test', 'cp', 'echo']
Output a Bash command to accomplish the following task. Task: Copies file 'test' to each of directories like './fs*/*'. Bash Command:<START>echo ./fs*/* | xargs -n 1 cp test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # 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 # test\n\n> Check file types and compare values.\n> Returns 0 if the condition evaluates to true, 1 if it evaluates to false.\n> More information: <https://www.gnu.org/software/coreutils/test>.\n\n- Test if a given variable is equal to a given string:\n\n`test "{{$MY_VAR}}" = "{{/bin/zsh}}"`\n\n- Test if a given variable is empty:\n\n`test -z "{{$GIT_BRANCH}}"`\n\n- Test if a file exists:\n\n`test -f "{{path/to/file_or_directory}}"`\n\n- Test if a directory does not exist:\n\n`test ! -d "{{path/to/directory}}"`\n\n- If A is true, then do B, or C in the case of an error (notice that C may run even if A fails):\n\n`test {{condition}} && {{echo "true"}} || {{echo "false"}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n # 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: Copies file 'test' to each of directories like './fs*/*'. Bash Command:<START>echo ./fs*/* | xargs -n 1 cp test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: 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. test(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training test(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TEST(1) User Commands TEST(1) NAME top test - check file types and compare values SYNOPSIS top test EXPRESSION test [ EXPRESSION ] [ ] [ OPTION DESCRIPTION top Exit with the status determined by EXPRESSION. --help display this help and exit --version output version information and exit An omitted EXPRESSION defaults to false. Otherwise, EXPRESSION is true or false and sets exit status. It is one of: ( EXPRESSION ) EXPRESSION is true ! EXPRESSION EXPRESSION is false EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true -n STRING the length of STRING is nonzero STRING equivalent to -n STRING -z STRING the length of STRING is zero STRING1 = STRING2 the strings are equal STRING1 != STRING2 the strings are not equal INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2 FILE1 -ot FILE2 FILE1 is older than FILE2 -b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -G FILE FILE exists and is owned by the effective group ID -h FILE FILE exists and is a symbolic link (same as -L) -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -N FILE FILE exists and has been modified since it was last read -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and the user has read access -s FILE FILE exists and has a size greater than zero -S FILE FILE exists and is a socket -t FD file descriptor FD is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and the user has write access -x FILE FILE exists and the user has execute (or search) access Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of STRING. NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead. NOTE: [ honors the --help and --version options, but test does not. test treats each of those as it treats any other nonempty STRING. NOTE: your shell may have its own version of test and/or [, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. AUTHOR top Written by Kevin Braunsdorf and Matthew Bradburn. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top access(2) Full documentation <https://www.gnu.org/software/coreutils/test> or available locally via: info '(coreutils) test invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 TEST(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. 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: Copies file 'test' to each of directories like './fs*/*'. Bash Command:<START>echo ./fs*/* | xargs -n 1 cp test<END>
Copies files 'src/prog.js' and 'images/icon.jpg' with fully-defined path to '/tmp/package' directory.
cp --parents src/prog.js images/icon.jpg /tmp/package
['cp']
Output a Bash command to accomplish the following task. Task: Copies files 'src/prog.js' and 'images/icon.jpg' with fully-defined path to '/tmp/package' directory. Bash Command:<START>cp --parents src/prog.js images/icon.jpg /tmp/package<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies files 'src/prog.js' and 'images/icon.jpg' with fully-defined path to '/tmp/package' directory. Bash Command:<START>cp --parents src/prog.js images/icon.jpg /tmp/package<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies files 'src/prog.js' and 'images/icon.jpg' with fully-defined path to '/tmp/package' directory. Bash Command:<START>cp --parents src/prog.js images/icon.jpg /tmp/package<END>
Copies newest file under the current folder to the '/tmp/'
cp $(ls -1tr * | tail -1) /tmp/
['ls', 'tail', 'cp']
Output a Bash command to accomplish the following task. Task: Copies newest file under the current folder to the '/tmp/' Bash Command:<START>cp $(ls -1tr * | tail -1) /tmp/<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 # 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 # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: Copies newest file under the current folder to the '/tmp/' Bash Command:<START>cp $(ls -1tr * | tail -1) /tmp/<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. 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. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: Copies newest file under the current folder to the '/tmp/' Bash Command:<START>cp $(ls -1tr * | tail -1) /tmp/<END>
Copy "*.cc", "*.h", and "SConstruct" to "rsync://localhost:40001/bledge_ce" using blocking IO
rsync --blocking-io *.cc *.h SConstruct rsync://localhost:40001/bledge_ce
['rsync']
Output a Bash command to accomplish the following task. Task: Copy "*.cc", "*.h", and "SConstruct" to "rsync://localhost:40001/bledge_ce" using blocking IO Bash Command:<START>rsync --blocking-io *.cc *.h SConstruct rsync://localhost:40001/bledge_ce<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # rsync\n\n> Transfer files either to or from a remote host (but not between two remote hosts), by default using SSH.\n> To specify a remote path, use `user@host:path/to/file_or_directory`.\n> More information: <https://download.samba.org/pub/rsync/rsync.1>.\n\n- Transfer a file:\n\n`rsync {{path/to/source}} {{path/to/destination}}`\n\n- Use archive mode (recursively copy directories, copy symlinks without resolving, and preserve permissions, ownership and modification times):\n\n`rsync --archive {{path/to/source}} {{path/to/destination}}`\n\n- Compress the data as it is sent to the destination, display verbose and human-readable progress, and keep partially transferred files if interrupted:\n\n`rsync --compress --verbose --human-readable --partial --progress {{path/to/source}} {{path/to/destination}}`\n\n- Recursively copy directories:\n\n`rsync --recursive {{path/to/source}} {{path/to/destination}}`\n\n- Transfer directory contents, but not the directory itself:\n\n`rsync --recursive {{path/to/source}}/ {{path/to/destination}}`\n\n- Use archive mode, resolve symlinks and skip files that are newer on the destination:\n\n`rsync --archive --update --copy-links {{path/to/source}} {{path/to/destination}}`\n\n- Transfer a directory to a remote host running `rsyncd` and delete files on the destination that do not exist on the source:\n\n`rsync --recursive --delete rsync://{{host}}:{{path/to/source}} {{path/to/destination}}`\n\n- Transfer a file over SSH using a different port than the default (22) and show global progress:\n\n`rsync --rsh 'ssh -p {{port}}' --info=progress2 {{host}}:{{path/to/source}} {{path/to/destination}}`\n Task: Copy "*.cc", "*.h", and "SConstruct" to "rsync://localhost:40001/bledge_ce" using blocking IO Bash Command:<START>rsync --blocking-io *.cc *.h SConstruct rsync://localhost:40001/bledge_ce<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: rsync(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rsync(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | GENERAL | SETUP | USAGE | COPYING TO A DIFFERENT NAME | SORTED TRANSFER ORDER | MULTI-HOST SECURITY | ADVANCED USAGE | CONNECTING TO AN RSYNC DAEMON | USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION | STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS | EXAMPLES | OPTION SUMMARY | OPTIONS | DAEMON OPTIONS | FILTER RULES | TRANSFER RULES | BATCH MODE | SYMBOLIC LINKS | DIAGNOSTICS | EXIT VALUES | ENVIRONMENT VARIABLES | FILES | SEE ALSO | BUGS | VERSION | INTERNAL OPTIONS | CREDITS | THANKS | AUTHOR | COLOPHON rsync(1) User Commands rsync(1) NAME top rsync - a fast, versatile, remote (and local) file-copying tool SYNOPSIS top Local: rsync [OPTION...] SRC... [DEST] Access via remote shell: Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST] Push: rsync [OPTION...] SRC... [USER@]HOST:DEST Access via rsync daemon: Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST] rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST] Push: rsync [OPTION...] SRC... [USER@]HOST::DEST rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST) Usages with just one SRC arg and no DEST arg will list the source files instead of copying. The online version of this manpage (that includes cross-linking of topics) is available at https://download.samba.org/pub/rsync/rsync.1. DESCRIPTION top Rsync is a fast and extraordinarily versatile file copying tool. It can copy locally, to/from another host over any remote shell, or to/from a remote rsync daemon. It offers a large number of options that control every aspect of its behavior and permit very flexible specification of the set of files to be copied. It is famous for its delta-transfer algorithm, which reduces the amount of data sent over the network by sending only the differences between the source files and the existing files in the destination. Rsync is widely used for backups and mirroring and as an improved copy command for everyday use. Rsync finds files that need to be transferred using a "quick check" algorithm (by default) that looks for files that have changed in size or in last-modified time. Any changes in the other preserved attributes (as requested by options) are made on the destination file directly when the quick check indicates that the file's data does not need to be updated. Some of the additional features of rsync are: o support for copying links, devices, owners, groups, and permissions o exclude and exclude-from options similar to GNU tar o a CVS exclude mode for ignoring the same files that CVS would ignore o can use any transparent remote shell, including ssh or rsh o does not require super-user privileges o pipelining of file transfers to minimize latency costs o support for anonymous or authenticated rsync daemons (ideal for mirroring) GENERAL top Rsync copies files either to or from a remote host, or locally on the current host (it does not support copying files between two remote hosts). There are two different ways for rsync to contact a remote system: using a remote-shell program as the transport (such as ssh or rsh) or contacting an rsync daemon directly via TCP. The remote-shell transport is used whenever the source or destination path contains a single colon (:) separator after a host specification. Contacting an rsync daemon directly happens when the source or destination path contains a double colon (::) separator after a host specification, OR when an rsync:// URL is specified (see also the USING RSYNC-DAEMON FEATURES VIA A REMOTE- SHELL CONNECTION section for an exception to this latter rule). As a special case, if a single source arg is specified without a destination, the files are listed in an output format similar to "ls -l". As expected, if neither the source or destination path specify a remote host, the copy occurs locally (see also the --list-only option). Rsync refers to the local side as the client and the remote side as the server. Don't confuse server with an rsync daemon. A daemon is always a server, but a server can be either a daemon or a remote-shell spawned process. SETUP top See the file README.md for installation instructions. Once installed, you can use rsync to any machine that you can access via a remote shell (as well as some that you can access using the rsync daemon-mode protocol). For remote transfers, a modern rsync uses ssh for its communications, but it may have been configured to use a different remote shell by default, such as rsh or remsh. You can also specify any remote shell you like, either by using the -e command line option, or by setting the RSYNC_RSH environment variable. Note that rsync must be installed on both the source and destination machines. USAGE top You use rsync in the same way you use rcp. You must specify a source and a destination, one of which may be remote. Perhaps the best way to explain the syntax is with some examples: rsync -t *.c foo:src/ This would transfer all files matching the pattern *.c from the current directory to the directory src on the machine foo. If any of the files already exist on the remote system then the rsync remote-update protocol is used to update the file by sending only the differences in the data. Note that the expansion of wildcards on the command-line (*.c) into a list of files is handled by the shell before it runs rsync and not by rsync itself (exactly the same as all other Posix-style programs). rsync -avz foo:src/bar /data/tmp This would recursively transfer all files from the directory src/bar on the machine foo into the /data/tmp/bar directory on the local machine. The files are transferred in archive mode, which ensures that symbolic links, devices, attributes, permissions, ownerships, etc. are preserved in the transfer. Additionally, compression will be used to reduce the size of data portions of the transfer. rsync -avz foo:src/bar/ /data/tmp A trailing slash on the source changes this behavior to avoid creating an additional directory level at the destination. You can think of a trailing / on a source as meaning "copy the contents of this directory" as opposed to "copy the directory by name", but in both cases the attributes of the containing directory are transferred to the containing directory on the destination. In other words, each of the following commands copies the files in the same way, including their setting of the attributes of /dest/foo: rsync -av /src/foo /dest rsync -av /src/foo/ /dest/foo Note also that host and module references don't require a trailing slash to copy the contents of the default directory. For example, both of these copy the remote directory's contents into "/dest": rsync -av host: /dest rsync -av host::module /dest You can also use rsync in local-only mode, where both the source and destination don't have a ':' in the name. In this case it behaves like an improved copy command. Finally, you can list all the (listable) modules available from a particular rsync daemon by leaving off the module name: rsync somehost.mydomain.com:: COPYING TO A DIFFERENT NAME top When you want to copy a directory to a different name, use a trailing slash on the source directory to put the contents of the directory into any destination directory you like: rsync -ai foo/ bar/ Rsync also has the ability to customize a destination file's name when copying a single item. The rules for this are: o The transfer list must consist of a single item (either a file or an empty directory) o The final element of the destination path must not exist as a directory o The destination path must not have been specified with a trailing slash Under those circumstances, rsync will set the name of the destination's single item to the last element of the destination path. Keep in mind that it is best to only use this idiom when copying a file and use the above trailing-slash idiom when copying a directory. The following example copies the foo.c file as bar.c in the save dir (assuming that bar.c isn't a directory): rsync -ai src/foo.c save/bar.c The single-item copy rule might accidentally bite you if you unknowingly copy a single item and specify a destination dir that doesn't exist (without using a trailing slash). For example, if src/*.c matches one file and save/dir doesn't exist, this will confuse you by naming the destination file save/dir: rsync -ai src/*.c save/dir To prevent such an accident, either make sure the destination dir exists or specify the destination path with a trailing slash: rsync -ai src/*.c save/dir/ SORTED TRANSFER ORDER top Rsync always sorts the specified filenames into its internal transfer list. This handles the merging together of the contents of identically named directories, makes it easy to remove duplicate filenames. It can, however, confuse someone when the files are transferred in a different order than what was given on the command-line. If you need a particular file to be transferred prior to another, either separate the files into different rsync calls, or consider using --delay-updates (which doesn't affect the sorted transfer order, but does make the final file-updating phase happen much more rapidly). MULTI-HOST SECURITY top Rsync takes steps to ensure that the file requests that are shared in a transfer are protected against various security issues. Most of the potential problems arise on the receiving side where rsync takes steps to ensure that the list of files being transferred remains within the bounds of what was requested. Toward this end, rsync 3.1.2 and later have aborted when a file list contains an absolute or relative path that tries to escape out of the top of the transfer. Also, beginning with version 3.2.5, rsync does two more safety checks of the file list to (1) ensure that no extra source arguments were added into the transfer other than those that the client requested and (2) ensure that the file list obeys the exclude rules that were sent to the sender. For those that don't yet have a 3.2.5 client rsync (or those that want to be extra careful), it is safest to do a copy into a dedicated destination directory for the remote files when you don't trust the remote host. For example, instead of doing an rsync copy into your home directory: rsync -aiv host1:dir1 ~ Dedicate a "host1-files" dir to the remote content: rsync -aiv host1:dir1 ~/host1-files See the --trust-sender option for additional details. CAUTION: it is not particularly safe to use rsync to copy files from a case-preserving filesystem to a case-ignoring filesystem. If you must perform such a copy, you should either disable symlinks via --no-links or enable the munging of symlinks via --munge-links (and make sure you use the right local or remote option). This will prevent rsync from doing potentially dangerous things if a symlink name overlaps with a file or directory. It does not, however, ensure that you get a full copy of all the files (since that may not be possible when the names overlap). A potentially better solution is to list all the source files and create a safe list of filenames that you pass to the --files-from option. Any files that conflict in name would need to be copied to different destination directories using more than one copy. While a copy of a case-ignoring filesystem to a case-ignoring filesystem can work out fairly well, if no --delete-during or --delete-before option is active, rsync can potentially update an existing file on the receiveing side without noticing that the upper-/lower-case of the filename should be changed to match the sender. ADVANCED USAGE top The syntax for requesting multiple files from a remote host is done by specifying additional remote-host args in the same style as the first, or with the hostname omitted. For instance, all these work: rsync -aiv host:file1 :file2 host:file{3,4} /dest/ rsync -aiv host::modname/file{1,2} host::modname/extra /dest/ rsync -aiv host::modname/first ::extra-file{1,2} /dest/ Note that a daemon connection only supports accessing one module per copy command, so if the start of a follow-up path doesn't begin with the modname of the first path, it is assumed to be a path in the module (such as the extra-file1 & extra-file2 that are grabbed above). Really old versions of rsync (2.6.9 and before) only allowed specifying one remote-source arg, so some people have instead relied on the remote-shell performing space splitting to break up an arg into multiple paths. Such unintuitive behavior is no longer supported by default (though you can request it, as described below). Starting in 3.2.4, filenames are passed to a remote shell in such a way as to preserve the characters you give it. Thus, if you ask for a file with spaces in the name, that's what the remote rsync looks for: rsync -aiv host:'a simple file.pdf' /dest/ If you use scripts that have been written to manually apply extra quoting to the remote rsync args (or to require remote arg splitting), you can ask rsync to let your script handle the extra escaping. This is done by either adding the --old-args option to the rsync runs in the script (which requires a new rsync) or exporting RSYNC_OLD_ARGS=1 and RSYNC_PROTECT_ARGS=0 (which works with old or new rsync versions). CONNECTING TO AN RSYNC DAEMON top It is also possible to use rsync without a remote shell as the transport. In this case you will directly connect to a remote rsync daemon, typically using TCP port 873. (This obviously requires the daemon to be running on the remote system, so refer to the STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS section below for information on that.) Using rsync in this way is the same as using it with a remote shell except that: o Use either double-colon syntax or rsync:// URL syntax instead of the single-colon (remote shell) syntax. o The first element of the "path" is actually a module name. o Additional remote source args can use an abbreviated syntax that omits the hostname and/or the module name, as discussed in ADVANCED USAGE. o The remote daemon may print a "message of the day" when you connect. o If you specify only the host (with no module or path) then a list of accessible modules on the daemon is output. o If you specify a remote source path but no destination, a listing of the matching files on the remote daemon is output. o The --rsh (-e) option must be omitted to avoid changing the connection style from using a socket connection to USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION. An example that copies all the files in a remote module named "src": rsync -av host::src /dest Some modules on the remote daemon may require authentication. If so, you will receive a password prompt when you connect. You can avoid the password prompt by setting the environment variable RSYNC_PASSWORD to the password you want to use or using the --password-file option. This may be useful when scripting rsync. WARNING: On some systems environment variables are visible to all users. On those systems using --password-file is recommended. You may establish the connection via a web proxy by setting the environment variable RSYNC_PROXY to a hostname:port pair pointing to your web proxy. Note that your web proxy's configuration must support proxy connections to port 873. You may also establish a daemon connection using a program as a proxy by setting the environment variable RSYNC_CONNECT_PROG to the commands you wish to run in place of making a direct socket connection. The string may contain the escape "%H" to represent the hostname specified in the rsync command (so use "%%" if you need a single "%" in your string). For example: export RSYNC_CONNECT_PROG='ssh proxyhost nc %H 873' rsync -av targethost1::module/src/ /dest/ rsync -av rsync://targethost2/module/src/ /dest/ The command specified above uses ssh to run nc (netcat) on a proxyhost, which forwards all data to port 873 (the rsync daemon) on the targethost (%H). Note also that if the RSYNC_SHELL environment variable is set, that program will be used to run the RSYNC_CONNECT_PROG command instead of using the default shell of the system() call. USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION top It is sometimes useful to use various features of an rsync daemon (such as named modules) without actually allowing any new socket connections into a system (other than what is already required to allow remote-shell access). Rsync supports connecting to a host using a remote shell and then spawning a single-use "daemon" server that expects to read its config file in the home dir of the remote user. This can be useful if you want to encrypt a daemon-style transfer's data, but since the daemon is started up fresh by the remote user, you may not be able to use features such as chroot or change the uid used by the daemon. (For another way to encrypt a daemon transfer, consider using ssh to tunnel a local port to a remote machine and configure a normal rsync daemon on that remote host to only allow connections from "localhost".) From the user's perspective, a daemon transfer via a remote-shell connection uses nearly the same command-line syntax as a normal rsync-daemon transfer, with the only exception being that you must explicitly set the remote shell program on the command-line with the --rsh=COMMAND option. (Setting the RSYNC_RSH in the environment will not turn on this functionality.) For example: rsync -av --rsh=ssh host::module /dest If you need to specify a different remote-shell user, keep in mind that the user@ prefix in front of the host is specifying the rsync-user value (for a module that requires user-based authentication). This means that you must give the '-l user' option to ssh when specifying the remote-shell, as in this example that uses the short version of the --rsh option: rsync -av -e "ssh -l ssh-user" rsync-user@host::module /dest The "ssh-user" will be used at the ssh level; the "rsync-user" will be used to log-in to the "module". In this setup, the daemon is started by the ssh command that is accessing the system (which can be forced via the ~/.ssh/authorized_keys file, if desired). However, when accessing a daemon directly, it needs to be started beforehand. STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS top In order to connect to an rsync daemon, the remote system needs to have a daemon already running (or it needs to have configured something like inetd to spawn an rsync daemon for incoming connections on a particular port). For full information on how to start a daemon that will handling incoming socket connections, see the rsyncd.conf(5) manpage -- that is the config file for the daemon, and it contains the full details for how to run the daemon (including stand-alone and inetd configurations). If you're using one of the remote-shell transports for the transfer, there is no need to manually start an rsync daemon. EXAMPLES top Here are some examples of how rsync can be used. To backup a home directory, which consists of large MS Word files and mail folders, a per-user cron job can be used that runs this each day: rsync -aiz . bkhost:backup/joe/ To move some files from a remote host to the local host, you could run: rsync -aiv --remove-source-files rhost:/tmp/{file1,file2}.c ~/src/ OPTION SUMMARY top Here is a short summary of the options available in rsync. Each option also has its own detailed description later in this manpage. --verbose, -v increase verbosity --info=FLAGS fine-grained informational verbosity --debug=FLAGS fine-grained debug verbosity --stderr=e|a|c change stderr output mode (default: errors) --quiet, -q suppress non-error messages --no-motd suppress daemon-mode MOTD --checksum, -c skip based on checksum, not mod-time & size --archive, -a archive mode is -rlptgoD (no -A,-X,-U,-N,-H) --no-OPTION turn off an implied OPTION (e.g. --no-D) --recursive, -r recurse into directories --relative, -R use relative path names --no-implied-dirs don't send implied dirs with --relative --backup, -b make backups (see --suffix & --backup-dir) --backup-dir=DIR make backups into hierarchy based in DIR --suffix=SUFFIX backup suffix (default ~ w/o --backup-dir) --update, -u skip files that are newer on the receiver --inplace update destination files in-place --append append data onto shorter files --append-verify --append w/old data in file checksum --dirs, -d transfer directories without recursing --old-dirs, --old-d works like --dirs when talking to old rsync --mkpath create destination's missing path components --links, -l copy symlinks as symlinks --copy-links, -L transform symlink into referent file/dir --copy-unsafe-links only "unsafe" symlinks are transformed --safe-links ignore symlinks that point outside the tree --munge-links munge symlinks to make them safe & unusable --copy-dirlinks, -k transform symlink to dir into referent dir --keep-dirlinks, -K treat symlinked dir on receiver as dir --hard-links, -H preserve hard links --perms, -p preserve permissions --executability, -E preserve executability --chmod=CHMOD affect file and/or directory permissions --acls, -A preserve ACLs (implies --perms) --xattrs, -X preserve extended attributes --owner, -o preserve owner (super-user only) --group, -g preserve group --devices preserve device files (super-user only) --copy-devices copy device contents as a regular file --write-devices write to devices as files (implies --inplace) --specials preserve special files -D same as --devices --specials --times, -t preserve modification times --atimes, -U preserve access (use) times --open-noatime avoid changing the atime on opened files --crtimes, -N preserve create times (newness) --omit-dir-times, -O omit directories from --times --omit-link-times, -J omit symlinks from --times --super receiver attempts super-user activities --fake-super store/recover privileged attrs using xattrs --sparse, -S turn sequences of nulls into sparse blocks --preallocate allocate dest files before writing them --dry-run, -n perform a trial run with no changes made --whole-file, -W copy files whole (w/o delta-xfer algorithm) --checksum-choice=STR choose the checksum algorithm (aka --cc) --one-file-system, -x don't cross filesystem boundaries --block-size=SIZE, -B force a fixed checksum block-size --rsh=COMMAND, -e specify the remote shell to use --rsync-path=PROGRAM specify the rsync to run on remote machine --existing skip creating new files on receiver --ignore-existing skip updating files that exist on receiver --remove-source-files sender removes synchronized files (non-dir) --del an alias for --delete-during --delete delete extraneous files from dest dirs --delete-before receiver deletes before xfer, not during --delete-during receiver deletes during the transfer --delete-delay find deletions during, delete after --delete-after receiver deletes after transfer, not during --delete-excluded also delete excluded files from dest dirs --ignore-missing-args ignore missing source args without error --delete-missing-args delete missing source args from destination --ignore-errors delete even if there are I/O errors --force force deletion of dirs even if not empty --max-delete=NUM don't delete more than NUM files --max-size=SIZE don't transfer any file larger than SIZE --min-size=SIZE don't transfer any file smaller than SIZE --max-alloc=SIZE change a limit relating to memory alloc --partial keep partially transferred files --partial-dir=DIR put a partially transferred file into DIR --delay-updates put all updated files into place at end --prune-empty-dirs, -m prune empty directory chains from file-list --numeric-ids don't map uid/gid values by user/group name --usermap=STRING custom username mapping --groupmap=STRING custom groupname mapping --chown=USER:GROUP simple username/groupname mapping --timeout=SECONDS set I/O timeout in seconds --contimeout=SECONDS set daemon connection timeout in seconds --ignore-times, -I don't skip files that match size and time --size-only skip files that match in size --modify-window=NUM, -@ set the accuracy for mod-time comparisons --temp-dir=DIR, -T create temporary files in directory DIR --fuzzy, -y find similar file for basis if no dest file --compare-dest=DIR also compare destination files relative to DIR --copy-dest=DIR ... and include copies of unchanged files --link-dest=DIR hardlink to files in DIR when unchanged --compress, -z compress file data during the transfer --compress-choice=STR choose the compression algorithm (aka --zc) --compress-level=NUM explicitly set compression level (aka --zl) --skip-compress=LIST skip compressing files with suffix in LIST --cvs-exclude, -C auto-ignore files in the same way CVS does --filter=RULE, -f add a file-filtering RULE -F same as --filter='dir-merge /.rsync-filter' repeated: --filter='- .rsync-filter' --exclude=PATTERN exclude files matching PATTERN --exclude-from=FILE read exclude patterns from FILE --include=PATTERN don't exclude files matching PATTERN --include-from=FILE read include patterns from FILE --files-from=FILE read list of source-file names from FILE --from0, -0 all *-from/filter files are delimited by 0s --old-args disable the modern arg-protection idiom --secluded-args, -s use the protocol to safely send the args --trust-sender trust the remote sender's file list --copy-as=USER[:GROUP] specify user & optional group for the copy --address=ADDRESS bind address for outgoing socket to daemon --port=PORT specify double-colon alternate port number --sockopts=OPTIONS specify custom TCP options --blocking-io use blocking I/O for the remote shell --outbuf=N|L|B set out buffering to None, Line, or Block --stats give some file-transfer stats --8-bit-output, -8 leave high-bit chars unescaped in output --human-readable, -h output numbers in a human-readable format --progress show progress during transfer -P same as --partial --progress --itemize-changes, -i output a change-summary for all updates --remote-option=OPT, -M send OPTION to the remote side only --out-format=FORMAT output updates using the specified FORMAT --log-file=FILE log what we're doing to the specified FILE --log-file-format=FMT log updates using the specified FMT --password-file=FILE read daemon-access password from FILE --early-input=FILE use FILE for daemon's early exec input --list-only list the files instead of copying them --bwlimit=RATE limit socket I/O bandwidth --stop-after=MINS Stop rsync after MINS minutes have elapsed --stop-at=y-m-dTh:m Stop rsync at the specified point in time --fsync fsync every written file --write-batch=FILE write a batched update to FILE --only-write-batch=FILE like --write-batch but w/o updating dest --read-batch=FILE read a batched update from FILE --protocol=NUM force an older protocol version to be used --iconv=CONVERT_SPEC request charset conversion of filenames --checksum-seed=NUM set block/file checksum seed (advanced) --ipv4, -4 prefer IPv4 --ipv6, -6 prefer IPv6 --version, -V print the version + other info and exit --help, -h (*) show this help (* -h is help only on its own) Rsync can also be run as a daemon, in which case the following options are accepted: --daemon run as an rsync daemon --address=ADDRESS bind to the specified address --bwlimit=RATE limit socket I/O bandwidth --config=FILE specify alternate rsyncd.conf file --dparam=OVERRIDE, -M override global daemon config parameter --no-detach do not detach from the parent --port=PORT listen on alternate port number --log-file=FILE override the "log file" setting --log-file-format=FMT override the "log format" setting --sockopts=OPTIONS specify custom TCP options --verbose, -v increase verbosity --ipv4, -4 prefer IPv4 --ipv6, -6 prefer IPv6 --help, -h show this help (when used with --daemon) OPTIONS top Rsync accepts both long (double-dash + word) and short (single- dash + letter) options. The full list of the available options are described below. If an option can be specified in more than one way, the choices are comma-separated. Some options only have a long variant, not a short. If the option takes a parameter, the parameter is only listed after the long variant, even though it must also be specified for the short. When specifying a parameter, you can either use the form --option=param, --option param, -o=param, -o param, or -oparam (the latter choices assume that your option has a short variant). The parameter may need to be quoted in some manner for it to survive the shell's command-line parsing. Also keep in mind that a leading tilde (~) in a pathname is substituted by your shell, so make sure that you separate the option name from the pathname using a space if you want the local shell to expand it. --help Print a short help page describing the options available in rsync and exit. You can also use -h for --help when it is used without any other options (since it normally means --human-readable). --version, -V Print the rsync version plus other info and exit. When repeated, the information is output is a JSON format that is still fairly readable (client side only). The output includes a list of compiled-in capabilities, a list of optimizations, the default list of checksum algorithms, the default list of compression algorithms, the default list of daemon auth digests, a link to the rsync web site, and a few other items. --verbose, -v This option increases the amount of information you are given during the transfer. By default, rsync works silently. A single -v will give you information about what files are being transferred and a brief summary at the end. Two -v options will give you information on what files are being skipped and slightly more information at the end. More than two -v options should only be used if you are debugging rsync. The end-of-run summary tells you the number of bytes sent to the remote rsync (which is the receiving side on a local copy), the number of bytes received from the remote host, and the average bytes per second of the transferred data computed over the entire length of the rsync run. The second line shows the total size (in bytes), which is the sum of all the file sizes that rsync considered transferring. It also shows a "speedup" value, which is a ratio of the total file size divided by the sum of the sent and received bytes (which is really just a feel-good bigger-is-better number). Note that these byte values can be made more (or less) human-readable by using the --human-readable (or --no-human-readable) options. In a modern rsync, the -v option is equivalent to the setting of groups of --info and --debug options. You can choose to use these newer options in addition to, or in place of using --verbose, as any fine-grained settings override the implied settings of -v. Both --info and --debug have a way to ask for help that tells you exactly what flags are set for each increase in verbosity. However, do keep in mind that a daemon's "max verbosity" setting will limit how high of a level the various individual flags can be set on the daemon side. For instance, if the max is 2, then any info and/or debug flag that is set to a higher value than what would be set by -vv will be downgraded to the -vv level in the daemon's logging. --info=FLAGS This option lets you have fine-grained control over the information output you want to see. An individual flag name may be followed by a level number, with 0 meaning to silence that output, 1 being the default output level, and higher numbers increasing the output of that flag (for those that support higher levels). Use --info=help to see all the available flag names, what they output, and what flag names are added for each increase in the verbose level. Some examples: rsync -a --info=progress2 src/ dest/ rsync -avv --info=stats2,misc1,flist0 src/ dest/ Note that --info=name's output is affected by the --out- format and --itemize-changes (-i) options. See those options for more information on what is output and when. This option was added to 3.1.0, so an older rsync on the server side might reject your attempts at fine-grained control (if one or more flags needed to be send to the server and the server was too old to understand them). See also the "max verbosity" caveat above when dealing with a daemon. --debug=FLAGS This option lets you have fine-grained control over the debug output you want to see. An individual flag name may be followed by a level number, with 0 meaning to silence that output, 1 being the default output level, and higher numbers increasing the output of that flag (for those that support higher levels). Use --debug=help to see all the available flag names, what they output, and what flag names are added for each increase in the verbose level. Some examples: rsync -avvv --debug=none src/ dest/ rsync -avA --del --debug=del2,acl src/ dest/ Note that some debug messages will only be output when the --stderr=all option is specified, especially those pertaining to I/O and buffer debugging. Beginning in 3.2.0, this option is no longer auto- forwarded to the server side in order to allow you to specify different debug values for each side of the transfer, as well as to specify a new debug option that is only present in one of the rsync versions. If you want to duplicate the same option on both sides, using brace expansion is an easy way to save you some typing. This works in zsh and bash: rsync -aiv {-M,}--debug=del2 src/ dest/ --stderr=errors|all|client This option controls which processes output to stderr and if info messages are also changed to stderr. The mode strings can be abbreviated, so feel free to use a single letter value. The 3 possible choices are: o errors - (the default) causes all the rsync processes to send an error directly to stderr, even if the process is on the remote side of the transfer. Info messages are sent to the client side via the protocol stream. If stderr is not available (i.e. when directly connecting with a daemon via a socket) errors fall back to being sent via the protocol stream. o all - causes all rsync messages (info and error) to get written directly to stderr from all (possible) processes. This causes stderr to become line- buffered (instead of raw) and eliminates the ability to divide up the info and error messages by file handle. For those doing debugging or using several levels of verbosity, this option can help to avoid clogging up the transfer stream (which should prevent any chance of a deadlock bug hanging things up). It also allows --debug to enable some extra I/O related messages. o client - causes all rsync messages to be sent to the client side via the protocol stream. One client process outputs all messages, with errors on stderr and info messages on stdout. This was the default in older rsync versions, but can cause error delays when a lot of transfer data is ahead of the messages. If you're pushing files to an older rsync, you may want to use --stderr=all since that idiom has been around for several releases. This option was added in rsync 3.2.3. This version also began the forwarding of a non-default setting to the remote side, though rsync uses the backward-compatible options --msgs2stderr and --no-msgs2stderr to represent the all and client settings, respectively. A newer rsync will continue to accept these older option names to maintain compatibility. --quiet, -q This option decreases the amount of information you are given during the transfer, notably suppressing information messages from the remote server. This option is useful when invoking rsync from cron. --no-motd This option affects the information that is output by the client at the start of a daemon transfer. This suppresses the message-of-the-day (MOTD) text, but it also affects the list of modules that the daemon sends in response to the "rsync host::" request (due to a limitation in the rsync protocol), so omit this option if you want to request the list of modules from the daemon. --ignore-times, -I Normally rsync will skip any files that are already the same size and have the same modification timestamp. This option turns off this "quick check" behavior, causing all files to be updated. This option can be confusing compared to --ignore-existing and --ignore-non-existing in that that they cause rsync to transfer fewer files, while this option causes rsync to transfer more files. --size-only This modifies rsync's "quick check" algorithm for finding files that need to be transferred, changing it from the default of transferring files with either a changed size or a changed last-modified time to just looking for files that have changed in size. This is useful when starting to use rsync after using another mirroring system which may not preserve timestamps exactly. --modify-window=NUM, -@ When comparing two timestamps, rsync treats the timestamps as being equal if they differ by no more than the modify- window value. The default is 0, which matches just integer seconds. If you specify a negative value (and the receiver is at least version 3.1.3) then nanoseconds will also be taken into account. Specifying 1 is useful for copies to/from MS Windows FAT filesystems, because FAT represents times with a 2-second resolution (allowing times to differ from the original by up to 1 second). If you want all your transfers to default to comparing nanoseconds, you can create a ~/.popt file and put these lines in it: rsync alias -a -a@-1 rsync alias -t -t@-1 With that as the default, you'd need to specify --modify- window=0 (aka -@0) to override it and ignore nanoseconds, e.g. if you're copying between ext3 and ext4, or if the receiving rsync is older than 3.1.3. --checksum, -c This changes the way rsync checks if the files have been changed and are in need of a transfer. Without this option, rsync uses a "quick check" that (by default) checks if each file's size and time of last modification match between the sender and receiver. This option changes this to compare a 128-bit checksum for each file that has a matching size. Generating the checksums means that both sides will expend a lot of disk I/O reading all the data in the files in the transfer, so this can slow things down significantly (and this is prior to any reading that will be done to transfer changed files) The sending side generates its checksums while it is doing the file-system scan that builds the list of the available files. The receiver generates its checksums when it is scanning for changed files, and will checksum any file that has the same size as the corresponding sender's file: files with either a changed size or a changed checksum are selected for transfer. Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option's before- the-transfer "Does this file need to be updated?" check. The checksum used is auto-negotiated between the client and the server, but can be overridden using either the --checksum-choice (--cc) option or an environment variable that is discussed in that option's section. --archive, -a This is equivalent to -rlptgoD. It is a quick way of saying you want recursion and want to preserve almost everything. Be aware that it does not include preserving ACLs (-A), xattrs (-X), atimes (-U), crtimes (-N), nor the finding and preserving of hardlinks (-H). The only exception to the above equivalence is when --files-from is specified, in which case -r is not implied. --no-OPTION You may turn off one or more implied options by prefixing the option name with "no-". Not all positive options have a negated opposite, but a lot do, including those that can be used to disable an implied option (e.g. --no-D, --no- perms) or have different defaults in various circumstances (e.g. --no-whole-file, --no-blocking-io, --no-dirs). Every valid negated option accepts both the short and the long option name after the "no-" prefix (e.g. --no-R is the same as --no-relative). As an example, if you want to use --archive (-a) but don't want --owner (-o), instead of converting -a into -rlptgD, you can specify -a --no-o (aka --archive --no-owner). The order of the options is important: if you specify --no-r -a, the -r option would end up being turned on, the opposite of -a --no-r. Note also that the side-effects of the --files-from option are NOT positional, as it affects the default state of several options and slightly changes the meaning of -a (see the --files-from option for more details). --recursive, -r This tells rsync to copy directories recursively. See also --dirs (-d) for an option that allows the scanning of a single directory. See the --inc-recursive option for a discussion of the incremental recursion for creating the list of files to transfer. --inc-recursive, --i-r This option explicitly enables on incremental recursion when scanning for files, which is enabled by default when using the --recursive option and both sides of the transfer are running rsync 3.0.0 or newer. Incremental recursion uses much less memory than non- incremental, while also beginning the transfer more quickly (since it doesn't need to scan the entire transfer hierarchy before it starts transferring files). If no recursion is enabled in the source files, this option has no effect. Some options require rsync to know the full file list, so these options disable the incremental recursion mode. These include: o --delete-before (the old default of --delete) o --delete-after o --prune-empty-dirs o --delay-updates In order to make --delete compatible with incremental recursion, rsync 3.0.0 made --delete-during the default delete mode (which was first added in 2.6.4). One side-effect of incremental recursion is that any missing sub-directories inside a recursively-scanned directory are (by default) created prior to recursing into the sub-dirs. This earlier creation point (compared to a non-incremental recursion) allows rsync to then set the modify time of the finished directory right away (without having to delay that until a bunch of recursive copying has finished). However, these early directories don't yet have their completed mode, mtime, or ownership set -- they have more restrictive rights until the subdirectory's copying actually begins. This early-creation idiom can be avoided by using the --omit-dir-times option. Incremental recursion can be disabled using the --no-inc- recursive (--no-i-r) option. --no-inc-recursive, --no-i-r Disables the new incremental recursion algorithm of the --recursive option. This makes rsync scan the full file list before it begins to transfer files. See --inc- recursive for more info. --relative, -R Use relative paths. This means that the full path names specified on the command line are sent to the server rather than just the last parts of the filenames. This is particularly useful when you want to send several different directories at the same time. For example, if you used this command: rsync -av /foo/bar/baz.c remote:/tmp/ would create a file named baz.c in /tmp/ on the remote machine. If instead you used rsync -avR /foo/bar/baz.c remote:/tmp/ then a file named /tmp/foo/bar/baz.c would be created on the remote machine, preserving its full path. These extra path elements are called "implied directories" (i.e. the "foo" and the "foo/bar" directories in the above example). Beginning with rsync 3.0.0, rsync always sends these implied directories as real directories in the file list, even if a path element is really a symlink on the sending side. This prevents some really unexpected behaviors when copying the full path of a file that you didn't realize had a symlink in its path. If you want to duplicate a server-side symlink, include both the symlink via its path, and referent directory via its real path. If you're dealing with an older rsync on the sending side, you may need to use the --no-implied-dirs option. It is also possible to limit the amount of path information that is sent as implied directories for each path you specify. With a modern rsync on the sending side (beginning with 2.6.7), you can insert a dot and a slash into the source path, like this: rsync -avR /foo/./bar/baz.c remote:/tmp/ That would create /tmp/bar/baz.c on the remote machine. (Note that the dot must be followed by a slash, so "/foo/." would not be abbreviated.) For older rsync versions, you would need to use a chdir to limit the source path. For example, when pushing files: (cd /foo; rsync -avR bar/baz.c remote:/tmp/) (Note that the parens put the two commands into a sub- shell, so that the "cd" command doesn't remain in effect for future commands.) If you're pulling files from an older rsync, use this idiom (but only for a non-daemon transfer): rsync -avR --rsync-path="cd /foo; rsync" \ remote:bar/baz.c /tmp/ --no-implied-dirs This option affects the default behavior of the --relative option. When it is specified, the attributes of the implied directories from the source names are not included in the transfer. This means that the corresponding path elements on the destination system are left unchanged if they exist, and any missing implied directories are created with default attributes. This even allows these implied path elements to have big differences, such as being a symlink to a directory on the receiving side. For instance, if a command-line arg or a files-from entry told rsync to transfer the file "path/foo/file", the directories "path" and "path/foo" are implied when --relative is used. If "path/foo" is a symlink to "bar" on the destination system, the receiving rsync would ordinarily delete "path/foo", recreate it as a directory, and receive the file into the new directory. With --no- implied-dirs, the receiving rsync updates "path/foo/file" using the existing path elements, which means that the file ends up being created in "path/bar". Another way to accomplish this link preservation is to use the --keep- dirlinks option (which will also affect symlinks to directories in the rest of the transfer). When pulling files from an rsync older than 3.0.0, you may need to use this option if the sending side has a symlink in the path you request and you wish the implied directories to be transferred as normal directories. --backup, -b With this option, preexisting destination files are renamed as each file is transferred or deleted. You can control where the backup file goes and what (if any) suffix gets appended using the --backup-dir and --suffix options. If you don't specify --backup-dir: 1. the --omit-dir-times option will be forced on 2. the use of --delete (without --delete-excluded), causes rsync to add a "protect" filter-rule for the backup suffix to the end of all your existing filters that looks like this: -f "P *~". This rule prevents previously backed-up files from being deleted. Note that if you are supplying your own filter rules, you may need to manually insert your own exclude/protect rule somewhere higher up in the list so that it has a high enough priority to be effective (e.g. if your rules specify a trailing inclusion/exclusion of *, the auto- added rule would never be reached). --backup-dir=DIR This implies the --backup option, and tells rsync to store all backups in the specified directory on the receiving side. This can be used for incremental backups. You can additionally specify a backup suffix using the --suffix option (otherwise the files backed up in the specified directory will keep their original filenames). Note that if you specify a relative path, the backup directory will be relative to the destination directory, so you probably want to specify either an absolute path or a path that starts with "../". If an rsync daemon is the receiver, the backup dir cannot go outside the module's path hierarchy, so take extra care not to delete it or copy into it. --suffix=SUFFIX This option allows you to override the default backup suffix used with the --backup (-b) option. The default suffix is a ~ if no --backup-dir was specified, otherwise it is an empty string. --update, -u This forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. (If an existing destination file has a modification time equal to the source file's, it will be updated if the sizes are different.) Note that this does not affect the copying of dirs, symlinks, or other special files. Also, a difference of file format between the sender and receiver is always considered to be important enough for an update, no matter what date is on the objects. In other words, if the source has a directory where the destination has a file, the transfer would occur regardless of the timestamps. This option is a TRANSFER RULE, so don't expect any exclude side effects. A caution for those that choose to combine --inplace with --update: an interrupted transfer will leave behind a partial file on the receiving side that has a very recent modified time, so re-running the transfer will probably not continue the interrupted file. As such, it is usually best to avoid combining this with --inplace unless you have implemented manual steps to handle any interrupted in-progress files. --inplace This option changes how rsync transfers a file when its data needs to be updated: instead of the default method of creating a new copy of the file and moving it into place when it is complete, rsync instead writes the updated data directly to the destination file. This has several effects: o Hard links are not broken. This means the new data will be visible through other hard links to the destination file. Moreover, attempts to copy differing source files onto a multiply-linked destination file will result in a "tug of war" with the destination data changing back and forth. o In-use binaries cannot be updated (either the OS will prevent this from happening, or binaries that attempt to swap-in their data will misbehave or crash). o The file's data will be in an inconsistent state during the transfer and will be left that way if the transfer is interrupted or if an update fails. o A file that rsync cannot write to cannot be updated. While a super user can update any file, a normal user needs to be granted write permission for the open of the file for writing to be successful. o The efficiency of rsync's delta-transfer algorithm may be reduced if some data in the destination file is overwritten before it can be copied to a position later in the file. This does not apply if you use --backup, since rsync is smart enough to use the backup file as the basis file for the transfer. WARNING: you should not use this option to update files that are being accessed by others, so be careful when choosing to use this for a copy. This option is useful for transferring large files with block-based changes or appended data, and also on systems that are disk bound, not network bound. It can also help keep a copy-on-write filesystem snapshot from diverging the entire contents of a file that only has minor changes. The option implies --partial (since an interrupted transfer does not delete the file), but conflicts with --partial-dir and --delay-updates. Prior to rsync 2.6.4 --inplace was also incompatible with --compare-dest and --link-dest. --append This special copy mode only works to efficiently update files that are known to be growing larger where any existing content on the receiving side is also known to be the same as the content on the sender. The use of --append can be dangerous if you aren't 100% sure that all the files in the transfer are shared, growing files. You should thus use filter rules to ensure that you weed out any files that do not fit this criteria. Rsync updates these growing file in-place without verifying any of the existing content in the file (it only verifies the content that it is appending). Rsync skips any files that exist on the receiving side that are not shorter than the associated file on the sending side (which means that new files are transferred). It also skips any files whose size on the sending side gets shorter during the send negotiations (rsync warns about a "diminished" file when this happens). This does not interfere with the updating of a file's non- content attributes (e.g. permissions, ownership, etc.) when the file does not need to be transferred, nor does it affect the updating of any directories or non-regular files. --append-verify This special copy mode works like --append except that all the data in the file is included in the checksum verification (making it less efficient but also potentially safer). This option can be dangerous if you aren't 100% sure that all the files in the transfer are shared, growing files. See the --append option for more details. Note: prior to rsync 3.0.0, the --append option worked like --append-verify, so if you are interacting with an older rsync (or the transfer is using a protocol prior to 30), specifying either append option will initiate an --append-verify transfer. --dirs, -d Tell the sending side to include any directories that are encountered. Unlike --recursive, a directory's contents are not copied unless the directory name specified is "." or ends with a trailing slash (e.g. ".", "dir/.", "dir/", etc.). Without this option or the --recursive option, rsync will skip all directories it encounters (and output a message to that effect for each one). If you specify both --dirs and --recursive, --recursive takes precedence. The --dirs option is implied by the --files-from option or the --list-only option (including an implied --list-only usage) if --recursive wasn't specified (so that directories are seen in the listing). Specify --no-dirs (or --no-d) if you want to turn this off. There is also a backward-compatibility helper option, --old-dirs (--old-d) that tells rsync to use a hack of -r --exclude='/*/*' to get an older rsync to list a single directory without recursing. --mkpath Create all missing path components of the destination path. By default, rsync allows only the final component of the destination path to not exist, which is an attempt to help you to validate your destination path. With this option, rsync creates all the missing destination-path components, just as if mkdir -p $DEST_PATH had been run on the receiving side. When specifying a destination path, including a trailing slash ensures that the whole path is treated as directory names to be created, even when the file list has a single item. See the COPYING TO A DIFFERENT NAME section for full details on how rsync decides if a final destination-path component should be created as a directory or not. If you would like the newly-created destination dirs to match the dirs on the sending side, you should be using --relative (-R) instead of --mkpath. For instance, the following two commands result in the same destination tree, but only the second command ensures that the "some/extra/path" components match the dirs on the sending side: rsync -ai --mkpath host:some/extra/path/*.c some/extra/path/ rsync -aiR host:some/extra/path/*.c ./ --links, -l Add symlinks to the transferred files instead of noisily ignoring them with a "non-regular file" warning for each symlink encountered. You can alternately silence the warning by specifying --info=nonreg0. The default handling of symlinks is to recreate each symlink's unchanged value on the receiving side. See the SYMBOLIC LINKS section for multi-option info. --copy-links, -L The sender transforms each symlink encountered in the transfer into the referent item, following the symlink chain to the file or directory that it references. If a symlink chain is broken, an error is output and the file is dropped from the transfer. This option supersedes any other options that affect symlinks in the transfer, since there are no symlinks left in the transfer. This option does not change the handling of existing symlinks on the receiving side, unlike versions of rsync prior to 2.6.3 which had the side-effect of telling the receiving side to also follow symlinks. A modern rsync won't forward this option to a remote receiver (since only the sender needs to know about it), so this caveat should only affect someone using an rsync client older than 2.6.7 (which is when -L stopped being forwarded to the receiver). See the --keep-dirlinks (-K) if you need a symlink to a directory to be treated as a real directory on the receiving side. See the SYMBOLIC LINKS section for multi-option info. --copy-unsafe-links This tells rsync to copy the referent of symbolic links that point outside the copied tree. Absolute symlinks are also treated like ordinary files, and so are any symlinks in the source path itself when --relative is used. Note that the cut-off point is the top of the transfer, which is the part of the path that rsync isn't mentioning in the verbose output. If you copy "/src/subdir" to "/dest/" then the "subdir" directory is a name inside the transfer tree, not the top of the transfer (which is /src) so it is legal for created relative symlinks to refer to other names inside the /src and /dest directories. If you instead copy "/src/subdir/" (with a trailing slash) to "/dest/subdir" that would not allow symlinks to any files outside of "subdir". Note that safe symlinks are only copied if --links was also specified or implied. The --copy-unsafe-links option has no extra effect when combined with --copy-links. See the SYMBOLIC LINKS section for multi-option info. --safe-links This tells the receiving rsync to ignore any symbolic links in the transfer which point outside the copied tree. All absolute symlinks are also ignored. Since this ignoring is happening on the receiving side, it will still be effective even when the sending side has munged symlinks (when it is using --munge-links). It also affects deletions, since the file being present in the transfer prevents any matching file on the receiver from being deleted when the symlink is deemed to be unsafe and is skipped. This option must be combined with --links (or --archive) to have any symlinks in the transfer to conditionally ignore. Its effect is superseded by --copy-unsafe-links. Using this option in conjunction with --relative may give unexpected results. See the SYMBOLIC LINKS section for multi-option info. --munge-links This option affects just one side of the transfer and tells rsync to munge symlink values when it is receiving files or unmunge symlink values when it is sending files. The munged values make the symlinks unusable on disk but allows the original contents of the symlinks to be recovered. The server-side rsync often enables this option without the client's knowledge, such as in an rsync daemon's configuration file or by an option given to the rrsync (restricted rsync) script. When specified on the client side, specify the option normally if it is the client side that has/needs the munged symlinks, or use -M--munge-links to give the option to the server when it has/needs the munged symlinks. Note that on a local transfer, the client is the sender, so specifying the option directly unmunges symlinks while specifying it as a remote option munges symlinks. This option has no effect when sent to a daemon via --remote-option because the daemon configures whether it wants munged symlinks via its "munge symlinks" parameter. The symlink value is munged/unmunged once it is in the transfer, so any option that transforms symlinks into non- symlinks occurs prior to the munging/unmunging except for --safe-links, which is a choice that the receiver makes, so it bases its decision on the munged/unmunged value. This does mean that if a receiver has munging enabled, that using --safe-links will cause all symlinks to be ignored (since they are all absolute). The method that rsync uses to munge the symlinks is to prefix each one's value with the string "/rsyncd-munged/". This prevents the links from being used as long as the directory does not exist. When this option is enabled, rsync will refuse to run if that path is a directory or a symlink to a directory (though it only checks at startup). See also the "munge-symlinks" python script in the support directory of the source code for a way to munge/unmunge one or more symlinks in-place. --copy-dirlinks, -k This option causes the sending side to treat a symlink to a directory as though it were a real directory. This is useful if you don't want symlinks to non-directories to be affected, as they would be using --copy-links. Without this option, if the sending side has replaced a directory with a symlink to a directory, the receiving side will delete anything that is in the way of the new symlink, including a directory hierarchy (as long as --force or --delete is in effect). See also --keep-dirlinks for an analogous option for the receiving side. --copy-dirlinks applies to all symlinks to directories in the source. If you want to follow only a few specified symlinks, a trick you can use is to pass them as additional source args with a trailing slash, using --relative to make the paths match up right. For example: rsync -r --relative src/./ src/./follow-me/ dest/ This works because rsync calls lstat(2) on the source arg as given, and the trailing slash makes lstat(2) follow the symlink, giving rise to a directory in the file-list which overrides the symlink found during the scan of "src/./". See the SYMBOLIC LINKS section for multi-option info. --keep-dirlinks, -K This option causes the receiving side to treat a symlink to a directory as though it were a real directory, but only if it matches a real directory from the sender. Without this option, the receiver's symlink would be deleted and replaced with a real directory. For example, suppose you transfer a directory "foo" that contains a file "file", but "foo" is a symlink to directory "bar" on the receiver. Without --keep-dirlinks, the receiver deletes symlink "foo", recreates it as a directory, and receives the file into the new directory. With --keep-dirlinks, the receiver keeps the symlink and "file" ends up in "bar". One note of caution: if you use --keep-dirlinks, you must trust all the symlinks in the copy or enable the --munge- links option on the receiving side! If it is possible for an untrusted user to create their own symlink to any real directory, the user could then (on a subsequent copy) replace the symlink with a real directory and affect the content of whatever directory the symlink references. For backup copies, you are better off using something like a bind mount instead of a symlink to modify your receiving hierarchy. See also --copy-dirlinks for an analogous option for the sending side. See the SYMBOLIC LINKS section for multi-option info. --hard-links, -H This tells rsync to look for hard-linked files in the source and link together the corresponding files on the destination. Without this option, hard-linked files in the source are treated as though they were separate files. This option does NOT necessarily ensure that the pattern of hard links on the destination exactly matches that on the source. Cases in which the destination may end up with extra hard links include the following: o If the destination contains extraneous hard-links (more linking than what is present in the source file list), the copying algorithm will not break them explicitly. However, if one or more of the paths have content differences, the normal file- update process will break those extra links (unless you are using the --inplace option). o If you specify a --link-dest directory that contains hard links, the linking of the destination files against the --link-dest files can cause some paths in the destination to become linked together due to the --link-dest associations. Note that rsync can only detect hard links between files that are inside the transfer set. If rsync updates a file that has extra hard-link connections to files outside the transfer, that linkage will be broken. If you are tempted to use the --inplace option to avoid this breakage, be very careful that you know how your files are being updated so that you are certain that no unintended changes happen due to lingering hard links (and see the --inplace option for more caveats). If incremental recursion is active (see --inc-recursive), rsync may transfer a missing hard-linked file before it finds that another link for that contents exists elsewhere in the hierarchy. This does not affect the accuracy of the transfer (i.e. which files are hard-linked together), just its efficiency (i.e. copying the data for a new, early copy of a hard-linked file that could have been found later in the transfer in another member of the hard- linked set of files). One way to avoid this inefficiency is to disable incremental recursion using the --no-inc- recursive option. --perms, -p This option causes the receiving rsync to set the destination permissions to be the same as the source permissions. (See also the --chmod option for a way to modify what rsync considers to be the source permissions.) When this option is off, permissions are set as follows: o Existing files (including updated files) retain their existing permissions, though the --executability option might change just the execute permission for the file. o New files get their "normal" permission bits set to the source file's permissions masked with the receiving directory's default permissions (either the receiving process's umask, or the permissions specified via the destination directory's default ACL), and their special permission bits disabled except in the case where a new directory inherits a setgid bit from its parent directory. Thus, when --perms and --executability are both disabled, rsync's behavior is the same as that of other file-copy utilities, such as cp(1) and tar(1). In summary: to give destination files (both old and new) the source permissions, use --perms. To give new files the destination-default permissions (while leaving existing files unchanged), make sure that the --perms option is off and use --chmod=ugo=rwX (which ensures that all non-masked bits get enabled). If you'd care to make this latter behavior easier to type, you could define a popt alias for it, such as putting this line in the file ~/.popt (the following defines the -Z option, and includes --no-g to use the default group of the destination dir): rsync alias -Z --no-p --no-g --chmod=ugo=rwX You could then use this new option in a command such as this one: rsync -avZ src/ dest/ (Caveat: make sure that -a does not follow -Z, or it will re-enable the two --no-* options mentioned above.) The preservation of the destination's setgid bit on newly- created directories when --perms is off was added in rsync 2.6.7. Older rsync versions erroneously preserved the three special permission bits for newly-created files when --perms was off, while overriding the destination's setgid bit setting on a newly-created directory. Default ACL observance was added to the ACL patch for rsync 2.6.7, so older (or non-ACL-enabled) rsyncs use the umask even if default ACLs are present. (Keep in mind that it is the version of the receiving rsync that affects these behaviors.) --executability, -E This option causes rsync to preserve the executability (or non-executability) of regular files when --perms is not enabled. A regular file is considered to be executable if at least one 'x' is turned on in its permissions. When an existing destination file's executability differs from that of the corresponding source file, rsync modifies the destination file's permissions as follows: o To make a file non-executable, rsync turns off all its 'x' permissions. o To make a file executable, rsync turns on each 'x' permission that has a corresponding 'r' permission enabled. If --perms is enabled, this option is ignored. --acls, -A This option causes rsync to update the destination ACLs to be the same as the source ACLs. The option also implies --perms. The source and destination systems must have compatible ACL entries for this option to work properly. See the --fake-super option for a way to backup and restore ACLs that are not compatible. --xattrs, -X This option causes rsync to update the destination extended attributes to be the same as the source ones. For systems that support extended-attribute namespaces, a copy being done by a super-user copies all namespaces except system.*. A normal user only copies the user.* namespace. To be able to backup and restore non-user namespaces as a normal user, see the --fake-super option. The above name filtering can be overridden by using one or more filter options with the x modifier. When you specify an xattr-affecting filter rule, rsync requires that you do your own system/user filtering, as well as any additional filtering for what xattr names are copied and what names are allowed to be deleted. For example, to skip the system namespace, you could specify: --filter='-x system.*' To skip all namespaces except the user namespace, you could specify a negated-user match: --filter='-x! user.*' To prevent any attributes from being deleted, you could specify a receiver-only rule that excludes all names: --filter='-xr *' Note that the -X option does not copy rsync's special xattr values (e.g. those used by --fake-super) unless you repeat the option (e.g. -XX). This "copy all xattrs" mode cannot be used with --fake-super. --chmod=CHMOD This option tells rsync to apply one or more comma- separated "chmod" modes to the permission of the files in the transfer. The resulting value is treated as though it were the permissions that the sending side supplied for the file, which means that this option can seem to have no effect on existing files if --perms is not enabled. In addition to the normal parsing rules specified in the chmod(1) manpage, you can specify an item that should only apply to a directory by prefixing it with a 'D', or specify an item that should only apply to a file by prefixing it with a 'F'. For example, the following will ensure that all directories get marked set-gid, that no files are other-writable, that both are user-writable and group-writable, and that both have consistent executability across all bits: --chmod=Dg+s,ug+w,Fo-w,+X Using octal mode numbers is also allowed: --chmod=D2775,F664 It is also legal to specify multiple --chmod options, as each additional option is just appended to the list of changes to make. See the --perms and --executability options for how the resulting permission value can be applied to the files in the transfer. --owner, -o This option causes rsync to set the owner of the destination file to be the same as the source file, but only if the receiving rsync is being run as the super-user (see also the --super and --fake-super options). Without this option, the owner of new and/or transferred files are set to the invoking user on the receiving side. The preservation of ownership will associate matching names by default, but may fall back to using the ID number in some circumstances (see also the --numeric-ids option for a full discussion). --group, -g This option causes rsync to set the group of the destination file to be the same as the source file. If the receiving program is not running as the super-user (or if --no-super was specified), only groups that the invoking user on the receiving side is a member of will be preserved. Without this option, the group is set to the default group of the invoking user on the receiving side. The preservation of group information will associate matching names by default, but may fall back to using the ID number in some circumstances (see also the --numeric- ids option for a full discussion). --devices This option causes rsync to transfer character and block device files to the remote system to recreate these devices. If the receiving rsync is not being run as the super-user, rsync silently skips creating the device files (see also the --super and --fake-super options). By default, rsync generates a "non-regular file" warning for each device file encountered when this option is not set. You can silence the warning by specifying --info=nonreg0. --specials This option causes rsync to transfer special files, such as named sockets and fifos. If the receiving rsync is not being run as the super-user, rsync silently skips creating the special files (see also the --super and --fake-super options). By default, rsync generates a "non-regular file" warning for each special file encountered when this option is not set. You can silence the warning by specifying --info=nonreg0. -D The -D option is equivalent to "--devices --specials". --copy-devices This tells rsync to treat a device on the sending side as a regular file, allowing it to be copied to a normal destination file (or another device if --write-devices was also specified). This option is refused by default by an rsync daemon. --write-devices This tells rsync to treat a device on the receiving side as a regular file, allowing the writing of file data into a device. This option implies the --inplace option. Be careful using this, as you should know what devices are present on the receiving side of the transfer, especially when running rsync as root. This option is refused by default by an rsync daemon. --times, -t This tells rsync to transfer modification times along with the files and update them on the remote system. Note that if this option is not used, the optimization that excludes files that have not been modified cannot be effective; in other words, a missing -t (or -a) will cause the next transfer to behave as if it used --ignore-times (-I), causing all files to be updated (though rsync's delta- transfer algorithm will make the update fairly efficient if the files haven't actually changed, you're much better off using -t). A modern rsync that is using transfer protocol 30 or 31 conveys a modify time using up to 8-bytes. If rsync is forced to speak an older protocol (perhaps due to the remote rsync being older than 3.0.0) a modify time is conveyed using 4-bytes. Prior to 3.2.7, these shorter values could convey a date range of 13-Dec-1901 to 19-Jan-2038. Beginning with 3.2.7, these 4-byte values now convey a date range of 1-Jan-1970 to 7-Feb-2106. If you have files dated older than 1970, make sure your rsync executables are upgraded so that the full range of dates can be conveyed. --atimes, -U This tells rsync to set the access (use) times of the destination files to the same value as the source files. If repeated, it also sets the --open-noatime option, which can help you to make the sending and receiving systems have the same access times on the transferred files without needing to run rsync an extra time after a file is transferred. Note that some older rsync versions (prior to 3.2.0) may have been built with a pre-release --atimes patch that does not imply --open-noatime when this option is repeated. --open-noatime This tells rsync to open files with the O_NOATIME flag (on systems that support it) to avoid changing the access time of the files that are being transferred. If your OS does not support the O_NOATIME flag then rsync will silently ignore this option. Note also that some filesystems are mounted to avoid updating the atime on read access even without the O_NOATIME flag being set. --crtimes, -N, This tells rsync to set the create times (newness) of the destination files to the same value as the source files. --omit-dir-times, -O This tells rsync to omit directories when it is preserving modification, access, and create times. If NFS is sharing the directories on the receiving side, it is a good idea to use -O. This option is inferred if you use --backup without --backup-dir. This option also has the side-effect of avoiding early creation of missing sub-directories when incremental recursion is enabled, as discussed in the --inc-recursive section. --omit-link-times, -J This tells rsync to omit symlinks when it is preserving modification, access, and create times. --super This tells the receiving side to attempt super-user activities even if the receiving rsync wasn't run by the super-user. These activities include: preserving users via the --owner option, preserving all groups (not just the current user's groups) via the --group option, and copying devices via the --devices option. This is useful for systems that allow such activities without being the super-user, and also for ensuring that you will get errors if the receiving side isn't being run as the super-user. To turn off super-user activities, the super-user can use --no-super. --fake-super When this option is enabled, rsync simulates super-user activities by saving/restoring the privileged attributes via special extended attributes that are attached to each file (as needed). This includes the file's owner and group (if it is not the default), the file's device info (device & special files are created as empty text files), and any permission bits that we won't allow to be set on the real file (e.g. the real file gets u-s,g-s,o-t for safety) or that would limit the owner's access (since the real super-user can always access/change a file, the files we create can always be accessed/changed by the creating user). This option also handles ACLs (if --acls was specified) and non-user extended attributes (if --xattrs was specified). This is a good way to backup data without using a super- user, and to store ACLs from incompatible systems. The --fake-super option only affects the side where the option is used. To affect the remote side of a remote- shell connection, use the --remote-option (-M) option: rsync -av -M--fake-super /src/ host:/dest/ For a local copy, this option affects both the source and the destination. If you wish a local copy to enable this option just for the destination files, specify -M--fake- super. If you wish a local copy to enable this option just for the source files, combine --fake-super with -M--super. This option is overridden by both --super and --no-super. See also the fake super setting in the daemon's rsyncd.conf file. --sparse, -S Try to handle sparse files efficiently so they take up less space on the destination. If combined with --inplace the file created might not end up with sparse blocks with some combinations of kernel version and/or filesystem type. If --whole-file is in effect (e.g. for a local copy) then it will always work because rsync truncates the file prior to writing out the updated version. Note that versions of rsync older than 3.1.3 will reject the combination of --sparse and --inplace. --preallocate This tells the receiver to allocate each destination file to its eventual size before writing data to the file. Rsync will only use the real filesystem-level preallocation support provided by Linux's fallocate(2) system call or Cygwin's posix_fallocate(3), not the slow glibc implementation that writes a null byte into each block. Without this option, larger files may not be entirely contiguous on the filesystem, but with this option rsync will probably copy more slowly. If the destination is not an extent-supporting filesystem (such as ext4, xfs, NTFS, etc.), this option may have no positive effect at all. If combined with --sparse, the file will only have sparse blocks (as opposed to allocated sequences of null bytes) if the kernel version and filesystem type support creating holes in the allocated data. --dry-run, -n This makes rsync perform a trial run that doesn't make any changes (and produces mostly the same output as a real run). It is most commonly used in combination with the --verbose (-v) and/or --itemize-changes (-i) options to see what an rsync command is going to do before one actually runs it. The output of --itemize-changes is supposed to be exactly the same on a dry run and a subsequent real run (barring intentional trickery and system call failures); if it isn't, that's a bug. Other output should be mostly unchanged, but may differ in some areas. Notably, a dry run does not send the actual data for file transfers, so --progress has no effect, the "bytes sent", "bytes received", "literal data", and "matched data" statistics are too small, and the "speedup" value is equivalent to a run where no file transfers were needed. --whole-file, -W This option disables rsync's delta-transfer algorithm, which causes all transferred files to be sent whole. The transfer may be faster if this option is used when the bandwidth between the source and destination machines is higher than the bandwidth to disk (especially when the "disk" is actually a networked filesystem). This is the default when both the source and destination are specified as local paths, but only if no batch-writing option is in effect. --no-whole-file, --no-W Disable whole-file updating when it is enabled by default for a local transfer. This usually slows rsync down, but it can be useful if you are trying to minimize the writes to the destination file (if combined with --inplace) or for testing the checksum-based update algorithm. See also the --whole-file option. --checksum-choice=STR, --cc=STR This option overrides the checksum algorithms. If one algorithm name is specified, it is used for both the transfer checksums and (assuming --checksum is specified) the pre-transfer checksums. If two comma-separated names are supplied, the first name affects the transfer checksums, and the second name affects the pre-transfer checksums (-c). The checksum options that you may be able to use are: o auto (the default automatic choice) o xxh128 o xxh3 o xxh64 (aka xxhash) o md5 o md4 o sha1 o none Run rsync --version to see the default checksum list compiled into your version (which may differ from the list above). If "none" is specified for the first (or only) name, the --whole-file option is forced on and no checksum verification is performed on the transferred data. If "none" is specified for the second (or only) name, the --checksum option cannot be used. The "auto" option is the default, where rsync bases its algorithm choice on a negotiation between the client and the server as follows: When both sides of the transfer are at least 3.2.0, rsync chooses the first algorithm in the client's list of choices that is also in the server's list of choices. If no common checksum choice is found, rsync exits with an error. If the remote rsync is too old to support checksum negotiation, a value is chosen based on the protocol version (which chooses between MD5 and various flavors of MD4 based on protocol age). The default order can be customized by setting the environment variable RSYNC_CHECKSUM_LIST to a space- separated list of acceptable checksum names. If the string contains a "&" character, it is separated into the "client string & server string", otherwise the same string applies to both. If the string (or string portion) contains no non-whitespace characters, the default checksum list is used. This method does not allow you to specify the transfer checksum separately from the pre- transfer checksum, and it discards "auto" and all unknown checksum names. A list with only invalid names results in a failed negotiation. The use of the --checksum-choice option overrides this environment list. --one-file-system, -x This tells rsync to avoid crossing a filesystem boundary when recursing. This does not limit the user's ability to specify items to copy from multiple filesystems, just rsync's recursion through the hierarchy of each directory that the user specified, and also the analogous recursion on the receiving side during deletion. Also keep in mind that rsync treats a "bind" mount to the same device as being on the same filesystem. If this option is repeated, rsync omits all mount-point directories from the copy. Otherwise, it includes an empty directory at each mount-point it encounters (using the attributes of the mounted directory because those of the underlying mount-point directory are inaccessible). If rsync has been told to collapse symlinks (via --copy- links or --copy-unsafe-links), a symlink to a directory on another device is treated like a mount-point. Symlinks to non-directories are unaffected by this option. --ignore-non-existing, --existing This tells rsync to skip creating files (including directories) that do not exist yet on the destination. If this option is combined with the --ignore-existing option, no files will be updated (which can be useful if all you want to do is delete extraneous files). This option is a TRANSFER RULE, so don't expect any exclude side effects. --ignore-existing This tells rsync to skip updating files that already exist on the destination (this does not ignore existing directories, or nothing would get done). See also --ignore-non-existing. This option is a TRANSFER RULE, so don't expect any exclude side effects. This option can be useful for those doing backups using the --link-dest option when they need to continue a backup run that got interrupted. Since a --link-dest run is copied into a new directory hierarchy (when it is used properly), using [--ignore-existing will ensure that the already-handled files don't get tweaked (which avoids a change in permissions on the hard-linked files). This does mean that this option is only looking at the existing files in the destination hierarchy itself. When --info=skip2 is used rsync will output "FILENAME exists (INFO)" messages where the INFO indicates one of "type change", "sum change" (requires -c), "file change" (based on the quick check), "attr change", or "uptodate". Using --info=skip1 (which is also implied by 2 -v options) outputs the exists message without the INFO suffix. --remove-source-files This tells rsync to remove from the sending side the files (meaning non-directories) that are a part of the transfer and have been successfully duplicated on the receiving side. Note that you should only use this option on source files that are quiescent. If you are using this to move files that show up in a particular directory over to another host, make sure that the finished files get renamed into the source directory, not directly written into it, so that rsync can't possibly transfer a file that is not yet fully written. If you can't first write the files into a different directory, you should use a naming idiom that lets rsync avoid transferring files that are not yet finished (e.g. name the file "foo.new" when it is written, rename it to "foo" when it is done, and then use the option --exclude='*.new' for the rsync transfer). Starting with 3.1.0, rsync will skip the sender-side removal (and output an error) if the file's size or modify time has not stayed unchanged. Starting with 3.2.6, a local rsync copy will ensure that the sender does not remove a file the receiver just verified, such as when the user accidentally makes the source and destination directory the same path. --delete This tells rsync to delete extraneous files from the receiving side (ones that aren't on the sending side), but only for the directories that are being synchronized. You must have asked rsync to send the whole directory (e.g. "dir" or "dir/") without using a wildcard for the directory's contents (e.g. "dir/*") since the wildcard is expanded by the shell and rsync thus gets a request to transfer individual files, not the files' parent directory. Files that are excluded from the transfer are also excluded from being deleted unless you use the --delete-excluded option or mark the rules as only matching on the sending side (see the include/exclude modifiers in the FILTER RULES section). Prior to rsync 2.6.7, this option would have no effect unless --recursive was enabled. Beginning with 2.6.7, deletions will also occur when --dirs (-d) is enabled, but only for directories whose contents are being copied. This option can be dangerous if used incorrectly! It is a very good idea to first try a run using the --dry-run (-n) option to see what files are going to be deleted. If the sending side detects any I/O errors, then the deletion of any files at the destination will be automatically disabled. This is to prevent temporary filesystem failures (such as NFS errors) on the sending side from causing a massive deletion of files on the destination. You can override this with the --ignore- errors option. The --delete option may be combined with one of the --delete-WHEN options without conflict, as well as --delete-excluded. However, if none of the --delete-WHEN options are specified, rsync will choose the --delete- during algorithm when talking to rsync 3.0.0 or newer, or the --delete-before algorithm when talking to an older rsync. See also --delete-delay and --delete-after. --delete-before Request that the file-deletions on the receiving side be done before the transfer starts. See --delete (which is implied) for more details on file-deletion. Deleting before the transfer is helpful if the filesystem is tight for space and removing extraneous files would help to make the transfer possible. However, it does introduce a delay before the start of the transfer, and this delay might cause the transfer to timeout (if --timeout was specified). It also forces rsync to use the old, non-incremental recursion algorithm that requires rsync to scan all the files in the transfer into memory at once (see --recursive). --delete-during, --del Request that the file-deletions on the receiving side be done incrementally as the transfer happens. The per- directory delete scan is done right before each directory is checked for updates, so it behaves like a more efficient --delete-before, including doing the deletions prior to any per-directory filter files being updated. This option was first added in rsync version 2.6.4. See --delete (which is implied) for more details on file- deletion. --delete-delay Request that the file-deletions on the receiving side be computed during the transfer (like --delete-during), and then removed after the transfer completes. This is useful when combined with --delay-updates and/or --fuzzy, and is more efficient than using --delete-after (but can behave differently, since --delete-after computes the deletions in a separate pass after all updates are done). If the number of removed files overflows an internal buffer, a temporary file will be created on the receiving side to hold the names (it is removed while open, so you shouldn't see it during the transfer). If the creation of the temporary file fails, rsync will try to fall back to using --delete-after (which it cannot do if --recursive is doing an incremental scan). See --delete (which is implied) for more details on file-deletion. --delete-after Request that the file-deletions on the receiving side be done after the transfer has completed. This is useful if you are sending new per-directory merge files as a part of the transfer and you want their exclusions to take effect for the delete phase of the current transfer. It also forces rsync to use the old, non-incremental recursion algorithm that requires rsync to scan all the files in the transfer into memory at once (see --recursive). See --delete (which is implied) for more details on file- deletion. See also the --delete-delay option that might be a faster choice for those that just want the deletions to occur at the end of the transfer. --delete-excluded This option turns any unqualified exclude/include rules into server-side rules that do not affect the receiver's deletions. By default, an exclude or include has both a server-side effect (to "hide" and "show" files when building the server's file list) and a receiver-side effect (to "protect" and "risk" files when deletions are occurring). Any rule that has no modifier to specify what sides it is executed on will be instead treated as if it were a server-side rule only, avoiding any "protect" effects of the rules. A rule can still apply to both sides even with this option specified if the rule is given both the sender & receiver modifier letters (e.g., -f'-sr foo'). Receiver-side protect/risk rules can also be explicitly specified to limit the deletions. This saves you from having to edit a bunch of -f'- foo' rules into -f'-s foo' (aka -f'H foo') rules (not to mention the corresponding includes). See the FILTER RULES section for more information. See --delete (which is implied) for more details on deletion. --ignore-missing-args When rsync is first processing the explicitly requested source files (e.g. command-line arguments or --files-from entries), it is normally an error if the file cannot be found. This option suppresses that error, and does not try to transfer the file. This does not affect subsequent vanished-file errors if a file was initially found to be present and later is no longer there. --delete-missing-args This option takes the behavior of the (implied) --ignore- missing-args option a step farther: each missing arg will become a deletion request of the corresponding destination file on the receiving side (should it exist). If the destination file is a non-empty directory, it will only be successfully deleted if --force or --delete are in effect. Other than that, this option is independent of any other type of delete processing. The missing source files are represented by special file- list entries which display as a "*missing" entry in the --list-only output. --ignore-errors Tells --delete to go ahead and delete files even when there are I/O errors. --force This option tells rsync to delete a non-empty directory when it is to be replaced by a non-directory. This is only relevant if deletions are not active (see --delete for details). Note for older rsync versions: --force used to still be required when using --delete-after, and it used to be non- functional unless the --recursive option was also enabled. --max-delete=NUM This tells rsync not to delete more than NUM files or directories. If that limit is exceeded, all further deletions are skipped through the end of the transfer. At the end, rsync outputs a warning (including a count of the skipped deletions) and exits with an error code of 25 (unless some more important error condition also occurred). Beginning with version 3.0.0, you may specify --max- delete=0 to be warned about any extraneous files in the destination without removing any of them. Older clients interpreted this as "unlimited", so if you don't know what version the client is, you can use the less obvious --max- delete=-1 as a backward-compatible way to specify that no deletions be allowed (though really old versions didn't warn when the limit was exceeded). --max-size=SIZE This tells rsync to avoid transferring any file that is larger than the specified SIZE. A numeric value can be suffixed with a string to indicate the numeric units or left unqualified to specify bytes. Feel free to use a fractional value along with the units, such as --max- size=1.5m. This option is a TRANSFER RULE, so don't expect any exclude side effects. The first letter of a units string can be B (bytes), K (kilo), M (mega), G (giga), T (tera), or P (peta). If the string is a single char or has "ib" added to it (e.g. "G" or "GiB") then the units are multiples of 1024. If you use a two-letter suffix that ends with a "B" (e.g. "kb") then you get units that are multiples of 1000. The string's letters can be any mix of upper and lower-case that you want to use. Finally, if the string ends with either "+1" or "-1", it is offset by one byte in the indicated direction. The largest possible value is usually 8192P-1. Examples: --max-size=1.5mb-1 is 1499999 bytes, and --max- size=2g+1 is 2147483649 bytes. Note that rsync versions prior to 3.1.0 did not allow --max-size=0. --min-size=SIZE This tells rsync to avoid transferring any file that is smaller than the specified SIZE, which can help in not transferring small, junk files. See the --max-size option for a description of SIZE and other info. Note that rsync versions prior to 3.1.0 did not allow --min-size=0. --max-alloc=SIZE By default rsync limits an individual malloc/realloc to about 1GB in size. For most people this limit works just fine and prevents a protocol error causing rsync to request massive amounts of memory. However, if you have many millions of files in a transfer, a large amount of server memory, and you don't want to split up your transfer into multiple parts, you can increase the per- allocation limit to something larger and rsync will consume more memory. Keep in mind that this is not a limit on the total size of allocated memory. It is a sanity-check value for each individual allocation. See the --max-size option for a description of how SIZE can be specified. The default suffix if none is given is bytes. Beginning in 3.2.3, a value of 0 specifies no limit. You can set a default value using the environment variable RSYNC_MAX_ALLOC using the same SIZE values as supported by this option. If the remote rsync doesn't understand the --max-alloc option, you can override an environmental value by specifying --max-alloc=1g, which will make rsync avoid sending the option to the remote side (because "1G" is the default). --block-size=SIZE, -B This forces the block size used in rsync's delta-transfer algorithm to a fixed value. It is normally selected based on the size of each file being updated. See the technical report for details. Beginning in 3.2.3 the SIZE can be specified with a suffix as detailed in the --max-size option. Older versions only accepted a byte count. --rsh=COMMAND, -e This option allows you to choose an alternative remote shell program to use for communication between the local and remote copies of rsync. Typically, rsync is configured to use ssh by default, but you may prefer to use rsh on a local network. If this option is used with [user@]host::module/path, then the remote shell COMMAND will be used to run an rsync daemon on the remote host, and all data will be transmitted through that remote shell connection, rather than through a direct socket connection to a running rsync daemon on the remote host. See the USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION section above. Beginning with rsync 3.2.0, the RSYNC_PORT environment variable will be set when a daemon connection is being made via a remote-shell connection. It is set to 0 if the default daemon port is being assumed, or it is set to the value of the rsync port that was specified via either the --port option or a non-empty port value in an rsync:// URL. This allows the script to discern if a non-default port is being requested, allowing for things such as an SSL or stunnel helper script to connect to a default or alternate port. Command-line arguments are permitted in COMMAND provided that COMMAND is presented to rsync as a single argument. You must use spaces (not tabs or other whitespace) to separate the command and args from each other, and you can use single- and/or double-quotes to preserve spaces in an argument (but not backslashes). Note that doubling a single-quote inside a single-quoted string gives you a single-quote; likewise for double-quotes (though you need to pay attention to which quotes your shell is parsing and which quotes rsync is parsing). Some examples: -e 'ssh -p 2234' -e 'ssh -o "ProxyCommand nohup ssh firewall nc -w1 %h %p"' (Note that ssh users can alternately customize site- specific connect options in their .ssh/config file.) You can also choose the remote shell program using the RSYNC_RSH environment variable, which accepts the same range of values as -e. See also the --blocking-io option which is affected by this option. --rsync-path=PROGRAM Use this to specify what program is to be run on the remote machine to start-up rsync. Often used when rsync is not in the default remote-shell's path (e.g. --rsync- path=/usr/local/bin/rsync). Note that PROGRAM is run with the help of a shell, so it can be any program, script, or command sequence you'd care to run, so long as it does not corrupt the standard-in & standard-out that rsync is using to communicate. One tricky example is to set a different default directory on the remote machine for use with the --relative option. For instance: rsync -avR --rsync-path="cd /a/b && rsync" host:c/d /e/ --remote-option=OPTION, -M This option is used for more advanced situations where you want certain effects to be limited to one side of the transfer only. For instance, if you want to pass --log- file=FILE and --fake-super to the remote system, specify it like this: rsync -av -M --log-file=foo -M--fake-super src/ dest/ If you want to have an option affect only the local side of a transfer when it normally affects both sides, send its negation to the remote side. Like this: rsync -av -x -M--no-x src/ dest/ Be cautious using this, as it is possible to toggle an option that will cause rsync to have a different idea about what data to expect next over the socket, and that will make it fail in a cryptic fashion. Note that you should use a separate -M option for each remote option you want to pass. On older rsync versions, the presence of any spaces in the remote-option arg could cause it to be split into separate remote args, but this requires the use of --old-args in a modern rsync. When performing a local transfer, the "local" side is the sender and the "remote" side is the receiver. Note some versions of the popt option-parsing library have a bug in them that prevents you from using an adjacent arg with an equal in it next to a short option letter (e.g. -M--log-file=/tmp/foo). If this bug affects your version of popt, you can use the version of popt that is included with rsync. --cvs-exclude, -C This is a useful shorthand for excluding a broad range of files that you often don't want to transfer between systems. It uses a similar algorithm to CVS to determine if a file should be ignored. The exclude list is initialized to exclude the following items (these initial items are marked as perishable -- see the FILTER RULES section): RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS .make.state .nse_depinfo *~ #* .#* ,* _$* *$ *.old *.bak *.BAK *.orig *.rej .del-* *.a *.olb *.o *.obj *.so *.exe *.Z *.elc *.ln core .svn/ .git/ .hg/ .bzr/ then, files listed in a $HOME/.cvsignore are added to the list and any files listed in the CVSIGNORE environment variable (all cvsignore names are delimited by whitespace). Finally, any file is ignored if it is in the same directory as a .cvsignore file and matches one of the patterns listed therein. Unlike rsync's filter/exclude files, these patterns are split on whitespace. See the cvs(1) manual for more information. If you're combining -C with your own --filter rules, you should note that these CVS excludes are appended at the end of your own rules, regardless of where the -C was placed on the command-line. This makes them a lower priority than any rules you specified explicitly. If you want to control where these CVS excludes get inserted into your filter rules, you should omit the -C as a command- line option and use a combination of --filter=:C and --filter=-C (either on your command-line or by putting the ":C" and "-C" rules into a filter file with your other rules). The first option turns on the per-directory scanning for the .cvsignore file. The second option does a one-time import of the CVS excludes mentioned above. --filter=RULE, -f This option allows you to add rules to selectively exclude certain files from the list of files to be transferred. This is most useful in combination with a recursive transfer. You may use as many --filter options on the command line as you like to build up the list of files to exclude. If the filter contains whitespace, be sure to quote it so that the shell gives the rule to rsync as a single argument. The text below also mentions that you can use an underscore to replace the space that separates a rule from its arg. See the FILTER RULES section for detailed information on this option. -F The -F option is a shorthand for adding two --filter rules to your command. The first time it is used is a shorthand for this rule: --filter='dir-merge /.rsync-filter' This tells rsync to look for per-directory .rsync-filter files that have been sprinkled through the hierarchy and use their rules to filter the files in the transfer. If -F is repeated, it is a shorthand for this rule: --filter='exclude .rsync-filter' This filters out the .rsync-filter files themselves from the transfer. See the FILTER RULES section for detailed information on how these options work. --exclude=PATTERN This option is a simplified form of the --filter option that specifies an exclude rule and does not allow the full rule-parsing syntax of normal filter rules. This is equivalent to specifying -f'- PATTERN'. See the FILTER RULES section for detailed information on this option. --exclude-from=FILE This option is related to the --exclude option, but it specifies a FILE that contains exclude patterns (one per line). Blank lines in the file are ignored, as are whole- line comments that start with ';' or '#' (filename rules that contain those characters are unaffected). If a line begins with "- " (dash, space) or "+ " (plus, space), then the type of rule is being explicitly specified as an exclude or an include (respectively). Any rules without such a prefix are taken to be an exclude. If a line consists of just "!", then the current filter rules are cleared before adding any further rules. If FILE is '-', the list will be read from standard input. --include=PATTERN This option is a simplified form of the --filter option that specifies an include rule and does not allow the full rule-parsing syntax of normal filter rules. This is equivalent to specifying -f'+ PATTERN'. See the FILTER RULES section for detailed information on this option. --include-from=FILE This option is related to the --include option, but it specifies a FILE that contains include patterns (one per line). Blank lines in the file are ignored, as are whole- line comments that start with ';' or '#' (filename rules that contain those characters are unaffected). If a line begins with "- " (dash, space) or "+ " (plus, space), then the type of rule is being explicitly specified as an exclude or an include (respectively). Any rules without such a prefix are taken to be an include. If a line consists of just "!", then the current filter rules are cleared before adding any further rules. If FILE is '-', the list will be read from standard input. --files-from=FILE Using this option allows you to specify the exact list of files to transfer (as read from the specified FILE or '-' for standard input). It also tweaks the default behavior of rsync to make transferring just the specified files and directories easier: o The --relative (-R) option is implied, which preserves the path information that is specified for each item in the file (use --no-relative or --no-R if you want to turn that off). o The --dirs (-d) option is implied, which will create directories specified in the list on the destination rather than noisily skipping them (use --no-dirs or --no-d if you want to turn that off). o The --archive (-a) option's behavior does not imply --recursive (-r), so specify it explicitly, if you want it. o These side-effects change the default state of rsync, so the position of the --files-from option on the command-line has no bearing on how other options are parsed (e.g. -a works the same before or after --files-from, as does --no-R and all other options). The filenames that are read from the FILE are all relative to the source dir -- any leading slashes are removed and no ".." references are allowed to go higher than the source dir. For example, take this command: rsync -a --files-from=/tmp/foo /usr remote:/backup If /tmp/foo contains the string "bin" (or even "/bin"), the /usr/bin directory will be created as /backup/bin on the remote host. If it contains "bin/" (note the trailing slash), the immediate contents of the directory would also be sent (without needing to be explicitly mentioned in the file -- this began in version 2.6.4). In both cases, if the -r option was enabled, that dir's entire hierarchy would also be transferred (keep in mind that -r needs to be specified explicitly with --files-from, since it is not implied by -a. Also note that the effect of the (enabled by default) -r option is to duplicate only the path info that is read from the file -- it does not force the duplication of the source-spec path (/usr in this case). In addition, the --files-from file can be read from the remote host instead of the local host if you specify a "host:" in front of the file (the host must match one end of the transfer). As a short-cut, you can specify just a prefix of ":" to mean "use the remote end of the transfer". For example: rsync -a --files-from=:/path/file-list src:/ /tmp/copy This would copy all the files specified in the /path/file- list file that was located on the remote "src" host. If the --iconv and --secluded-args options are specified and the --files-from filenames are being sent from one host to another, the filenames will be translated from the sending host's charset to the receiving host's charset. NOTE: sorting the list of files in the --files-from input helps rsync to be more efficient, as it will avoid re- visiting the path elements that are shared between adjacent entries. If the input is not sorted, some path elements (implied directories) may end up being scanned multiple times, and rsync will eventually unduplicate them after they get turned into file-list elements. --from0, -0 This tells rsync that the rules/filenames it reads from a file are terminated by a null ('\0') character, not a NL, CR, or CR+LF. This affects --exclude-from, --include- from, --files-from, and any merged files specified in a --filter rule. It does not affect --cvs-exclude (since all names read from a .cvsignore file are split on whitespace). --old-args This option tells rsync to stop trying to protect the arg values on the remote side from unintended word-splitting or other misinterpretation. It also allows the client to treat an empty arg as a "." instead of generating an error. The default in a modern rsync is for "shell-active" characters (including spaces) to be backslash-escaped in the args that are sent to the remote shell. The wildcard characters *, ?, [, & ] are not escaped in filename args (allowing them to expand into multiple filenames) while being protected in option args, such as --usermap. If you have a script that wants to use old-style arg splitting in its filenames, specify this option once. If the remote shell has a problem with any backslash escapes at all, specify this option twice. You may also control this setting via the RSYNC_OLD_ARGS environment variable. If it has the value "1", rsync will default to a single-option setting. If it has the value "2" (or more), rsync will default to a repeated-option setting. If it is "0", you'll get the default escaping behavior. The environment is always overridden by manually specified positive or negative options (the negative is --no-old-args). Note that this option also disables the extra safety check added in 3.2.5 that ensures that a remote sender isn't including extra top-level items in the file-list that you didn't request. This side-effect is necessary because we can't know for sure what names to expect when the remote shell is interpreting the args. This option conflicts with the --secluded-args option. --secluded-args, -s This option sends all filenames and most options to the remote rsync via the protocol (not the remote shell command line) which avoids letting the remote shell modify them. Wildcards are expanded on the remote host by rsync instead of a shell. This is similar to the default backslash-escaping of args that was added in 3.2.4 (see --old-args) in that it prevents things like space splitting and unwanted special- character side-effects. However, it has the drawbacks of being incompatible with older rsync versions (prior to 3.0.0) and of being refused by restricted shells that want to be able to inspect all the option values for safety. This option is useful for those times that you need the argument's character set to be converted for the remote host, if the remote shell is incompatible with the default backslash-escpaing method, or there is some other reason that you want the majority of the options and arguments to bypass the command-line of the remote shell. If you combine this option with --iconv, the args related to the remote side will be translated from the local to the remote character-set. The translation happens before wild-cards are expanded. See also the --files-from option. You may also control this setting via the RSYNC_PROTECT_ARGS environment variable. If it has a non- zero value, this setting will be enabled by default, otherwise it will be disabled by default. Either state is overridden by a manually specified positive or negative version of this option (note that --no-s and --no- secluded-args are the negative versions). This environment variable is also superseded by a non-zero RSYNC_OLD_ARGS export. This option conflicts with the --old-args option. This option used to be called --protect-args (before 3.2.6) and that older name can still be used (though specifying it as -s is always the easiest and most compatible choice). --trust-sender This option disables two extra validation checks that a local client performs on the file list generated by a remote sender. This option should only be used if you trust the sender to not put something malicious in the file list (something that could possibly be done via a modified rsync, a modified shell, or some other similar manipulation). Normally, the rsync client (as of version 3.2.5) runs two extra validation checks when pulling files from a remote rsync: o It verifies that additional arg items didn't get added at the top of the transfer. o It verifies that none of the items in the file list are names that should have been excluded (if filter rules were specified). Note that various options can turn off one or both of these checks if the option interferes with the validation. For instance: o Using a per-directory filter file reads filter rules that only the server knows about, so the filter checking is disabled. o Using the --old-args option allows the sender to manipulate the requested args, so the arg checking is disabled. o Reading the files-from list from the server side means that the client doesn't know the arg list, so the arg checking is disabled. o Using --read-batch disables both checks since the batch file's contents will have been verified when it was created. This option may help an under-powered client server if the extra pattern matching is slowing things down on a huge transfer. It can also be used to work around a currently- unknown bug in the verification logic for a transfer from a trusted sender. When using this option it is a good idea to specify a dedicated destination directory, as discussed in the MULTI-HOST SECURITY section. --copy-as=USER[:GROUP] This option instructs rsync to use the USER and (if specified after a colon) the GROUP for the copy operations. This only works if the user that is running rsync has the ability to change users. If the group is not specified then the user's default groups are used. This option can help to reduce the risk of an rsync being run as root into or out of a directory that might have live changes happening to it and you want to make sure that root-level read or write actions of system files are not possible. While you could alternatively run all of rsync as the specified user, sometimes you need the root- level host-access credentials to be used, so this allows rsync to drop root for the copying part of the operation after the remote-shell or daemon connection is established. The option only affects one side of the transfer unless the transfer is local, in which case it affects both sides. Use the --remote-option to affect the remote side, such as -M--copy-as=joe. For a local transfer, the lsh (or lsh.sh) support file provides a local-shell helper script that can be used to allow a "localhost:" or "lh:" host-spec to be specified without needing to setup any remote shells, allowing you to specify remote options that affect the side of the transfer that is using the host- spec (and using hostname "lh" avoids the overriding of the remote directory to the user's home dir). For example, the following rsync writes the local files as user "joe": sudo rsync -aiv --copy-as=joe host1:backups/joe/ /home/joe/ This makes all files owned by user "joe", limits the groups to those that are available to that user, and makes it impossible for the joe user to do a timed exploit of the path to induce a change to a file that the joe user has no permissions to change. The following command does a local copy into the "dest/" dir as user "joe" (assuming you've installed support/lsh into a dir on your $PATH): sudo rsync -aive lsh -M--copy-as=joe src/ lh:dest/ --temp-dir=DIR, -T This option instructs rsync to use DIR as a scratch directory when creating temporary copies of the files transferred on the receiving side. The default behavior is to create each temporary file in the same directory as the associated destination file. Beginning with rsync 3.1.1, the temp-file names inside the specified DIR will not be prefixed with an extra dot (though they will still have a random suffix added). This option is most often used when the receiving disk partition does not have enough free space to hold a copy of the largest file in the transfer. In this case (i.e. when the scratch directory is on a different disk partition), rsync will not be able to rename each received temporary file over the top of the associated destination file, but instead must copy it into place. Rsync does this by copying the file over the top of the destination file, which means that the destination file will contain truncated data during this copy. If this were not done this way (even if the destination file were first removed, the data locally copied to a temporary file in the destination directory, and then renamed into place) it would be possible for the old file to continue taking up disk space (if someone had it open), and thus there might not be enough room to fit the new version on the disk at the same time. If you are using this option for reasons other than a shortage of disk space, you may wish to combine it with the --delay-updates option, which will ensure that all copied files get put into subdirectories in the destination hierarchy, awaiting the end of the transfer. If you don't have enough room to duplicate all the arriving files on the destination partition, another way to tell rsync that you aren't overly concerned about disk space is to use the --partial-dir option with a relative path; because this tells rsync that it is OK to stash off a copy of a single file in a subdir in the destination hierarchy, rsync will use the partial-dir as a staging area to bring over the copied file, and then rename it into place from there. (Specifying a --partial-dir with an absolute path does not have this side-effect.) --fuzzy, -y This option tells rsync that it should look for a basis file for any destination file that is missing. The current algorithm looks in the same directory as the destination file for either a file that has an identical size and modified-time, or a similarly-named file. If found, rsync uses the fuzzy basis file to try to speed up the transfer. If the option is repeated, the fuzzy scan will also be done in any matching alternate destination directories that are specified via --compare-dest, --copy-dest, or --link-dest. Note that the use of the --delete option might get rid of any potential fuzzy-match files, so either use --delete- after or specify some filename exclusions if you need to prevent this. --compare-dest=DIR This option instructs rsync to use DIR on the destination machine as an additional hierarchy to compare destination files against doing transfers (if the files are missing in the destination directory). If a file is found in DIR that is identical to the sender's file, the file will NOT be transferred to the destination directory. This is useful for creating a sparse backup of just files that have changed from an earlier backup. This option is typically used to copy into an empty (or newly created) directory. Beginning in version 2.6.4, multiple --compare-dest directories may be provided, which will cause rsync to search the list in the order specified for an exact match. If a match is found that differs only in attributes, a local copy is made and the attributes updated. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. If DIR is a relative path, it is relative to the destination directory. See also --copy-dest and --link- dest. NOTE: beginning with version 3.1.0, rsync will remove a file from a non-empty destination hierarchy if an exact match is found in one of the compare-dest hierarchies (making the end result more closely match a fresh copy). --copy-dest=DIR This option behaves like --compare-dest, but rsync will also copy unchanged files found in DIR to the destination directory using a local copy. This is useful for doing transfers to a new destination while leaving existing files intact, and then doing a flash-cutover when all files have been successfully transferred. Multiple --copy-dest directories may be provided, which will cause rsync to search the list in the order specified for an unchanged file. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. If DIR is a relative path, it is relative to the destination directory. See also --compare-dest and --link-dest. --link-dest=DIR This option behaves like --copy-dest, but unchanged files are hard linked from DIR to the destination directory. The files must be identical in all preserved attributes (e.g. permissions, possibly ownership) in order for the files to be linked together. An example: rsync -av --link-dest=$PWD/prior_dir host:src_dir/ new_dir/ If files aren't linking, double-check their attributes. Also check if some attributes are getting forced outside of rsync's control, such a mount option that squishes root to a single user, or mounts a removable drive with generic ownership (such as OS X's "Ignore ownership on this volume" option). Beginning in version 2.6.4, multiple --link-dest directories may be provided, which will cause rsync to search the list in the order specified for an exact match (there is a limit of 20 such directories). If a match is found that differs only in attributes, a local copy is made and the attributes updated. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. This option works best when copying into an empty destination hierarchy, as existing files may get their attributes tweaked, and that can affect alternate destination files via hard-links. Also, itemizing of changes can get a bit muddled. Note that prior to version 3.1.0, an alternate-directory exact match would never be found (nor linked into the destination) when a destination file already exists. Note that if you combine this option with --ignore-times, rsync will not link any files together because it only links identical files together as a substitute for transferring the file, never as an additional check after the file is updated. If DIR is a relative path, it is relative to the destination directory. See also --compare-dest and --copy-dest. Note that rsync versions prior to 2.6.1 had a bug that could prevent --link-dest from working properly for a non- super-user when --owner (-o) was specified (or implied). You can work-around this bug by avoiding the -o option (or using --no-o) when sending to an old rsync. --compress, -z With this option, rsync compresses the file data as it is sent to the destination machine, which reduces the amount of data being transmitted -- something that is useful over a slow connection. Rsync supports multiple compression methods and will choose one for you unless you force the choice using the --compress-choice (--zc) option. Run rsync --version to see the default compress list compiled into your version. When both sides of the transfer are at least 3.2.0, rsync chooses the first algorithm in the client's list of choices that is also in the server's list of choices. If no common compress choice is found, rsync exits with an error. If the remote rsync is too old to support checksum negotiation, its list is assumed to be "zlib". The default order can be customized by setting the environment variable RSYNC_COMPRESS_LIST to a space- separated list of acceptable compression names. If the string contains a "&" character, it is separated into the "client string & server string", otherwise the same string applies to both. If the string (or string portion) contains no non-whitespace characters, the default compress list is used. Any unknown compression names are discarded from the list, but a list with only invalid names results in a failed negotiation. There are some older rsync versions that were configured to reject a -z option and require the use of -zz because their compression library was not compatible with the default zlib compression method. You can usually ignore this weirdness unless the rsync server complains and tells you to specify -zz. --compress-choice=STR, --zc=STR This option can be used to override the automatic negotiation of the compression algorithm that occurs when --compress is used. The option implies --compress unless "none" was specified, which instead implies --no-compress. The compression options that you may be able to use are: o zstd o lz4 o zlibx o zlib o none Run rsync --version to see the default compress list compiled into your version (which may differ from the list above). Note that if you see an error about an option named --old- compress or --new-compress, this is rsync trying to send the --compress-choice=zlib or --compress-choice=zlibx option in a backward-compatible manner that more rsync versions understand. This error indicates that the older rsync version on the server will not allow you to force the compression type. Note that the "zlibx" compression algorithm is just the "zlib" algorithm with matched data excluded from the compression stream (to try to make it more compatible with an external zlib implementation). --compress-level=NUM, --zl=NUM Explicitly set the compression level to use (see --compress, -z) instead of letting it default. The --compress option is implied as long as the level chosen is not a "don't compress" level for the compression algorithm that is in effect (e.g. zlib compression treats level 0 as "off"). The level values vary depending on the checksum in effect. Because rsync will negotiate a checksum choice by default (when the remote rsync is new enough), it can be good to combine this option with a --compress-choice (--zc) option unless you're sure of the choice in effect. For example: rsync -aiv --zc=zstd --zl=22 host:src/ dest/ For zlib & zlibx compression the valid values are from 1 to 9 with 6 being the default. Specifying --zl=0 turns compression off, and specifying --zl=-1 chooses the default level of 6. For zstd compression the valid values are from -131072 to 22 with 3 being the default. Specifying 0 chooses the default of 3. For lz4 compression there are no levels, so the value is always 0. If you specify a too-large or too-small value, the number is silently limited to a valid value. This allows you to specify something like --zl=999999999 and be assured that you'll end up with the maximum compression level no matter what algorithm was chosen. If you want to know the compression level that is in effect, specify --debug=nstr to see the "negotiated string" results. This will report something like "Client compress: zstd (level 3)" (along with the checksum choice in effect). --skip-compress=LIST NOTE: no compression method currently supports per-file compression changes, so this option has no effect. Override the list of file suffixes that will be compressed as little as possible. Rsync sets the compression level on a per-file basis based on the file's suffix. If the compression algorithm has an "off" level, then no compression occurs for those files. Other algorithms that support changing the streaming level on-the-fly will have the level minimized to reduces the CPU usage as much as possible for a matching file. The LIST should be one or more file suffixes (without the dot) separated by slashes (/). You may specify an empty string to indicate that no files should be skipped. Simple character-class matching is supported: each must consist of a list of letters inside the square brackets (e.g. no special classes, such as "[:alpha:]", are supported, and '-' has no special meaning). The characters asterisk (*) and question-mark (?) have no special meaning. Here's an example that specifies 6 suffixes to skip (since 1 of the 5 rules matches 2 suffixes): --skip-compress=gz/jpg/mp[34]/7z/bz2 The default file suffixes in the skip-compress list in this version of rsync are: 3g2 3gp 7z aac ace apk avi bz2 deb dmg ear f4v flac flv gpg gz iso jar jpeg jpg lrz lz lz4 lzma lzo m1a m1v m2a m2ts m2v m4a m4b m4p m4r m4v mka mkv mov mp1 mp2 mp3 mp4 mpa mpeg mpg mpv mts odb odf odg odi odm odp ods odt oga ogg ogm ogv ogx opus otg oth otp ots ott oxt png qt rar rpm rz rzip spx squashfs sxc sxd sxg sxm sxw sz tbz tbz2 tgz tlz ts txz tzo vob war webm webp xz z zip zst This list will be replaced by your --skip-compress list in all but one situation: a copy from a daemon rsync will add your skipped suffixes to its list of non-compressing files (and its list may be configured to a different default). --numeric-ids With this option rsync will transfer numeric group and user IDs rather than using user and group names and mapping them at both ends. By default rsync will use the username and groupname to determine what ownership to give files. The special uid 0 and the special group 0 are never mapped via user/group names even if the --numeric-ids option is not specified. If a user or group has no name on the source system or it has no match on the destination system, then the numeric ID from the source system is used instead. See also the use chroot setting in the rsyncd.conf manpage for some comments on how the chroot setting affects rsync's ability to look up the names of the users and groups and what you can do about it. --usermap=STRING, --groupmap=STRING These options allow you to specify users and groups that should be mapped to other values by the receiving side. The STRING is one or more FROM:TO pairs of values separated by commas. Any matching FROM value from the sender is replaced with a TO value from the receiver. You may specify usernames or user IDs for the FROM and TO values, and the FROM value may also be a wild-card string, which will be matched against the sender's names (wild- cards do NOT match against ID numbers, though see below for why a '*' matches everything). You may instead specify a range of ID numbers via an inclusive range: LOW- HIGH. For example: --usermap=0-99:nobody,wayne:admin,*:normal --groupmap=usr:1,1:usr The first match in the list is the one that is used. You should specify all your user mappings using a single --usermap option, and/or all your group mappings using a single --groupmap option. Note that the sender's name for the 0 user and group are not transmitted to the receiver, so you should either match these values using a 0, or use the names in effect on the receiving side (typically "root"). All other FROM names match those in use on the sending side. All TO names match those in use on the receiving side. Any IDs that do not have a name on the sending side are treated as having an empty name for the purpose of matching. This allows them to be matched via a "*" or using an empty name. For instance: --usermap=:nobody --groupmap=*:nobody When the --numeric-ids option is used, the sender does not send any names, so all the IDs are treated as having an empty name. This means that you will need to specify numeric FROM values if you want to map these nameless IDs to different values. For the --usermap option to work, the receiver will need to be running as a super-user (see also the --super and --fake-super options). For the --groupmap option to work, the receiver will need to have permissions to set that group. Starting with rsync 3.2.4, the --usermap option implies the --owner (-o) option while the --groupmap option implies the --group (-g) option (since rsync needs to have those options enabled for the mapping options to work). An older rsync client may need to use -s to avoid a complaint about wildcard characters, but a modern rsync handles this automatically. --chown=USER:GROUP This option forces all files to be owned by USER with group GROUP. This is a simpler interface than using --usermap & --groupmap directly, but it is implemented using those options internally so they cannot be mixed. If either the USER or GROUP is empty, no mapping for the omitted user/group will occur. If GROUP is empty, the trailing colon may be omitted, but if USER is empty, a leading colon must be supplied. If you specify "--chown=foo:bar", this is exactly the same as specifying "--usermap=*:foo --groupmap=*:bar", only easier (and with the same implied --owner and/or --group options). An older rsync client may need to use -s to avoid a complaint about wildcard characters, but a modern rsync handles this automatically. --timeout=SECONDS This option allows you to set a maximum I/O timeout in seconds. If no data is transferred for the specified time then rsync will exit. The default is 0, which means no timeout. --contimeout=SECONDS This option allows you to set the amount of time that rsync will wait for its connection to an rsync daemon to succeed. If the timeout is reached, rsync exits with an error. --address=ADDRESS By default rsync will bind to the wildcard address when connecting to an rsync daemon. The --address option allows you to specify a specific IP address (or hostname) to bind to. See also the daemon version of the --address option. --port=PORT This specifies an alternate TCP port number to use rather than the default of 873. This is only needed if you are using the double-colon (::) syntax to connect with an rsync daemon (since the URL syntax has a way to specify the port as a part of the URL). See also the daemon version of the --port option. --sockopts=OPTIONS This option can provide endless fun for people who like to tune their systems to the utmost degree. You can set all sorts of socket options which may make transfers faster (or slower!). Read the manpage for the setsockopt() system call for details on some of the options you may be able to set. By default no special socket options are set. This only affects direct socket connections to a remote rsync daemon. See also the daemon version of the --sockopts option. --blocking-io This tells rsync to use blocking I/O when launching a remote shell transport. If the remote shell is either rsh or remsh, rsync defaults to using blocking I/O, otherwise it defaults to using non-blocking I/O. (Note that ssh prefers non-blocking I/O.) --outbuf=MODE This sets the output buffering mode. The mode can be None (aka Unbuffered), Line, or Block (aka Full). You may specify as little as a single letter for the mode, and use upper or lower case. The main use of this option is to change Full buffering to Line buffering when rsync's output is going to a file or pipe. --itemize-changes, -i Requests a simple itemized list of the changes that are being made to each file, including attribute changes. This is exactly the same as specifying --out- format='%i %n%L'. If you repeat the option, unchanged files will also be output, but only if the receiving rsync is at least version 2.6.7 (you can use -vv with older versions of rsync, but that also turns on the output of other verbose messages). The "%i" escape has a cryptic output that is 11 letters long. The general format is like the string YXcstpoguax, where Y is replaced by the type of update being done, X is replaced by the file-type, and the other letters represent attributes that may be output if they are being modified. The update types that replace the Y are as follows: o A < means that a file is being transferred to the remote host (sent). o A > means that a file is being transferred to the local host (received). o A c means that a local change/creation is occurring for the item (such as the creation of a directory or the changing of a symlink, etc.). o A h means that the item is a hard link to another item (requires --hard-links). o A . means that the item is not being updated (though it might have attributes that are being modified). o A * means that the rest of the itemized-output area contains a message (e.g. "deleting"). The file-types that replace the X are: f for a file, a d for a directory, an L for a symlink, a D for a device, and a S for a special file (e.g. named sockets and fifos). The other letters in the string indicate if some attributes of the file have changed, as follows: o "." - the attribute is unchanged. o "+" - the file is newly created. o " " - all the attributes are unchanged (all dots turn to spaces). o "?" - the change is unknown (when the remote rsync is old). o A letter indicates an attribute is being updated. The attribute that is associated with each letter is as follows: o A c means either that a regular file has a different checksum (requires --checksum) or that a symlink, device, or special file has a changed value. Note that if you are sending files to an rsync prior to 3.0.1, this change flag will be present only for checksum-differing regular files. o A s means the size of a regular file is different and will be updated by the file transfer. o A t means the modification time is different and is being updated to the sender's value (requires --times). An alternate value of T means that the modification time will be set to the transfer time, which happens when a file/symlink/device is updated without --times and when a symlink is changed and the receiver can't set its time. (Note: when using an rsync 3.0.0 client, you might see the s flag combined with t instead of the proper T flag for this time-setting failure.) o A p means the permissions are different and are being updated to the sender's value (requires --perms). o An o means the owner is different and is being updated to the sender's value (requires --owner and super-user privileges). o A g means the group is different and is being updated to the sender's value (requires --group and the authority to set the group). o o A u|n|b indicates the following information: u means the access (use) time is different and is being updated to the sender's value (requires --atimes) o n means the create time (newness) is different and is being updated to the sender's value (requires --crtimes) o b means that both the access and create times are being updated o The a means that the ACL information is being changed. o The x means that the extended attribute information is being changed. One other output is possible: when deleting files, the "%i" will output the string "*deleting" for each item that is being removed (assuming that you are talking to a recent enough rsync that it logs deletions instead of outputting them as a verbose message). --out-format=FORMAT This allows you to specify exactly what the rsync client outputs to the user on a per-update basis. The format is a text string containing embedded single-character escape sequences prefixed with a percent (%) character. A default format of "%n%L" is assumed if either --info=name or -v is specified (this tells you just the name of the file and, if the item is a link, where it points). For a full list of the possible escape characters, see the log format setting in the rsyncd.conf manpage. Specifying the --out-format option implies the --info=name option, which will mention each file, dir, etc. that gets updated in a significant way (a transferred file, a recreated symlink/device, or a touched directory). In addition, if the itemize-changes escape (%i) is included in the string (e.g. if the --itemize-changes option was used), the logging of names increases to mention any item that is changed in any way (as long as the receiving side is at least 2.6.4). See the --itemize-changes option for a description of the output of "%i". Rsync will output the out-format string prior to a file's transfer unless one of the transfer-statistic escapes is requested, in which case the logging is done at the end of the file's transfer. When this late logging is in effect and --progress is also specified, rsync will also output the name of the file being transferred prior to its progress information (followed, of course, by the out- format output). --log-file=FILE This option causes rsync to log what it is doing to a file. This is similar to the logging that a daemon does, but can be requested for the client side and/or the server side of a non-daemon transfer. If specified as a client option, transfer logging will be enabled with a default format of "%i %n%L". See the --log-file-format option if you wish to override this. Here's an example command that requests the remote side to log what is happening: rsync -av --remote-option=--log-file=/tmp/rlog src/ dest/ This is very useful if you need to debug why a connection is closing unexpectedly. See also the daemon version of the --log-file option. --log-file-format=FORMAT This allows you to specify exactly what per-update logging is put into the file specified by the --log-file option (which must also be specified for this option to have any effect). If you specify an empty string, updated files will not be mentioned in the log file. For a list of the possible escape characters, see the log format setting in the rsyncd.conf manpage. The default FORMAT used if --log-file is specified and this option is not is '%i %n%L'. See also the daemon version of the --log-file-format option. --stats This tells rsync to print a verbose set of statistics on the file transfer, allowing you to tell how effective rsync's delta-transfer algorithm is for your data. This option is equivalent to --info=stats2 if combined with 0 or 1 -v options, or --info=stats3 if combined with 2 or more -v options. The current statistics are as follows: o Number of files is the count of all "files" (in the generic sense), which includes directories, symlinks, etc. The total count will be followed by a list of counts by filetype (if the total is non- zero). For example: "(reg: 5, dir: 3, link: 2, dev: 1, special: 1)" lists the totals for regular files, directories, symlinks, devices, and special files. If any of value is 0, it is completely omitted from the list. o Number of created files is the count of how many "files" (generic sense) were created (as opposed to updated). The total count will be followed by a list of counts by filetype (if the total is non- zero). o Number of deleted files is the count of how many "files" (generic sense) were deleted. The total count will be followed by a list of counts by filetype (if the total is non-zero). Note that this line is only output if deletions are in effect, and only if protocol 31 is being used (the default for rsync 3.1.x). o Number of regular files transferred is the count of normal files that were updated via rsync's delta- transfer algorithm, which does not include dirs, symlinks, etc. Note that rsync 3.1.0 added the word "regular" into this heading. o Total file size is the total sum of all file sizes in the transfer. This does not count any size for directories or special files, but does include the size of symlinks. o Total transferred file size is the total sum of all files sizes for just the transferred files. o Literal data is how much unmatched file-update data we had to send to the receiver for it to recreate the updated files. o Matched data is how much data the receiver got locally when recreating the updated files. o File list size is how big the file-list data was when the sender sent it to the receiver. This is smaller than the in-memory size for the file list due to some compressing of duplicated data when rsync sends the list. o File list generation time is the number of seconds that the sender spent creating the file list. This requires a modern rsync on the sending side for this to be present. o File list transfer time is the number of seconds that the sender spent sending the file list to the receiver. o Total bytes sent is the count of all the bytes that rsync sent from the client side to the server side. o Total bytes received is the count of all non- message bytes that rsync received by the client side from the server side. "Non-message" bytes means that we don't count the bytes for a verbose message that the server sent to us, which makes the stats more consistent. --8-bit-output, -8 This tells rsync to leave all high-bit characters unescaped in the output instead of trying to test them to see if they're valid in the current locale and escaping the invalid ones. All control characters (but never tabs) are always escaped, regardless of this option's setting. The escape idiom that started in 2.6.7 is to output a literal backslash (\) and a hash (#), followed by exactly 3 octal digits. For example, a newline would output as "\#012". A literal backslash that is in a filename is not escaped unless it is followed by a hash and 3 digits (0-9). --human-readable, -h Output numbers in a more human-readable format. There are 3 possible levels: 1. output numbers with a separator between each set of 3 digits (either a comma or a period, depending on if the decimal point is represented by a period or a comma). 2. output numbers in units of 1000 (with a character suffix for larger units -- see below). 3. output numbers in units of 1024. The default is human-readable level 1. Each -h option increases the level by one. You can take the level down to 0 (to output numbers as pure digits) by specifying the --no-human-readable (--no-h) option. The unit letters that are appended in levels 2 and 3 are: K (kilo), M (mega), G (giga), T (tera), or P (peta). For example, a 1234567-byte file would output as 1.23M in level-2 (assuming that a period is your local decimal point). Backward compatibility note: versions of rsync prior to 3.1.0 do not support human-readable level 1, and they default to level 0. Thus, specifying one or two -h options will behave in a comparable manner in old and new versions as long as you didn't specify a --no-h option prior to one or more -h options. See the --list-only option for one difference. --partial By default, rsync will delete any partially transferred file if the transfer is interrupted. In some circumstances it is more desirable to keep partially transferred files. Using the --partial option tells rsync to keep the partial file which should make a subsequent transfer of the rest of the file much faster. --partial-dir=DIR This option modifies the behavior of the --partial option while also implying that it be enabled. This enhanced partial-file method puts any partially transferred files into the specified DIR instead of writing the partial file out to the destination file. On the next transfer, rsync will use a file found in this dir as data to speed up the resumption of the transfer and then delete it after it has served its purpose. Note that if --whole-file is specified (or implied), any partial-dir files that are found for a file that is being updated will simply be removed (since rsync is sending files without using rsync's delta-transfer algorithm). Rsync will create the DIR if it is missing, but just the last dir -- not the whole path. This makes it easy to use a relative path (such as "--partial-dir=.rsync-partial") to have rsync create the partial-directory in the destination file's directory when it is needed, and then remove it again when the partial file is deleted. Note that this directory removal is only done for a relative pathname, as it is expected that an absolute path is to a directory that is reserved for partial-dir work. If the partial-dir value is not an absolute path, rsync will add an exclude rule at the end of all your existing excludes. This will prevent the sending of any partial- dir files that may exist on the sending side, and will also prevent the untimely deletion of partial-dir items on the receiving side. An example: the above --partial-dir option would add the equivalent of this "perishable" exclude at the end of any other filter rules: -f '-p .rsync-partial/' If you are supplying your own exclude rules, you may need to add your own exclude/hide/protect rule for the partial- dir because: 1. the auto-added rule may be ineffective at the end of your other rules, or 2. you may wish to override rsync's exclude choice. For instance, if you want to make rsync clean-up any left- over partial-dirs that may be lying around, you should specify --delete-after and add a "risk" filter rule, e.g. -f 'R .rsync-partial/'. Avoid using --delete-before or --delete-during unless you don't need rsync to use any of the left-over partial-dir data during the current run. IMPORTANT: the --partial-dir should not be writable by other users or it is a security risk! E.g. AVOID "/tmp"! You can also set the partial-dir value the RSYNC_PARTIAL_DIR environment variable. Setting this in the environment does not force --partial to be enabled, but rather it affects where partial files go when --partial is specified. For instance, instead of using --partial-dir=.rsync-tmp along with --progress, you could set RSYNC_PARTIAL_DIR=.rsync-tmp in your environment and then use the -P option to turn on the use of the .rsync- tmp dir for partial transfers. The only times that the --partial option does not look for this environment value are: 1. when --inplace was specified (since --inplace conflicts with --partial-dir), and 2. when --delay-updates was specified (see below). When a modern rsync resumes the transfer of a file in the partial-dir, that partial file is now updated in-place instead of creating yet another tmp-file copy (so it maxes out at dest + tmp instead of dest + partial + tmp). This requires both ends of the transfer to be at least version 3.2.0. For the purposes of the daemon-config's "refuse options" setting, --partial-dir does not imply --partial. This is so that a refusal of the --partial option can be used to disallow the overwriting of destination files with a partial transfer, while still allowing the safer idiom provided by --partial-dir. --delay-updates This option puts the temporary file from each updated file into a holding directory until the end of the transfer, at which time all the files are renamed into place in rapid succession. This attempts to make the updating of the files a little more atomic. By default the files are placed into a directory named .~tmp~ in each file's destination directory, but if you've specified the --partial-dir option, that directory will be used instead. See the comments in the --partial-dir section for a discussion of how this .~tmp~ dir will be excluded from the transfer, and what you can do if you want rsync to cleanup old .~tmp~ dirs that might be lying around. Conflicts with --inplace and --append. This option implies --no-inc-recursive since it needs the full file list in memory in order to be able to iterate over it at the end. This option uses more memory on the receiving side (one bit per file transferred) and also requires enough free disk space on the receiving side to hold an additional copy of all the updated files. Note also that you should not use an absolute path to --partial-dir unless: 1. there is no chance of any of the files in the transfer having the same name (since all the updated files will be put into a single directory if the path is absolute), and 2. there are no mount points in the hierarchy (since the delayed updates will fail if they can't be renamed into place). See also the "atomic-rsync" python script in the "support" subdir for an update algorithm that is even more atomic (it uses --link-dest and a parallel hierarchy of files). --prune-empty-dirs, -m This option tells the receiving rsync to get rid of empty directories from the file-list, including nested directories that have no non-directory children. This is useful for avoiding the creation of a bunch of useless directories when the sending rsync is recursively scanning a hierarchy of files using include/exclude/filter rules. This option can still leave empty directories on the receiving side if you make use of TRANSFER_RULES. Because the file-list is actually being pruned, this option also affects what directories get deleted when a delete is active. However, keep in mind that excluded files and directories can prevent existing items from being deleted due to an exclude both hiding source files and protecting destination files. See the perishable filter-rule option for how to avoid this. You can prevent the pruning of certain empty directories from the file-list by using a global "protect" filter. For instance, this option would ensure that the directory "emptydir" was kept in the file-list: --filter 'protect emptydir/' Here's an example that copies all .pdf files in a hierarchy, only creating the necessary destination directories to hold the .pdf files, and ensures that any superfluous files and directories in the destination are removed (note the hide filter of non-directories being used instead of an exclude): rsync -avm --del --include='*.pdf' -f 'hide,! */' src/ dest If you didn't want to remove superfluous destination files, the more time-honored options of --include='*/' --exclude='*' would work fine in place of the hide-filter (if that is more natural to you). --progress This option tells rsync to print information showing the progress of the transfer. This gives a bored user something to watch. With a modern rsync this is the same as specifying --info=flist2,name,progress, but any user- supplied settings for those info flags takes precedence (e.g. --info=flist0 --progress). While rsync is transferring a regular file, it updates a progress line that looks like this: 782448 63% 110.64kB/s 0:00:04 In this example, the receiver has reconstructed 782448 bytes or 63% of the sender's file, which is being reconstructed at a rate of 110.64 kilobytes per second, and the transfer will finish in 4 seconds if the current rate is maintained until the end. These statistics can be misleading if rsync's delta- transfer algorithm is in use. For example, if the sender's file consists of the basis file followed by additional data, the reported rate will probably drop dramatically when the receiver gets to the literal data, and the transfer will probably take much longer to finish than the receiver estimated as it was finishing the matched part of the file. When the file transfer finishes, rsync replaces the progress line with a summary line that looks like this: 1,238,099 100% 146.38kB/s 0:00:08 (xfr#5, to-chk=169/396) In this example, the file was 1,238,099 bytes long in total, the average rate of transfer for the whole file was 146.38 kilobytes per second over the 8 seconds that it took to complete, it was the 5th transfer of a regular file during the current rsync session, and there are 169 more files for the receiver to check (to see if they are up-to-date or not) remaining out of the 396 total files in the file-list. In an incremental recursion scan, rsync won't know the total number of files in the file-list until it reaches the ends of the scan, but since it starts to transfer files during the scan, it will display a line with the text "ir-chk" (for incremental recursion check) instead of "to-chk" until the point that it knows the full size of the list, at which point it will switch to using "to-chk". Thus, seeing "ir-chk" lets you know that the total count of files in the file list is still going to increase (and each time it does, the count of files left to check will increase by the number of the files added to the list). -P The -P option is equivalent to "--partial --progress". Its purpose is to make it much easier to specify these two options for a long transfer that may be interrupted. There is also a --info=progress2 option that outputs statistics based on the whole transfer, rather than individual files. Use this flag without outputting a filename (e.g. avoid -v or specify --info=name0) if you want to see how the transfer is doing without scrolling the screen with a lot of names. (You don't need to specify the --progress option in order to use --info=progress2.) Finally, you can get an instant progress report by sending rsync a signal of either SIGINFO or SIGVTALRM. On BSD systems, a SIGINFO is generated by typing a Ctrl+T (Linux doesn't currently support a SIGINFO signal). When the client-side process receives one of those signals, it sets a flag to output a single progress report which is output when the current file transfer finishes (so it may take a little time if a big file is being handled when the signal arrives). A filename is output (if needed) followed by the --info=progress2 format of progress info. If you don't know which of the 3 rsync processes is the client process, it's OK to signal all of them (since the non- client processes ignore the signal). CAUTION: sending SIGVTALRM to an older rsync (pre-3.2.0) will kill it. --password-file=FILE This option allows you to provide a password for accessing an rsync daemon via a file or via standard input if FILE is -. The file should contain just the password on the first line (all other lines are ignored). Rsync will exit with an error if FILE is world readable or if a root-run rsync command finds a non-root-owned file. This option does not supply a password to a remote shell transport such as ssh; to learn how to do that, consult the remote shell's documentation. When accessing an rsync daemon using a remote shell as the transport, this option only comes into effect after the remote shell finishes its authentication (i.e. if you have also specified a password in the daemon's config file). --early-input=FILE This option allows rsync to send up to 5K of data to the "early exec" script on its stdin. One possible use of this data is to give the script a secret that can be used to mount an encrypted filesystem (which you should unmount in the the "post-xfer exec" script). The daemon must be at least version 3.2.1. --list-only This option will cause the source files to be listed instead of transferred. This option is inferred if there is a single source arg and no destination specified, so its main uses are: 1. to turn a copy command that includes a destination arg into a file-listing command, or 2. to be able to specify more than one source arg. Note: be sure to include the destination. CAUTION: keep in mind that a source arg with a wild-card is expanded by the shell into multiple args, so it is never safe to try to specify a single wild-card arg to try to infer this option. A safe example is: rsync -av --list-only foo* dest/ This option always uses an output format that looks similar to this: drwxrwxr-x 4,096 2022/09/30 12:53:11 support -rw-rw-r-- 80 2005/01/11 10:37:37 support/Makefile The only option that affects this output style is (as of 3.1.0) the --human-readable (-h) option. The default is to output sizes as byte counts with digit separators (in a 14-character-width column). Specifying at least one -h option makes the sizes output with unit suffixes. If you want old-style bytecount sizes without digit separators (and an 11-character-width column) use --no-h. Compatibility note: when requesting a remote listing of files from an rsync that is version 2.6.3 or older, you may encounter an error if you ask for a non-recursive listing. This is because a file listing implies the --dirs option w/o --recursive, and older rsyncs don't have that option. To avoid this problem, either specify the --no-dirs option (if you don't need to expand a directory's content), or turn on recursion and exclude the content of subdirectories: -r --exclude='/*/*'. --bwlimit=RATE This option allows you to specify the maximum transfer rate for the data sent over the socket, specified in units per second. The RATE value can be suffixed with a string to indicate a size multiplier, and may be a fractional value (e.g. --bwlimit=1.5m). If no suffix is specified, the value will be assumed to be in units of 1024 bytes (as if "K" or "KiB" had been appended). See the --max-size option for a description of all the available suffixes. A value of 0 specifies no limit. For backward-compatibility reasons, the rate limit will be rounded to the nearest KiB unit, so no rate smaller than 1024 bytes per second is possible. Rsync writes data over the socket in blocks, and this option both limits the size of the blocks that rsync writes, and tries to keep the average transfer rate at the requested limit. Some burstiness may be seen where rsync writes out a block of data and then sleeps to bring the average rate into compliance. Due to the internal buffering of data, the --progress option may not be an accurate reflection on how fast the data is being sent. This is because some files can show up as being rapidly sent when the data is quickly buffered, while other can show up as very slow when the flushing of the output buffer occurs. This may be fixed in a future version. See also the daemon version of the --bwlimit option. --stop-after=MINS, (--time-limit=MINS) This option tells rsync to stop copying when the specified number of minutes has elapsed. For maximal flexibility, rsync does not communicate this option to the remote rsync since it is usually enough that one side of the connection quits as specified. This allows the option's use even when only one side of the connection supports it. You can tell the remote side about the time limit using --remote-option (-M), should the need arise. The --time-limit version of this option is deprecated. --stop-at=y-m-dTh:m This option tells rsync to stop copying when the specified point in time has been reached. The date & time can be fully specified in a numeric format of year-month- dayThour:minute (e.g. 2000-12-31T23:59) in the local timezone. You may choose to separate the date numbers using slashes instead of dashes. The value can also be abbreviated in a variety of ways, such as specifying a 2-digit year and/or leaving off various values. In all cases, the value will be taken to be the next possible point in time where the supplied information matches. If the value specifies the current time or a past time, rsync exits with an error. For example, "1-30" specifies the next January 30th (at midnight local time), "14:00" specifies the next 2 P.M., "1" specifies the next 1st of the month at midnight, "31" specifies the next month where we can stop on its 31st day, and ":59" specifies the next 59th minute after the hour. For maximal flexibility, rsync does not communicate this option to the remote rsync since it is usually enough that one side of the connection quits as specified. This allows the option's use even when only one side of the connection supports it. You can tell the remote side about the time limit using --remote-option (-M), should the need arise. Do keep in mind that the remote host may have a different default timezone than your local host. --fsync Cause the receiving side to fsync each finished file. This may slow down the transfer, but can help to provide peace of mind when updating critical files. --write-batch=FILE Record a file that can later be applied to another identical destination with --read-batch. See the "BATCH MODE" section for details, and also the --only-write-batch option. This option overrides the negotiated checksum & compress lists and always negotiates a choice based on old-school md5/md4/zlib choices. If you want a more modern choice, use the --checksum-choice (--cc) and/or --compress-choice (--zc) options. --only-write-batch=FILE Works like --write-batch, except that no updates are made on the destination system when creating the batch. This lets you transport the changes to the destination system via some other means and then apply the changes via --read-batch. Note that you can feel free to write the batch directly to some portable media: if this media fills to capacity before the end of the transfer, you can just apply that partial transfer to the destination and repeat the whole process to get the rest of the changes (as long as you don't mind a partially updated destination system while the multi-update cycle is happening). Also note that you only save bandwidth when pushing changes to a remote system because this allows the batched data to be diverted from the sender into the batch file without having to flow over the wire to the receiver (when pulling, the sender is remote, and thus can't write the batch). --read-batch=FILE Apply all of the changes stored in FILE, a file previously generated by --write-batch. If FILE is -, the batch data will be read from standard input. See the "BATCH MODE" section for details. --protocol=NUM Force an older protocol version to be used. This is useful for creating a batch file that is compatible with an older version of rsync. For instance, if rsync 2.6.4 is being used with the --write-batch option, but rsync 2.6.3 is what will be used to run the --read-batch option, you should use "--protocol=28" when creating the batch file to force the older protocol version to be used in the batch file (assuming you can't upgrade the rsync on the reading system). --iconv=CONVERT_SPEC Rsync can convert filenames between character sets using this option. Using a CONVERT_SPEC of "." tells rsync to look up the default character-set via the locale setting. Alternately, you can fully specify what conversion to do by giving a local and a remote charset separated by a comma in the order --iconv=LOCAL,REMOTE, e.g. --iconv=utf8,iso88591. This order ensures that the option will stay the same whether you're pushing or pulling files. Finally, you can specify either --no-iconv or a CONVERT_SPEC of "-" to turn off any conversion. The default setting of this option is site-specific, and can also be affected via the RSYNC_ICONV environment variable. For a list of what charset names your local iconv library supports, you can run "iconv --list". If you specify the --secluded-args (-s) option, rsync will translate the filenames you specify on the command-line that are being sent to the remote host. See also the --files-from option. Note that rsync does not do any conversion of names in filter files (including include/exclude files). It is up to you to ensure that you're specifying matching rules that can match on both sides of the transfer. For instance, you can specify extra include/exclude rules if there are filename differences on the two sides that need to be accounted for. When you pass an --iconv option to an rsync daemon that allows it, the daemon uses the charset specified in its "charset" configuration parameter regardless of the remote charset you actually pass. Thus, you may feel free to specify just the local charset for a daemon transfer (e.g. --iconv=utf8). --ipv4, -4 or --ipv6, -6 Tells rsync to prefer IPv4/IPv6 when creating sockets or running ssh. This affects sockets that rsync has direct control over, such as the outgoing socket when directly contacting an rsync daemon, as well as the forwarding of the -4 or -6 option to ssh when rsync can deduce that ssh is being used as the remote shell. For other remote shells you'll need to specify the "--rsh SHELL -4" option directly (or whatever IPv4/IPv6 hint options it uses). See also the daemon version of these options. If rsync was compiled without support for IPv6, the --ipv6 option will have no effect. The rsync --version output will contain "no IPv6" if is the case. --checksum-seed=NUM Set the checksum seed to the integer NUM. This 4 byte checksum seed is included in each block and MD4 file checksum calculation (the more modern MD5 file checksums don't use a seed). By default the checksum seed is generated by the server and defaults to the current time(). This option is used to set a specific checksum seed, which is useful for applications that want repeatable block checksums, or in the case where the user wants a more random checksum seed. Setting NUM to 0 causes rsync to use the default of time() for checksum seed. DAEMON OPTIONS top The options allowed when starting an rsync daemon are as follows: --daemon This tells rsync that it is to run as a daemon. The daemon you start running may be accessed using an rsync client using the host::module or rsync://host/module/ syntax. If standard input is a socket then rsync will assume that it is being run via inetd, otherwise it will detach from the current terminal and become a background daemon. The daemon will read the config file (rsyncd.conf) on each connect made by a client and respond to requests accordingly. See the rsyncd.conf(5) manpage for more details. --address=ADDRESS By default rsync will bind to the wildcard address when run as a daemon with the --daemon option. The --address option allows you to specify a specific IP address (or hostname) to bind to. This makes virtual hosting possible in conjunction with the --config option. See also the address global option in the rsyncd.conf manpage and the client version of the --address option. --bwlimit=RATE This option allows you to specify the maximum transfer rate for the data the daemon sends over the socket. The client can still specify a smaller --bwlimit value, but no larger value will be allowed. See the client version of the --bwlimit option for some extra details. --config=FILE This specifies an alternate config file than the default. This is only relevant when --daemon is specified. The default is /etc/rsyncd.conf unless the daemon is running over a remote shell program and the remote user is not the super-user; in that case the default is rsyncd.conf in the current directory (typically $HOME). --dparam=OVERRIDE, -M This option can be used to set a daemon-config parameter when starting up rsync in daemon mode. It is equivalent to adding the parameter at the end of the global settings prior to the first module's definition. The parameter names can be specified without spaces, if you so desire. For instance: rsync --daemon -M pidfile=/path/rsync.pid --no-detach When running as a daemon, this option instructs rsync to not detach itself and become a background process. This option is required when running as a service on Cygwin, and may also be useful when rsync is supervised by a program such as daemontools or AIX's System Resource Controller. --no-detach is also recommended when rsync is run under a debugger. This option has no effect if rsync is run from inetd or sshd. --port=PORT This specifies an alternate TCP port number for the daemon to listen on rather than the default of 873. See also the client version of the --port option and the port global setting in the rsyncd.conf manpage. --log-file=FILE This option tells the rsync daemon to use the given log- file name instead of using the "log file" setting in the config file. See also the client version of the --log-file option. --log-file-format=FORMAT This option tells the rsync daemon to use the given FORMAT string instead of using the "log format" setting in the config file. It also enables "transfer logging" unless the string is empty, in which case transfer logging is turned off. See also the client version of the --log-file-format option. --sockopts This overrides the socket options setting in the rsyncd.conf file and has the same syntax. See also the client version of the --sockopts option. --verbose, -v This option increases the amount of information the daemon logs during its startup phase. After the client connects, the daemon's verbosity level will be controlled by the options that the client used and the "max verbosity" setting in the module's config section. See also the client version of the --verbose option. --ipv4, -4 or --ipv6, -6 Tells rsync to prefer IPv4/IPv6 when creating the incoming sockets that the rsync daemon will use to listen for connections. One of these options may be required in older versions of Linux to work around an IPv6 bug in the kernel (if you see an "address already in use" error when nothing else is using the port, try specifying --ipv6 or --ipv4 when starting the daemon). See also the client version of these options. If rsync was compiled without support for IPv6, the --ipv6 option will have no effect. The rsync --version output will contain "no IPv6" if is the case. --help, -h When specified after --daemon, print a short help page describing the options available for starting an rsync daemon. FILTER RULES top The filter rules allow for custom control of several aspects of how files are handled: o Control which files the sending side puts into the file list that describes the transfer hierarchy o Control which files the receiving side protects from deletion when the file is not in the sender's file list o Control which extended attribute names are skipped when copying xattrs The rules are either directly specified via option arguments or they can be read in from one or more files. The filter-rule files can even be a part of the hierarchy of files being copied, affecting different parts of the tree in different ways. SIMPLE INCLUDE/EXCLUDE RULES We will first cover the basics of how include & exclude rules affect what files are transferred, ignoring any deletion side- effects. Filter rules mainly affect the contents of directories that rsync is "recursing" into, but they can also affect a top- level item in the transfer that was specified as a argument. The default for any unmatched file/dir is for it to be included in the transfer, which puts the file/dir into the sender's file list. The use of an exclude rule causes one or more matching files/dirs to be left out of the sender's file list. An include rule can be used to limit the effect of an exclude rule that is matching too many files. The order of the rules is important because the first rule that matches is the one that takes effect. Thus, if an early rule excludes a file, no include rule that comes after it can have any effect. This means that you must place any include overrides somewhere prior to the exclude that it is intended to limit. When a directory is excluded, all its contents and sub-contents are also excluded. The sender doesn't scan through any of it at all, which can save a lot of time when skipping large unneeded sub-trees. It is also important to understand that the include/exclude rules are applied to every file and directory that the sender is recursing into. Thus, if you want a particular deep file to be included, you have to make sure that none of the directories that must be traversed on the way down to that file are excluded or else the file will never be discovered to be included. As an example, if the directory "a/path" was given as a transfer argument and you want to ensure that the file "a/path/down/deep/wanted.txt" is a part of the transfer, then the sender must not exclude the directories "a/path", "a/path/down", or "a/path/down/deep" as it makes it way scanning through the file tree. When you are working on the rules, it can be helpful to ask rsync to tell you what is being excluded/included and why. Specifying --debug=FILTER or (when pulling files) -M--debug=FILTER turns on level 1 of the FILTER debug information that will output a message any time that a file or directory is included or excluded and which rule it matched. Beginning in 3.2.4 it will also warn if a filter rule has trailing whitespace, since an exclude of "foo " (with a trailing space) will not exclude a file named "foo". Exclude and include rules can specify wildcard PATTERN MATCHING RULES (similar to shell wildcards) that allow you to match things like a file suffix or a portion of a filename. A rule can be limited to only affecting a directory by putting a trailing slash onto the filename. SIMPLE INCLUDE/EXCLUDE EXAMPLE With the following file tree created on the sending side: mkdir x/ touch x/file.txt mkdir x/y/ touch x/y/file.txt touch x/y/zzz.txt mkdir x/z/ touch x/z/file.txt Then the following rsync command will transfer the file "x/y/file.txt" and the directories needed to hold it, resulting in the path "/tmp/x/y/file.txt" existing on the remote host: rsync -ai -f'+ x/' -f'+ x/y/' -f'+ x/y/file.txt' -f'- *' x host:/tmp/ Aside: this copy could also have been accomplished using the -R option (though the 2 commands behave differently if deletions are enabled): rsync -aiR x/y/file.txt host:/tmp/ The following command does not need an include of the "x" directory because it is not a part of the transfer (note the traililng slash). Running this command would copy just "/tmp/x/file.txt" because the "y" and "z" dirs get excluded: rsync -ai -f'+ file.txt' -f'- *' x/ host:/tmp/x/ This command would omit the zzz.txt file while copying "x" and everything else it contains: rsync -ai -f'- zzz.txt' x host:/tmp/ FILTER RULES WHEN DELETING By default the include & exclude filter rules affect both the sender (as it creates its file list) and the receiver (as it creates its file lists for calculating deletions). If no delete option is in effect, the receiver skips creating the delete- related file lists. This two-sided default can be manually overridden so that you are only specifying sender rules or receiver rules, as described in the FILTER RULES IN DEPTH section. When deleting, an exclude protects a file from being removed on the receiving side while an include overrides that protection (putting the file at risk of deletion). The default is for a file to be at risk -- its safety depends on it matching a corresponding file from the sender. An example of the two-sided exclude effect can be illustrated by the copying of a C development directory between 2 systems. When doing a touch-up copy, you might want to skip copying the built executable and the .o files (sender hide) so that the receiving side can build their own and not lose any object files that are already correct (receiver protect). For instance: rsync -ai --del -f'- *.o' -f'- cmd' src host:/dest/ Note that using -f'-p *.o' is even better than -f'- *.o' if there is a chance that the directory structure may have changed. The "p" modifier is discussed in FILTER RULE MODIFIERS. One final note, if your shell doesn't mind unexpanded wildcards, you could simplify the typing of the filter options by using an underscore in place of the space and leaving off the quotes. For instance, -f -_*.o -f -_cmd (and similar) could be used instead of the filter options above. FILTER RULES IN DEPTH Rsync supports old-style include/exclude rules and new-style filter rules. The older rules are specified using --include and --exclude as well as the --include-from and --exclude-from. These are limited in behavior but they don't require a "-" or "+" prefix. An old-style exclude rule is turned into a "- name" filter rule (with no modifiers) and an old-style include rule is turned into a "+ name" filter rule (with no modifiers). Rsync builds an ordered list of filter rules as specified on the command-line and/or read-in from files. New style filter rules have the following syntax: RULE [PATTERN_OR_FILENAME] RULE,MODIFIERS [PATTERN_OR_FILENAME] You have your choice of using either short or long RULE names, as described below. If you use a short-named rule, the ',' separating the RULE from the MODIFIERS is optional. The PATTERN or FILENAME that follows (when present) must come after either a single space or an underscore (_). Any additional spaces and/or underscores are considered to be a part of the pattern name. Here are the available rule prefixes: exclude, '-' specifies an exclude pattern that (by default) is both a hide and a protect. include, '+' specifies an include pattern that (by default) is both a show and a risk. merge, '.' specifies a merge-file on the client side to read for more rules. dir-merge, ':' specifies a per-directory merge-file. Using this kind of filter rule requires that you trust the sending side's filter checking, so it has the side-effect mentioned under the --trust-sender option. hide, 'H' specifies a pattern for hiding files from the transfer. Equivalent to a sender-only exclude, so -f'H foo' could also be specified as -f'-s foo'. show, 'S' files that match the pattern are not hidden. Equivalent to a sender-only include, so -f'S foo' could also be specified as -f'+s foo'. protect, 'P' specifies a pattern for protecting files from deletion. Equivalent to a receiver-only exclude, so -f'P foo' could also be specified as -f'-r foo'. risk, 'R' files that match the pattern are not protected. Equivalent to a receiver-only include, so -f'R foo' could also be specified as -f'+r foo'. clear, '!' clears the current include/exclude list (takes no arg) When rules are being read from a file (using merge or dir-merge), empty lines are ignored, as are whole-line comments that start with a '#' (filename rules that contain a hash character are unaffected). Note also that the --filter, --include, and --exclude options take one rule/pattern each. To add multiple ones, you can repeat the options on the command-line, use the merge-file syntax of the --filter option, or the --include-from / --exclude-from options. PATTERN MATCHING RULES Most of the rules mentioned above take an argument that specifies what the rule should match. If rsync is recursing through a directory hierarchy, keep in mind that each pattern is matched against the name of every directory in the descent path as rsync finds the filenames to send. The matching rules for the pattern argument take several forms: o If a pattern contains a / (not counting a trailing slash) or a "**" (which can match a slash), then the pattern is matched against the full pathname, including any leading directories within the transfer. If the pattern doesn't contain a (non-trailing) / or a "**", then it is matched only against the final component of the filename or pathname. For example, foo means that the final path component must be "foo" while foo/bar would match the last 2 elements of the path (as long as both elements are within the transfer). o A pattern that ends with a / only matches a directory, not a regular file, symlink, or device. o A pattern that starts with a / is anchored to the start of the transfer path instead of the end. For example, /foo/** or /foo/bar/** match only leading elements in the path. If the rule is read from a per-directory filter file, the transfer path being matched will begin at the level of the filter file instead of the top of the transfer. See the section on ANCHORING INCLUDE/EXCLUDE PATTERNS for a full discussion of how to specify a pattern that matches at the root of the transfer. Rsync chooses between doing a simple string match and wildcard matching by checking if the pattern contains one of these three wildcard characters: '*', '?', and '[' : o a '?' matches any single character except a slash (/). o a '*' matches zero or more non-slash characters. o a '**' matches zero or more characters, including slashes. o a '[' introduces a character class, such as [a-z] or [[:alpha:]], that must match one character. o a trailing *** in the pattern is a shorthand that allows you to match a directory and all its contents using a single rule. For example, specifying "dir_name/***" will match both the "dir_name" directory (as if "dir_name/" had been specified) and everything in the directory (as if "dir_name/**" had been specified). o a backslash can be used to escape a wildcard character, but it is only interpreted as an escape character if at least one wildcard character is present in the match pattern. For instance, the pattern "foo\bar" matches that single backslash literally, while the pattern "foo\bar*" would need to be changed to "foo\\bar*" to avoid the "\b" becoming just "b". Here are some examples of exclude/include matching: o Option -f'- *.o' would exclude all filenames ending with .o o Option -f'- /foo' would exclude a file (or directory) named foo in the transfer-root directory o Option -f'- foo/' would exclude any directory named foo o Option -f'- foo/*/bar' would exclude any file/dir named bar which is at two levels below a directory named foo (if foo is in the transfer) o Option -f'- /foo/**/bar' would exclude any file/dir named bar that was two or more levels below a top-level directory named foo (note that /foo/bar is not excluded by this) o Options -f'+ */' -f'+ *.c' -f'- *' would include all directories and .c source files but nothing else o Options -f'+ foo/' -f'+ foo/bar.c' -f'- *' would include only the foo directory and foo/bar.c (the foo directory must be explicitly included or it would be excluded by the "- *") FILTER RULE MODIFIERS The following modifiers are accepted after an include (+) or exclude (-) rule: o A / specifies that the include/exclude rule should be matched against the absolute pathname of the current item. For example, -f'-/ /etc/passwd' would exclude the passwd file any time the transfer was sending files from the "/etc" directory, and "-/ subdir/foo" would always exclude "foo" when it is in a dir named "subdir", even if "foo" is at the root of the current transfer. o A ! specifies that the include/exclude should take effect if the pattern fails to match. For instance, -f'-! */' would exclude all non-directories. o A C is used to indicate that all the global CVS-exclude rules should be inserted as excludes in place of the "-C". No arg should follow. o An s is used to indicate that the rule applies to the sending side. When a rule affects the sending side, it affects what files are put into the sender's file list. The default is for a rule to affect both sides unless --delete-excluded was specified, in which case default rules become sender-side only. See also the hide (H) and show (S) rules, which are an alternate way to specify sending-side includes/excludes. o An r is used to indicate that the rule applies to the receiving side. When a rule affects the receiving side, it prevents files from being deleted. See the s modifier for more info. See also the protect (P) and risk (R) rules, which are an alternate way to specify receiver-side includes/excludes. o A p indicates that a rule is perishable, meaning that it is ignored in directories that are being deleted. For instance, the --cvs-exclude (-C) option's default rules that exclude things like "CVS" and "*.o" are marked as perishable, and will not prevent a directory that was removed on the source from being deleted on the destination. o An x indicates that a rule affects xattr names in xattr copy/delete operations (and is thus ignored when matching file/dir names). If no xattr-matching rules are specified, a default xattr filtering rule is used (see the --xattrs option). MERGE-FILE FILTER RULES You can merge whole files into your filter rules by specifying either a merge (.) or a dir-merge (:) filter rule (as introduced in the FILTER RULES section above). There are two kinds of merged files -- single-instance ('.') and per-directory (':'). A single-instance merge file is read one time, and its rules are incorporated into the filter list in the place of the "." rule. For per-directory merge files, rsync will scan every directory that it traverses for the named file, merging its contents when the file exists into the current list of inherited rules. These per-directory rule files must be created on the sending side because it is the sending side that is being scanned for the available files to transfer. These rule files may also need to be transferred to the receiving side if you want them to affect what files don't get deleted (see PER- DIRECTORY RULES AND DELETE below). Some examples: merge /etc/rsync/default.rules . /etc/rsync/default.rules dir-merge .per-dir-filter dir-merge,n- .non-inherited-per-dir-excludes :n- .non-inherited-per-dir-excludes The following modifiers are accepted after a merge or dir-merge rule: o A - specifies that the file should consist of only exclude patterns, with no other rule-parsing except for in-file comments. o A + specifies that the file should consist of only include patterns, with no other rule-parsing except for in-file comments. o A C is a way to specify that the file should be read in a CVS-compatible manner. This turns on 'n', 'w', and '-', but also allows the list-clearing token (!) to be specified. If no filename is provided, ".cvsignore" is assumed. o A e will exclude the merge-file name from the transfer; e.g. "dir-merge,e .rules" is like "dir-merge .rules" and "- .rules". o An n specifies that the rules are not inherited by subdirectories. o A w specifies that the rules are word-split on whitespace instead of the normal line-splitting. This also turns off comments. Note: the space that separates the prefix from the rule is treated specially, so "- foo + bar" is parsed as two rules (assuming that prefix-parsing wasn't also disabled). o You may also specify any of the modifiers for the "+" or "-" rules (above) in order to have the rules that are read in from the file default to having that modifier set (except for the ! modifier, which would not be useful). For instance, "merge,-/ .excl" would treat the contents of .excl as absolute-path excludes, while "dir-merge,s .filt" and ":sC" would each make all their per-directory rules apply only on the sending side. If the merge rule specifies sides to affect (via the s or r modifier or both), then the rules in the file must not specify sides (via a modifier or a rule prefix such as hide). Per-directory rules are inherited in all subdirectories of the directory where the merge-file was found unless the 'n' modifier was used. Each subdirectory's rules are prefixed to the inherited per-directory rules from its parents, which gives the newest rules a higher priority than the inherited rules. The entire set of dir-merge rules are grouped together in the spot where the merge-file was specified, so it is possible to override dir-merge rules via a rule that got specified earlier in the list of global rules. When the list-clearing rule ("!") is read from a per-directory file, it only clears the inherited rules for the current merge file. Another way to prevent a single rule from a dir-merge file from being inherited is to anchor it with a leading slash. Anchored rules in a per-directory merge-file are relative to the merge- file's directory, so a pattern "/foo" would only match the file "foo" in the directory where the dir-merge filter file was found. Here's an example filter file which you'd specify via --filter=". file": merge /home/user/.global-filter - *.gz dir-merge .rules + *.[ch] - *.o - foo* This will merge the contents of the /home/user/.global-filter file at the start of the list and also turns the ".rules" filename into a per-directory filter file. All rules read in prior to the start of the directory scan follow the global anchoring rules (i.e. a leading slash matches at the root of the transfer). If a per-directory merge-file is specified with a path that is a parent directory of the first transfer directory, rsync will scan all the parent dirs from that starting point to the transfer directory for the indicated per-directory file. For instance, here is a common filter (see -F): --filter=': /.rsync-filter' That rule tells rsync to scan for the file .rsync-filter in all directories from the root down through the parent directory of the transfer prior to the start of the normal directory scan of the file in the directories that are sent as a part of the transfer. (Note: for an rsync daemon, the root is always the same as the module's "path".) Some examples of this pre-scanning for per-directory files: rsync -avF /src/path/ /dest/dir rsync -av --filter=': ../../.rsync-filter' /src/path/ /dest/dir rsync -av --filter=': .rsync-filter' /src/path/ /dest/dir The first two commands above will look for ".rsync-filter" in "/" and "/src" before the normal scan begins looking for the file in "/src/path" and its subdirectories. The last command avoids the parent-dir scan and only looks for the ".rsync-filter" files in each directory that is a part of the transfer. If you want to include the contents of a ".cvsignore" in your patterns, you should use the rule ":C", which creates a dir-merge of the .cvsignore file, but parsed in a CVS-compatible manner. You can use this to affect where the --cvs-exclude (-C) option's inclusion of the per-directory .cvsignore file gets placed into your rules by putting the ":C" wherever you like in your filter rules. Without this, rsync would add the dir-merge rule for the .cvsignore file at the end of all your other rules (giving it a lower priority than your command-line rules). For example: cat <<EOT | rsync -avC --filter='. -' a/ b + foo.o :C - *.old EOT rsync -avC --include=foo.o -f :C --exclude='*.old' a/ b Both of the above rsync commands are identical. Each one will merge all the per-directory .cvsignore rules in the middle of the list rather than at the end. This allows their dir-specific rules to supersede the rules that follow the :C instead of being subservient to all your rules. To affect the other CVS exclude rules (i.e. the default list of exclusions, the contents of $HOME/.cvsignore, and the value of $CVSIGNORE) you should omit the -C command-line option and instead insert a "-C" rule into your filter rules; e.g. "--filter=-C". LIST-CLEARING FILTER RULE You can clear the current include/exclude list by using the "!" filter rule (as introduced in the FILTER RULES section above). The "current" list is either the global list of rules (if the rule is encountered while parsing the filter options) or a set of per-directory rules (which are inherited in their own sub-list, so a subdirectory can use this to clear out the parent's rules). ANCHORING INCLUDE/EXCLUDE PATTERNS As mentioned earlier, global include/exclude patterns are anchored at the "root of the transfer" (as opposed to per- directory patterns, which are anchored at the merge-file's directory). If you think of the transfer as a subtree of names that are being sent from sender to receiver, the transfer-root is where the tree starts to be duplicated in the destination directory. This root governs where patterns that start with a / match. Because the matching is relative to the transfer-root, changing the trailing slash on a source path or changing your use of the --relative option affects the path you need to use in your matching (in addition to changing how much of the file tree is duplicated on the destination host). The following examples demonstrate this. Let's say that we want to match two source files, one with an absolute path of "/home/me/foo/bar", and one with a path of "/home/you/bar/baz". Here is how the various command choices differ for a 2-source transfer: Example cmd: rsync -a /home/me /home/you /dest +/- pattern: /me/foo/bar +/- pattern: /you/bar/baz Target file: /dest/me/foo/bar Target file: /dest/you/bar/baz Example cmd: rsync -a /home/me/ /home/you/ /dest +/- pattern: /foo/bar (note missing "me") +/- pattern: /bar/baz (note missing "you") Target file: /dest/foo/bar Target file: /dest/bar/baz Example cmd: rsync -a --relative /home/me/ /home/you /dest +/- pattern: /home/me/foo/bar (note full path) +/- pattern: /home/you/bar/baz (ditto) Target file: /dest/home/me/foo/bar Target file: /dest/home/you/bar/baz Example cmd: cd /home; rsync -a --relative me/foo you/ /dest +/- pattern: /me/foo/bar (starts at specified path) +/- pattern: /you/bar/baz (ditto) Target file: /dest/me/foo/bar Target file: /dest/you/bar/baz The easiest way to see what name you should filter is to just look at the output when using --verbose and put a / in front of the name (use the --dry-run option if you're not yet ready to copy any files). PER-DIRECTORY RULES AND DELETE Without a delete option, per-directory rules are only relevant on the sending side, so you can feel free to exclude the merge files themselves without affecting the transfer. To make this easy, the 'e' modifier adds this exclude for you, as seen in these two equivalent commands: rsync -av --filter=': .excl' --exclude=.excl host:src/dir /dest rsync -av --filter=':e .excl' host:src/dir /dest However, if you want to do a delete on the receiving side AND you want some files to be excluded from being deleted, you'll need to be sure that the receiving side knows what files to exclude. The easiest way is to include the per-directory merge files in the transfer and use --delete-after, because this ensures that the receiving side gets all the same exclude rules as the sending side before it tries to delete anything: rsync -avF --delete-after host:src/dir /dest However, if the merge files are not a part of the transfer, you'll need to either specify some global exclude rules (i.e. specified on the command line), or you'll need to maintain your own per-directory merge files on the receiving side. An example of the first is this (assume that the remote .rules files exclude themselves): rsync -av --filter=': .rules' --filter='. /my/extra.rules' --delete host:src/dir /dest In the above example the extra.rules file can affect both sides of the transfer, but (on the sending side) the rules are subservient to the rules merged from the .rules files because they were specified after the per-directory merge rule. In one final example, the remote side is excluding the .rsync- filter files from the transfer, but we want to use our own .rsync-filter files to control what gets deleted on the receiving side. To do this we must specifically exclude the per-directory merge files (so that they don't get deleted) and then put rules into the local files to control what else should not get deleted. Like one of these commands: rsync -av --filter=':e /.rsync-filter' --delete \ host:src/dir /dest rsync -avFF --delete host:src/dir /dest TRANSFER RULES top In addition to the FILTER RULES that affect the recursive file scans that generate the file list on the sending and (when deleting) receiving sides, there are transfer rules. These rules affect which files the generator decides need to be transferred without the side effects of an exclude filter rule. Transfer rules affect only files and never directories. Because a transfer rule does not affect what goes into the sender's (and receiver's) file list, it cannot have any effect on which files get deleted on the receiving side. For example, if the file "foo" is present in the sender's list but its size is such that it is omitted due to a transfer rule, the receiving side does not request the file. However, its presence in the file list means that a delete pass will not remove a matching file named "foo" on the receiving side. On the other hand, a server-side exclude (hide) of the file "foo" leaves the file out of the server's file list, and absent a receiver-side exclude (protect) the receiver will remove a matching file named "foo" if deletions are requested. Given that the files are still in the sender's file list, the --prune-empty-dirs option will not judge a directory as being empty even if it contains only files that the transfer rules omitted. Similarly, a transfer rule does not have any extra effect on which files are deleted on the receiving side, so setting a maximum file size for the transfer does not prevent big files from being deleted. Examples of transfer rules include the default "quick check" algorithm (which compares size & modify time), the --update option, the --max-size option, the --ignore-non-existing option, and a few others. BATCH MODE top Batch mode can be used to apply the same set of updates to many identical systems. Suppose one has a tree which is replicated on a number of hosts. Now suppose some changes have been made to this source tree and those changes need to be propagated to the other hosts. In order to do this using batch mode, rsync is run with the write-batch option to apply the changes made to the source tree to one of the destination trees. The write-batch option causes the rsync client to store in a "batch file" all the information needed to repeat this operation against other, identical destination trees. Generating the batch file once saves having to perform the file status, checksum, and data block generation more than once when updating multiple destination trees. Multicast transport protocols can be used to transfer the batch update files in parallel to many hosts at once, instead of sending the same data to every host individually. To apply the recorded changes to another destination tree, run rsync with the read-batch option, specifying the name of the same batch file, and the destination tree. Rsync updates the destination tree using the information stored in the batch file. For your convenience, a script file is also created when the write-batch option is used: it will be named the same as the batch file with ".sh" appended. This script file contains a command-line suitable for updating a destination tree using the associated batch file. It can be executed using a Bourne (or Bourne-like) shell, optionally passing in an alternate destination tree pathname which is then used instead of the original destination path. This is useful when the destination tree path on the current host differs from the one used to create the batch file. Examples: $ rsync --write-batch=foo -a host:/source/dir/ /adest/dir/ $ scp foo* remote: $ ssh remote ./foo.sh /bdest/dir/ $ rsync --write-batch=foo -a /source/dir/ /adest/dir/ $ ssh remote rsync --read-batch=- -a /bdest/dir/ <foo In these examples, rsync is used to update /adest/dir/ from /source/dir/ and the information to repeat this operation is stored in "foo" and "foo.sh". The host "remote" is then updated with the batched data going into the directory /bdest/dir. The differences between the two examples reveals some of the flexibility you have in how you deal with batches: o The first example shows that the initial copy doesn't have to be local -- you can push or pull data to/from a remote host using either the remote-shell syntax or rsync daemon syntax, as desired. o The first example uses the created "foo.sh" file to get the right rsync options when running the read-batch command on the remote host. o The second example reads the batch data via standard input so that the batch file doesn't need to be copied to the remote machine first. This example avoids the foo.sh script because it needed to use a modified --read-batch option, but you could edit the script file if you wished to make use of it (just be sure that no other option is trying to use standard input, such as the --exclude-from=- option). Caveats: The read-batch option expects the destination tree that it is updating to be identical to the destination tree that was used to create the batch update fileset. When a difference between the destination trees is encountered the update might be discarded with a warning (if the file appears to be up-to-date already) or the file-update may be attempted and then, if the file fails to verify, the update discarded with an error. This means that it should be safe to re-run a read-batch operation if the command got interrupted. If you wish to force the batched-update to always be attempted regardless of the file's size and date, use the -I option (when reading the batch). If an error occurs, the destination tree will probably be in a partially updated state. In that case, rsync can be used in its regular (non-batch) mode of operation to fix up the destination tree. The rsync version used on all destinations must be at least as new as the one used to generate the batch file. Rsync will die with an error if the protocol version in the batch file is too new for the batch-reading rsync to handle. See also the --protocol option for a way to have the creating rsync generate a batch file that an older rsync can understand. (Note that batch files changed format in version 2.6.3, so mixing versions older than that with newer versions will not work.) When reading a batch file, rsync will force the value of certain options to match the data in the batch file if you didn't set them to the same as the batch-writing command. Other options can (and should) be changed. For instance --write-batch changes to --read-batch, --files-from is dropped, and the --filter / --include / --exclude options are not needed unless one of the --delete options is specified. The code that creates the BATCH.sh file transforms any filter/include/exclude options into a single list that is appended as a "here" document to the shell script file. An advanced user can use this to modify the exclude list if a change in what gets deleted by --delete is desired. A normal user can ignore this detail and just use the shell script as an easy way to run the appropriate --read-batch command for the batched data. The original batch mode in rsync was based on "rsync+", but the latest version uses a new implementation. SYMBOLIC LINKS top Three basic behaviors are possible when rsync encounters a symbolic link in the source directory. By default, symbolic links are not transferred at all. A message "skipping non-regular" file is emitted for any symlinks that exist. If --links is specified, then symlinks are added to the transfer (instead of being noisily ignored), and the default handling is to recreate them with the same target on the destination. Note that --archive implies --links. If --copy-links is specified, then symlinks are "collapsed" by copying their referent, rather than the symlink. Rsync can also distinguish "safe" and "unsafe" symbolic links. An example where this might be used is a web site mirror that wishes to ensure that the rsync module that is copied does not include symbolic links to /etc/passwd in the public section of the site. Using --copy-unsafe-links will cause any links to be copied as the file they point to on the destination. Using --safe-links will cause unsafe links to be omitted by the receiver. (Note that you must specify or imply --links for --safe-links to have any effect.) Symbolic links are considered unsafe if they are absolute symlinks (start with /), empty, or if they contain enough ".." components to ascend from the top of the transfer. Here's a summary of how the symlink options are interpreted. The list is in order of precedence, so if your combination of options isn't mentioned, use the first line that is a complete subset of your options: --copy-links Turn all symlinks into normal files and directories (leaving no symlinks in the transfer for any other options to affect). --copy-dirlinks Turn just symlinks to directories into real directories, leaving all other symlinks to be handled as described below. --links --copy-unsafe-links Turn all unsafe symlinks into files and create all safe symlinks. --copy-unsafe-links Turn all unsafe symlinks into files, noisily skip all safe symlinks. --links --safe-links The receiver skips creating unsafe symlinks found in the transfer and creates the safe ones. --links Create all symlinks. For the effect of --munge-links, see the discussion in that option's section. Note that the --keep-dirlinks option does not effect symlinks in the transfer but instead affects how rsync treats a symlink to a directory that already exists on the receiving side. See that option's section for a warning. DIAGNOSTICS top Rsync occasionally produces error messages that may seem a little cryptic. The one that seems to cause the most confusion is "protocol version mismatch -- is your shell clean?". This message is usually caused by your startup scripts or remote shell facility producing unwanted garbage on the stream that rsync is using for its transport. The way to diagnose this problem is to run your remote shell like this: ssh remotehost /bin/true > out.dat then look at out.dat. If everything is working correctly then out.dat should be a zero length file. If you are getting the above error from rsync then you will probably find that out.dat contains some text or data. Look at the contents and try to work out what is producing it. The most common cause is incorrectly configured shell startup scripts (such as .cshrc or .profile) that contain output statements for non-interactive logins. If you are having trouble debugging filter patterns, then try specifying the -vv option. At this level of verbosity rsync will show why each individual file is included or excluded. EXIT VALUES top o 0 - Success o 1 - Syntax or usage error o 2 - Protocol incompatibility o 3 - Errors selecting input/output files, dirs o o 4 - Requested action not supported. Either: an attempt was made to manipulate 64-bit files on a platform that cannot support them o an option was specified that is supported by the client and not by the server o 5 - Error starting client-server protocol o 6 - Daemon unable to append to log-file o 10 - Error in socket I/O o 11 - Error in file I/O o 12 - Error in rsync protocol data stream o 13 - Errors with program diagnostics o 14 - Error in IPC code o 20 - Received SIGUSR1 or SIGINT o 21 - Some error returned by waitpid() o 22 - Error allocating core memory buffers o 23 - Partial transfer due to error o 24 - Partial transfer due to vanished source files o 25 - The --max-delete limit stopped deletions o 30 - Timeout in data send/receive o 35 - Timeout waiting for daemon connection ENVIRONMENT VARIABLES top CVSIGNORE The CVSIGNORE environment variable supplements any ignore patterns in .cvsignore files. See the --cvs-exclude option for more details. RSYNC_ICONV Specify a default --iconv setting using this environment variable. First supported in 3.0.0. RSYNC_OLD_ARGS Specify a "1" if you want the --old-args option to be enabled by default, a "2" (or more) if you want it to be enabled in the repeated-option state, or a "0" to make sure that it is disabled by default. When this environment variable is set to a non-zero value, it supersedes the RSYNC_PROTECT_ARGS variable. This variable is ignored if --old-args, --no-old-args, or --secluded-args is specified on the command line. First supported in 3.2.4. RSYNC_PROTECT_ARGS Specify a non-zero numeric value if you want the --secluded-args option to be enabled by default, or a zero value to make sure that it is disabled by default. This variable is ignored if --secluded-args, --no- secluded-args, or --old-args is specified on the command line. First supported in 3.1.0. Starting in 3.2.4, this variable is ignored if RSYNC_OLD_ARGS is set to a non-zero value. RSYNC_RSH This environment variable allows you to override the default shell used as the transport for rsync. Command line options are permitted after the command name, just as in the --rsh (-e) option. RSYNC_PROXY This environment variable allows you to redirect your rsync client to use a web proxy when connecting to an rsync daemon. You should set RSYNC_PROXY to a hostname:port pair. RSYNC_PASSWORD This environment variable allows you to set the password for an rsync daemon connection, which avoids the password prompt. Note that this does not supply a password to a remote shell transport such as ssh (consult its documentation for how to do that). USER or LOGNAME The USER or LOGNAME environment variables are used to determine the default username sent to an rsync daemon. If neither is set, the username defaults to "nobody". If both are set, USER takes precedence. RSYNC_PARTIAL_DIR This environment variable specifies the directory to use for a --partial transfer without implying that partial transfers be enabled. See the --partial-dir option for full details. RSYNC_COMPRESS_LIST This environment variable allows you to customize the negotiation of the compression algorithm by specifying an alternate order or a reduced list of names. Use the command rsync --version to see the available compression names. See the --compress option for full details. RSYNC_CHECKSUM_LIST This environment variable allows you to customize the negotiation of the checksum algorithm by specifying an alternate order or a reduced list of names. Use the command rsync --version to see the available checksum names. See the --checksum-choice option for full details. RSYNC_MAX_ALLOC This environment variable sets an allocation maximum as if you had used the --max-alloc option. RSYNC_PORT This environment variable is not read by rsync, but is instead set in its sub-environment when rsync is running the remote shell in combination with a daemon connection. This allows a script such as rsync-ssl to be able to know the port number that the user specified on the command line. HOME This environment variable is used to find the user's default .cvsignore file. RSYNC_CONNECT_PROG This environment variable is mainly used in debug setups to set the program to use when making a daemon connection. See CONNECTING TO AN RSYNC DAEMON for full details. RSYNC_SHELL This environment variable is mainly used in debug setups to set the program to use to run the program specified by RSYNC_CONNECT_PROG. See CONNECTING TO AN RSYNC DAEMON for full details. FILES top /etc/rsyncd.conf or rsyncd.conf SEE ALSO top rsync-ssl(1), rsyncd.conf(5), rrsync(1) BUGS top o Times are transferred as *nix time_t values. o When transferring to FAT filesystems rsync may re-sync unmodified files. See the comments on the --modify-window option. o File permissions, devices, etc. are transferred as native numerical values. o See also the comments on the --delete option. Please report bugs! See the web site at https://rsync.samba.org/. VERSION top This manpage is current for version 3.2.7 of rsync. INTERNAL OPTIONS top The options --server and --sender are used internally by rsync, and should never be typed by a user under normal circumstances. Some awareness of these options may be needed in certain scenarios, such as when setting up a login that can only run an rsync command. For instance, the support directory of the rsync distribution has an example script named rrsync (for restricted rsync) that can be used with a restricted ssh login. CREDITS top Rsync is distributed under the GNU General Public License. See the file COPYING for details. An rsync web site is available at https://rsync.samba.org/. The site includes an FAQ-O-Matic which may cover questions unanswered by this manual page. The rsync github project is https://github.com/WayneD/rsync. We would be delighted to hear from you if you like this program. Please contact the mailing-list at rsync@lists.samba.org. This program uses the excellent zlib compression library written by Jean-loup Gailly and Mark Adler. THANKS top Special thanks go out to: John Van Essen, Matt McCutchen, Wesley W. Terpstra, David Dykstra, Jos Backus, Sebastian Krahmer, Martin Pool, and our gone-but-not-forgotten compadre, J.W. Schultz. Thanks also to Richard Brent, Brendan Mackay, Bill Waite, Stephen Rothwell and David Bell. I've probably missed some people, my apologies if I have. AUTHOR top Rsync was originally written by Andrew Tridgell and Paul Mackerras. Many people have later contributed to it. It is currently maintained by Wayne Davison. Mailing lists for support and development are available at https://lists.samba.org/. COLOPHON top This page is part of the rsync (a fast, versatile, remote (and local) file-copying tool) project. Information about the project can be found at https://rsync.samba.org/. If you have a bug report for this manual page, see https://rsync.samba.org/bugzilla.html. This page was obtained from the tarball fetched from https://download.samba.org/pub/rsync/ 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 rsync 3.2.7 20 Oct 2022 rsync(1) Pages that refer to this page: pmlogger_daily(1), rrsync(1), rsync-ssl(1), rsyncd.conf(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: Copy "*.cc", "*.h", and "SConstruct" to "rsync://localhost:40001/bledge_ce" using blocking IO Bash Command:<START>rsync --blocking-io *.cc *.h SConstruct rsync://localhost:40001/bledge_ce<END>
Copy "./export" recursively to "/path/to/webroot" preserving permissions
rsync -pr ./export /path/to/webroot
['rsync']
Output a Bash command to accomplish the following task. Task: Copy "./export" recursively to "/path/to/webroot" preserving permissions Bash Command:<START>rsync -pr ./export /path/to/webroot<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # rsync\n\n> Transfer files either to or from a remote host (but not between two remote hosts), by default using SSH.\n> To specify a remote path, use `user@host:path/to/file_or_directory`.\n> More information: <https://download.samba.org/pub/rsync/rsync.1>.\n\n- Transfer a file:\n\n`rsync {{path/to/source}} {{path/to/destination}}`\n\n- Use archive mode (recursively copy directories, copy symlinks without resolving, and preserve permissions, ownership and modification times):\n\n`rsync --archive {{path/to/source}} {{path/to/destination}}`\n\n- Compress the data as it is sent to the destination, display verbose and human-readable progress, and keep partially transferred files if interrupted:\n\n`rsync --compress --verbose --human-readable --partial --progress {{path/to/source}} {{path/to/destination}}`\n\n- Recursively copy directories:\n\n`rsync --recursive {{path/to/source}} {{path/to/destination}}`\n\n- Transfer directory contents, but not the directory itself:\n\n`rsync --recursive {{path/to/source}}/ {{path/to/destination}}`\n\n- Use archive mode, resolve symlinks and skip files that are newer on the destination:\n\n`rsync --archive --update --copy-links {{path/to/source}} {{path/to/destination}}`\n\n- Transfer a directory to a remote host running `rsyncd` and delete files on the destination that do not exist on the source:\n\n`rsync --recursive --delete rsync://{{host}}:{{path/to/source}} {{path/to/destination}}`\n\n- Transfer a file over SSH using a different port than the default (22) and show global progress:\n\n`rsync --rsh 'ssh -p {{port}}' --info=progress2 {{host}}:{{path/to/source}} {{path/to/destination}}`\n Task: Copy "./export" recursively to "/path/to/webroot" preserving permissions Bash Command:<START>rsync -pr ./export /path/to/webroot<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: rsync(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rsync(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | GENERAL | SETUP | USAGE | COPYING TO A DIFFERENT NAME | SORTED TRANSFER ORDER | MULTI-HOST SECURITY | ADVANCED USAGE | CONNECTING TO AN RSYNC DAEMON | USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION | STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS | EXAMPLES | OPTION SUMMARY | OPTIONS | DAEMON OPTIONS | FILTER RULES | TRANSFER RULES | BATCH MODE | SYMBOLIC LINKS | DIAGNOSTICS | EXIT VALUES | ENVIRONMENT VARIABLES | FILES | SEE ALSO | BUGS | VERSION | INTERNAL OPTIONS | CREDITS | THANKS | AUTHOR | COLOPHON rsync(1) User Commands rsync(1) NAME top rsync - a fast, versatile, remote (and local) file-copying tool SYNOPSIS top Local: rsync [OPTION...] SRC... [DEST] Access via remote shell: Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST] Push: rsync [OPTION...] SRC... [USER@]HOST:DEST Access via rsync daemon: Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST] rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST] Push: rsync [OPTION...] SRC... [USER@]HOST::DEST rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST) Usages with just one SRC arg and no DEST arg will list the source files instead of copying. The online version of this manpage (that includes cross-linking of topics) is available at https://download.samba.org/pub/rsync/rsync.1. DESCRIPTION top Rsync is a fast and extraordinarily versatile file copying tool. It can copy locally, to/from another host over any remote shell, or to/from a remote rsync daemon. It offers a large number of options that control every aspect of its behavior and permit very flexible specification of the set of files to be copied. It is famous for its delta-transfer algorithm, which reduces the amount of data sent over the network by sending only the differences between the source files and the existing files in the destination. Rsync is widely used for backups and mirroring and as an improved copy command for everyday use. Rsync finds files that need to be transferred using a "quick check" algorithm (by default) that looks for files that have changed in size or in last-modified time. Any changes in the other preserved attributes (as requested by options) are made on the destination file directly when the quick check indicates that the file's data does not need to be updated. Some of the additional features of rsync are: o support for copying links, devices, owners, groups, and permissions o exclude and exclude-from options similar to GNU tar o a CVS exclude mode for ignoring the same files that CVS would ignore o can use any transparent remote shell, including ssh or rsh o does not require super-user privileges o pipelining of file transfers to minimize latency costs o support for anonymous or authenticated rsync daemons (ideal for mirroring) GENERAL top Rsync copies files either to or from a remote host, or locally on the current host (it does not support copying files between two remote hosts). There are two different ways for rsync to contact a remote system: using a remote-shell program as the transport (such as ssh or rsh) or contacting an rsync daemon directly via TCP. The remote-shell transport is used whenever the source or destination path contains a single colon (:) separator after a host specification. Contacting an rsync daemon directly happens when the source or destination path contains a double colon (::) separator after a host specification, OR when an rsync:// URL is specified (see also the USING RSYNC-DAEMON FEATURES VIA A REMOTE- SHELL CONNECTION section for an exception to this latter rule). As a special case, if a single source arg is specified without a destination, the files are listed in an output format similar to "ls -l". As expected, if neither the source or destination path specify a remote host, the copy occurs locally (see also the --list-only option). Rsync refers to the local side as the client and the remote side as the server. Don't confuse server with an rsync daemon. A daemon is always a server, but a server can be either a daemon or a remote-shell spawned process. SETUP top See the file README.md for installation instructions. Once installed, you can use rsync to any machine that you can access via a remote shell (as well as some that you can access using the rsync daemon-mode protocol). For remote transfers, a modern rsync uses ssh for its communications, but it may have been configured to use a different remote shell by default, such as rsh or remsh. You can also specify any remote shell you like, either by using the -e command line option, or by setting the RSYNC_RSH environment variable. Note that rsync must be installed on both the source and destination machines. USAGE top You use rsync in the same way you use rcp. You must specify a source and a destination, one of which may be remote. Perhaps the best way to explain the syntax is with some examples: rsync -t *.c foo:src/ This would transfer all files matching the pattern *.c from the current directory to the directory src on the machine foo. If any of the files already exist on the remote system then the rsync remote-update protocol is used to update the file by sending only the differences in the data. Note that the expansion of wildcards on the command-line (*.c) into a list of files is handled by the shell before it runs rsync and not by rsync itself (exactly the same as all other Posix-style programs). rsync -avz foo:src/bar /data/tmp This would recursively transfer all files from the directory src/bar on the machine foo into the /data/tmp/bar directory on the local machine. The files are transferred in archive mode, which ensures that symbolic links, devices, attributes, permissions, ownerships, etc. are preserved in the transfer. Additionally, compression will be used to reduce the size of data portions of the transfer. rsync -avz foo:src/bar/ /data/tmp A trailing slash on the source changes this behavior to avoid creating an additional directory level at the destination. You can think of a trailing / on a source as meaning "copy the contents of this directory" as opposed to "copy the directory by name", but in both cases the attributes of the containing directory are transferred to the containing directory on the destination. In other words, each of the following commands copies the files in the same way, including their setting of the attributes of /dest/foo: rsync -av /src/foo /dest rsync -av /src/foo/ /dest/foo Note also that host and module references don't require a trailing slash to copy the contents of the default directory. For example, both of these copy the remote directory's contents into "/dest": rsync -av host: /dest rsync -av host::module /dest You can also use rsync in local-only mode, where both the source and destination don't have a ':' in the name. In this case it behaves like an improved copy command. Finally, you can list all the (listable) modules available from a particular rsync daemon by leaving off the module name: rsync somehost.mydomain.com:: COPYING TO A DIFFERENT NAME top When you want to copy a directory to a different name, use a trailing slash on the source directory to put the contents of the directory into any destination directory you like: rsync -ai foo/ bar/ Rsync also has the ability to customize a destination file's name when copying a single item. The rules for this are: o The transfer list must consist of a single item (either a file or an empty directory) o The final element of the destination path must not exist as a directory o The destination path must not have been specified with a trailing slash Under those circumstances, rsync will set the name of the destination's single item to the last element of the destination path. Keep in mind that it is best to only use this idiom when copying a file and use the above trailing-slash idiom when copying a directory. The following example copies the foo.c file as bar.c in the save dir (assuming that bar.c isn't a directory): rsync -ai src/foo.c save/bar.c The single-item copy rule might accidentally bite you if you unknowingly copy a single item and specify a destination dir that doesn't exist (without using a trailing slash). For example, if src/*.c matches one file and save/dir doesn't exist, this will confuse you by naming the destination file save/dir: rsync -ai src/*.c save/dir To prevent such an accident, either make sure the destination dir exists or specify the destination path with a trailing slash: rsync -ai src/*.c save/dir/ SORTED TRANSFER ORDER top Rsync always sorts the specified filenames into its internal transfer list. This handles the merging together of the contents of identically named directories, makes it easy to remove duplicate filenames. It can, however, confuse someone when the files are transferred in a different order than what was given on the command-line. If you need a particular file to be transferred prior to another, either separate the files into different rsync calls, or consider using --delay-updates (which doesn't affect the sorted transfer order, but does make the final file-updating phase happen much more rapidly). MULTI-HOST SECURITY top Rsync takes steps to ensure that the file requests that are shared in a transfer are protected against various security issues. Most of the potential problems arise on the receiving side where rsync takes steps to ensure that the list of files being transferred remains within the bounds of what was requested. Toward this end, rsync 3.1.2 and later have aborted when a file list contains an absolute or relative path that tries to escape out of the top of the transfer. Also, beginning with version 3.2.5, rsync does two more safety checks of the file list to (1) ensure that no extra source arguments were added into the transfer other than those that the client requested and (2) ensure that the file list obeys the exclude rules that were sent to the sender. For those that don't yet have a 3.2.5 client rsync (or those that want to be extra careful), it is safest to do a copy into a dedicated destination directory for the remote files when you don't trust the remote host. For example, instead of doing an rsync copy into your home directory: rsync -aiv host1:dir1 ~ Dedicate a "host1-files" dir to the remote content: rsync -aiv host1:dir1 ~/host1-files See the --trust-sender option for additional details. CAUTION: it is not particularly safe to use rsync to copy files from a case-preserving filesystem to a case-ignoring filesystem. If you must perform such a copy, you should either disable symlinks via --no-links or enable the munging of symlinks via --munge-links (and make sure you use the right local or remote option). This will prevent rsync from doing potentially dangerous things if a symlink name overlaps with a file or directory. It does not, however, ensure that you get a full copy of all the files (since that may not be possible when the names overlap). A potentially better solution is to list all the source files and create a safe list of filenames that you pass to the --files-from option. Any files that conflict in name would need to be copied to different destination directories using more than one copy. While a copy of a case-ignoring filesystem to a case-ignoring filesystem can work out fairly well, if no --delete-during or --delete-before option is active, rsync can potentially update an existing file on the receiveing side without noticing that the upper-/lower-case of the filename should be changed to match the sender. ADVANCED USAGE top The syntax for requesting multiple files from a remote host is done by specifying additional remote-host args in the same style as the first, or with the hostname omitted. For instance, all these work: rsync -aiv host:file1 :file2 host:file{3,4} /dest/ rsync -aiv host::modname/file{1,2} host::modname/extra /dest/ rsync -aiv host::modname/first ::extra-file{1,2} /dest/ Note that a daemon connection only supports accessing one module per copy command, so if the start of a follow-up path doesn't begin with the modname of the first path, it is assumed to be a path in the module (such as the extra-file1 & extra-file2 that are grabbed above). Really old versions of rsync (2.6.9 and before) only allowed specifying one remote-source arg, so some people have instead relied on the remote-shell performing space splitting to break up an arg into multiple paths. Such unintuitive behavior is no longer supported by default (though you can request it, as described below). Starting in 3.2.4, filenames are passed to a remote shell in such a way as to preserve the characters you give it. Thus, if you ask for a file with spaces in the name, that's what the remote rsync looks for: rsync -aiv host:'a simple file.pdf' /dest/ If you use scripts that have been written to manually apply extra quoting to the remote rsync args (or to require remote arg splitting), you can ask rsync to let your script handle the extra escaping. This is done by either adding the --old-args option to the rsync runs in the script (which requires a new rsync) or exporting RSYNC_OLD_ARGS=1 and RSYNC_PROTECT_ARGS=0 (which works with old or new rsync versions). CONNECTING TO AN RSYNC DAEMON top It is also possible to use rsync without a remote shell as the transport. In this case you will directly connect to a remote rsync daemon, typically using TCP port 873. (This obviously requires the daemon to be running on the remote system, so refer to the STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS section below for information on that.) Using rsync in this way is the same as using it with a remote shell except that: o Use either double-colon syntax or rsync:// URL syntax instead of the single-colon (remote shell) syntax. o The first element of the "path" is actually a module name. o Additional remote source args can use an abbreviated syntax that omits the hostname and/or the module name, as discussed in ADVANCED USAGE. o The remote daemon may print a "message of the day" when you connect. o If you specify only the host (with no module or path) then a list of accessible modules on the daemon is output. o If you specify a remote source path but no destination, a listing of the matching files on the remote daemon is output. o The --rsh (-e) option must be omitted to avoid changing the connection style from using a socket connection to USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION. An example that copies all the files in a remote module named "src": rsync -av host::src /dest Some modules on the remote daemon may require authentication. If so, you will receive a password prompt when you connect. You can avoid the password prompt by setting the environment variable RSYNC_PASSWORD to the password you want to use or using the --password-file option. This may be useful when scripting rsync. WARNING: On some systems environment variables are visible to all users. On those systems using --password-file is recommended. You may establish the connection via a web proxy by setting the environment variable RSYNC_PROXY to a hostname:port pair pointing to your web proxy. Note that your web proxy's configuration must support proxy connections to port 873. You may also establish a daemon connection using a program as a proxy by setting the environment variable RSYNC_CONNECT_PROG to the commands you wish to run in place of making a direct socket connection. The string may contain the escape "%H" to represent the hostname specified in the rsync command (so use "%%" if you need a single "%" in your string). For example: export RSYNC_CONNECT_PROG='ssh proxyhost nc %H 873' rsync -av targethost1::module/src/ /dest/ rsync -av rsync://targethost2/module/src/ /dest/ The command specified above uses ssh to run nc (netcat) on a proxyhost, which forwards all data to port 873 (the rsync daemon) on the targethost (%H). Note also that if the RSYNC_SHELL environment variable is set, that program will be used to run the RSYNC_CONNECT_PROG command instead of using the default shell of the system() call. USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION top It is sometimes useful to use various features of an rsync daemon (such as named modules) without actually allowing any new socket connections into a system (other than what is already required to allow remote-shell access). Rsync supports connecting to a host using a remote shell and then spawning a single-use "daemon" server that expects to read its config file in the home dir of the remote user. This can be useful if you want to encrypt a daemon-style transfer's data, but since the daemon is started up fresh by the remote user, you may not be able to use features such as chroot or change the uid used by the daemon. (For another way to encrypt a daemon transfer, consider using ssh to tunnel a local port to a remote machine and configure a normal rsync daemon on that remote host to only allow connections from "localhost".) From the user's perspective, a daemon transfer via a remote-shell connection uses nearly the same command-line syntax as a normal rsync-daemon transfer, with the only exception being that you must explicitly set the remote shell program on the command-line with the --rsh=COMMAND option. (Setting the RSYNC_RSH in the environment will not turn on this functionality.) For example: rsync -av --rsh=ssh host::module /dest If you need to specify a different remote-shell user, keep in mind that the user@ prefix in front of the host is specifying the rsync-user value (for a module that requires user-based authentication). This means that you must give the '-l user' option to ssh when specifying the remote-shell, as in this example that uses the short version of the --rsh option: rsync -av -e "ssh -l ssh-user" rsync-user@host::module /dest The "ssh-user" will be used at the ssh level; the "rsync-user" will be used to log-in to the "module". In this setup, the daemon is started by the ssh command that is accessing the system (which can be forced via the ~/.ssh/authorized_keys file, if desired). However, when accessing a daemon directly, it needs to be started beforehand. STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS top In order to connect to an rsync daemon, the remote system needs to have a daemon already running (or it needs to have configured something like inetd to spawn an rsync daemon for incoming connections on a particular port). For full information on how to start a daemon that will handling incoming socket connections, see the rsyncd.conf(5) manpage -- that is the config file for the daemon, and it contains the full details for how to run the daemon (including stand-alone and inetd configurations). If you're using one of the remote-shell transports for the transfer, there is no need to manually start an rsync daemon. EXAMPLES top Here are some examples of how rsync can be used. To backup a home directory, which consists of large MS Word files and mail folders, a per-user cron job can be used that runs this each day: rsync -aiz . bkhost:backup/joe/ To move some files from a remote host to the local host, you could run: rsync -aiv --remove-source-files rhost:/tmp/{file1,file2}.c ~/src/ OPTION SUMMARY top Here is a short summary of the options available in rsync. Each option also has its own detailed description later in this manpage. --verbose, -v increase verbosity --info=FLAGS fine-grained informational verbosity --debug=FLAGS fine-grained debug verbosity --stderr=e|a|c change stderr output mode (default: errors) --quiet, -q suppress non-error messages --no-motd suppress daemon-mode MOTD --checksum, -c skip based on checksum, not mod-time & size --archive, -a archive mode is -rlptgoD (no -A,-X,-U,-N,-H) --no-OPTION turn off an implied OPTION (e.g. --no-D) --recursive, -r recurse into directories --relative, -R use relative path names --no-implied-dirs don't send implied dirs with --relative --backup, -b make backups (see --suffix & --backup-dir) --backup-dir=DIR make backups into hierarchy based in DIR --suffix=SUFFIX backup suffix (default ~ w/o --backup-dir) --update, -u skip files that are newer on the receiver --inplace update destination files in-place --append append data onto shorter files --append-verify --append w/old data in file checksum --dirs, -d transfer directories without recursing --old-dirs, --old-d works like --dirs when talking to old rsync --mkpath create destination's missing path components --links, -l copy symlinks as symlinks --copy-links, -L transform symlink into referent file/dir --copy-unsafe-links only "unsafe" symlinks are transformed --safe-links ignore symlinks that point outside the tree --munge-links munge symlinks to make them safe & unusable --copy-dirlinks, -k transform symlink to dir into referent dir --keep-dirlinks, -K treat symlinked dir on receiver as dir --hard-links, -H preserve hard links --perms, -p preserve permissions --executability, -E preserve executability --chmod=CHMOD affect file and/or directory permissions --acls, -A preserve ACLs (implies --perms) --xattrs, -X preserve extended attributes --owner, -o preserve owner (super-user only) --group, -g preserve group --devices preserve device files (super-user only) --copy-devices copy device contents as a regular file --write-devices write to devices as files (implies --inplace) --specials preserve special files -D same as --devices --specials --times, -t preserve modification times --atimes, -U preserve access (use) times --open-noatime avoid changing the atime on opened files --crtimes, -N preserve create times (newness) --omit-dir-times, -O omit directories from --times --omit-link-times, -J omit symlinks from --times --super receiver attempts super-user activities --fake-super store/recover privileged attrs using xattrs --sparse, -S turn sequences of nulls into sparse blocks --preallocate allocate dest files before writing them --dry-run, -n perform a trial run with no changes made --whole-file, -W copy files whole (w/o delta-xfer algorithm) --checksum-choice=STR choose the checksum algorithm (aka --cc) --one-file-system, -x don't cross filesystem boundaries --block-size=SIZE, -B force a fixed checksum block-size --rsh=COMMAND, -e specify the remote shell to use --rsync-path=PROGRAM specify the rsync to run on remote machine --existing skip creating new files on receiver --ignore-existing skip updating files that exist on receiver --remove-source-files sender removes synchronized files (non-dir) --del an alias for --delete-during --delete delete extraneous files from dest dirs --delete-before receiver deletes before xfer, not during --delete-during receiver deletes during the transfer --delete-delay find deletions during, delete after --delete-after receiver deletes after transfer, not during --delete-excluded also delete excluded files from dest dirs --ignore-missing-args ignore missing source args without error --delete-missing-args delete missing source args from destination --ignore-errors delete even if there are I/O errors --force force deletion of dirs even if not empty --max-delete=NUM don't delete more than NUM files --max-size=SIZE don't transfer any file larger than SIZE --min-size=SIZE don't transfer any file smaller than SIZE --max-alloc=SIZE change a limit relating to memory alloc --partial keep partially transferred files --partial-dir=DIR put a partially transferred file into DIR --delay-updates put all updated files into place at end --prune-empty-dirs, -m prune empty directory chains from file-list --numeric-ids don't map uid/gid values by user/group name --usermap=STRING custom username mapping --groupmap=STRING custom groupname mapping --chown=USER:GROUP simple username/groupname mapping --timeout=SECONDS set I/O timeout in seconds --contimeout=SECONDS set daemon connection timeout in seconds --ignore-times, -I don't skip files that match size and time --size-only skip files that match in size --modify-window=NUM, -@ set the accuracy for mod-time comparisons --temp-dir=DIR, -T create temporary files in directory DIR --fuzzy, -y find similar file for basis if no dest file --compare-dest=DIR also compare destination files relative to DIR --copy-dest=DIR ... and include copies of unchanged files --link-dest=DIR hardlink to files in DIR when unchanged --compress, -z compress file data during the transfer --compress-choice=STR choose the compression algorithm (aka --zc) --compress-level=NUM explicitly set compression level (aka --zl) --skip-compress=LIST skip compressing files with suffix in LIST --cvs-exclude, -C auto-ignore files in the same way CVS does --filter=RULE, -f add a file-filtering RULE -F same as --filter='dir-merge /.rsync-filter' repeated: --filter='- .rsync-filter' --exclude=PATTERN exclude files matching PATTERN --exclude-from=FILE read exclude patterns from FILE --include=PATTERN don't exclude files matching PATTERN --include-from=FILE read include patterns from FILE --files-from=FILE read list of source-file names from FILE --from0, -0 all *-from/filter files are delimited by 0s --old-args disable the modern arg-protection idiom --secluded-args, -s use the protocol to safely send the args --trust-sender trust the remote sender's file list --copy-as=USER[:GROUP] specify user & optional group for the copy --address=ADDRESS bind address for outgoing socket to daemon --port=PORT specify double-colon alternate port number --sockopts=OPTIONS specify custom TCP options --blocking-io use blocking I/O for the remote shell --outbuf=N|L|B set out buffering to None, Line, or Block --stats give some file-transfer stats --8-bit-output, -8 leave high-bit chars unescaped in output --human-readable, -h output numbers in a human-readable format --progress show progress during transfer -P same as --partial --progress --itemize-changes, -i output a change-summary for all updates --remote-option=OPT, -M send OPTION to the remote side only --out-format=FORMAT output updates using the specified FORMAT --log-file=FILE log what we're doing to the specified FILE --log-file-format=FMT log updates using the specified FMT --password-file=FILE read daemon-access password from FILE --early-input=FILE use FILE for daemon's early exec input --list-only list the files instead of copying them --bwlimit=RATE limit socket I/O bandwidth --stop-after=MINS Stop rsync after MINS minutes have elapsed --stop-at=y-m-dTh:m Stop rsync at the specified point in time --fsync fsync every written file --write-batch=FILE write a batched update to FILE --only-write-batch=FILE like --write-batch but w/o updating dest --read-batch=FILE read a batched update from FILE --protocol=NUM force an older protocol version to be used --iconv=CONVERT_SPEC request charset conversion of filenames --checksum-seed=NUM set block/file checksum seed (advanced) --ipv4, -4 prefer IPv4 --ipv6, -6 prefer IPv6 --version, -V print the version + other info and exit --help, -h (*) show this help (* -h is help only on its own) Rsync can also be run as a daemon, in which case the following options are accepted: --daemon run as an rsync daemon --address=ADDRESS bind to the specified address --bwlimit=RATE limit socket I/O bandwidth --config=FILE specify alternate rsyncd.conf file --dparam=OVERRIDE, -M override global daemon config parameter --no-detach do not detach from the parent --port=PORT listen on alternate port number --log-file=FILE override the "log file" setting --log-file-format=FMT override the "log format" setting --sockopts=OPTIONS specify custom TCP options --verbose, -v increase verbosity --ipv4, -4 prefer IPv4 --ipv6, -6 prefer IPv6 --help, -h show this help (when used with --daemon) OPTIONS top Rsync accepts both long (double-dash + word) and short (single- dash + letter) options. The full list of the available options are described below. If an option can be specified in more than one way, the choices are comma-separated. Some options only have a long variant, not a short. If the option takes a parameter, the parameter is only listed after the long variant, even though it must also be specified for the short. When specifying a parameter, you can either use the form --option=param, --option param, -o=param, -o param, or -oparam (the latter choices assume that your option has a short variant). The parameter may need to be quoted in some manner for it to survive the shell's command-line parsing. Also keep in mind that a leading tilde (~) in a pathname is substituted by your shell, so make sure that you separate the option name from the pathname using a space if you want the local shell to expand it. --help Print a short help page describing the options available in rsync and exit. You can also use -h for --help when it is used without any other options (since it normally means --human-readable). --version, -V Print the rsync version plus other info and exit. When repeated, the information is output is a JSON format that is still fairly readable (client side only). The output includes a list of compiled-in capabilities, a list of optimizations, the default list of checksum algorithms, the default list of compression algorithms, the default list of daemon auth digests, a link to the rsync web site, and a few other items. --verbose, -v This option increases the amount of information you are given during the transfer. By default, rsync works silently. A single -v will give you information about what files are being transferred and a brief summary at the end. Two -v options will give you information on what files are being skipped and slightly more information at the end. More than two -v options should only be used if you are debugging rsync. The end-of-run summary tells you the number of bytes sent to the remote rsync (which is the receiving side on a local copy), the number of bytes received from the remote host, and the average bytes per second of the transferred data computed over the entire length of the rsync run. The second line shows the total size (in bytes), which is the sum of all the file sizes that rsync considered transferring. It also shows a "speedup" value, which is a ratio of the total file size divided by the sum of the sent and received bytes (which is really just a feel-good bigger-is-better number). Note that these byte values can be made more (or less) human-readable by using the --human-readable (or --no-human-readable) options. In a modern rsync, the -v option is equivalent to the setting of groups of --info and --debug options. You can choose to use these newer options in addition to, or in place of using --verbose, as any fine-grained settings override the implied settings of -v. Both --info and --debug have a way to ask for help that tells you exactly what flags are set for each increase in verbosity. However, do keep in mind that a daemon's "max verbosity" setting will limit how high of a level the various individual flags can be set on the daemon side. For instance, if the max is 2, then any info and/or debug flag that is set to a higher value than what would be set by -vv will be downgraded to the -vv level in the daemon's logging. --info=FLAGS This option lets you have fine-grained control over the information output you want to see. An individual flag name may be followed by a level number, with 0 meaning to silence that output, 1 being the default output level, and higher numbers increasing the output of that flag (for those that support higher levels). Use --info=help to see all the available flag names, what they output, and what flag names are added for each increase in the verbose level. Some examples: rsync -a --info=progress2 src/ dest/ rsync -avv --info=stats2,misc1,flist0 src/ dest/ Note that --info=name's output is affected by the --out- format and --itemize-changes (-i) options. See those options for more information on what is output and when. This option was added to 3.1.0, so an older rsync on the server side might reject your attempts at fine-grained control (if one or more flags needed to be send to the server and the server was too old to understand them). See also the "max verbosity" caveat above when dealing with a daemon. --debug=FLAGS This option lets you have fine-grained control over the debug output you want to see. An individual flag name may be followed by a level number, with 0 meaning to silence that output, 1 being the default output level, and higher numbers increasing the output of that flag (for those that support higher levels). Use --debug=help to see all the available flag names, what they output, and what flag names are added for each increase in the verbose level. Some examples: rsync -avvv --debug=none src/ dest/ rsync -avA --del --debug=del2,acl src/ dest/ Note that some debug messages will only be output when the --stderr=all option is specified, especially those pertaining to I/O and buffer debugging. Beginning in 3.2.0, this option is no longer auto- forwarded to the server side in order to allow you to specify different debug values for each side of the transfer, as well as to specify a new debug option that is only present in one of the rsync versions. If you want to duplicate the same option on both sides, using brace expansion is an easy way to save you some typing. This works in zsh and bash: rsync -aiv {-M,}--debug=del2 src/ dest/ --stderr=errors|all|client This option controls which processes output to stderr and if info messages are also changed to stderr. The mode strings can be abbreviated, so feel free to use a single letter value. The 3 possible choices are: o errors - (the default) causes all the rsync processes to send an error directly to stderr, even if the process is on the remote side of the transfer. Info messages are sent to the client side via the protocol stream. If stderr is not available (i.e. when directly connecting with a daemon via a socket) errors fall back to being sent via the protocol stream. o all - causes all rsync messages (info and error) to get written directly to stderr from all (possible) processes. This causes stderr to become line- buffered (instead of raw) and eliminates the ability to divide up the info and error messages by file handle. For those doing debugging or using several levels of verbosity, this option can help to avoid clogging up the transfer stream (which should prevent any chance of a deadlock bug hanging things up). It also allows --debug to enable some extra I/O related messages. o client - causes all rsync messages to be sent to the client side via the protocol stream. One client process outputs all messages, with errors on stderr and info messages on stdout. This was the default in older rsync versions, but can cause error delays when a lot of transfer data is ahead of the messages. If you're pushing files to an older rsync, you may want to use --stderr=all since that idiom has been around for several releases. This option was added in rsync 3.2.3. This version also began the forwarding of a non-default setting to the remote side, though rsync uses the backward-compatible options --msgs2stderr and --no-msgs2stderr to represent the all and client settings, respectively. A newer rsync will continue to accept these older option names to maintain compatibility. --quiet, -q This option decreases the amount of information you are given during the transfer, notably suppressing information messages from the remote server. This option is useful when invoking rsync from cron. --no-motd This option affects the information that is output by the client at the start of a daemon transfer. This suppresses the message-of-the-day (MOTD) text, but it also affects the list of modules that the daemon sends in response to the "rsync host::" request (due to a limitation in the rsync protocol), so omit this option if you want to request the list of modules from the daemon. --ignore-times, -I Normally rsync will skip any files that are already the same size and have the same modification timestamp. This option turns off this "quick check" behavior, causing all files to be updated. This option can be confusing compared to --ignore-existing and --ignore-non-existing in that that they cause rsync to transfer fewer files, while this option causes rsync to transfer more files. --size-only This modifies rsync's "quick check" algorithm for finding files that need to be transferred, changing it from the default of transferring files with either a changed size or a changed last-modified time to just looking for files that have changed in size. This is useful when starting to use rsync after using another mirroring system which may not preserve timestamps exactly. --modify-window=NUM, -@ When comparing two timestamps, rsync treats the timestamps as being equal if they differ by no more than the modify- window value. The default is 0, which matches just integer seconds. If you specify a negative value (and the receiver is at least version 3.1.3) then nanoseconds will also be taken into account. Specifying 1 is useful for copies to/from MS Windows FAT filesystems, because FAT represents times with a 2-second resolution (allowing times to differ from the original by up to 1 second). If you want all your transfers to default to comparing nanoseconds, you can create a ~/.popt file and put these lines in it: rsync alias -a -a@-1 rsync alias -t -t@-1 With that as the default, you'd need to specify --modify- window=0 (aka -@0) to override it and ignore nanoseconds, e.g. if you're copying between ext3 and ext4, or if the receiving rsync is older than 3.1.3. --checksum, -c This changes the way rsync checks if the files have been changed and are in need of a transfer. Without this option, rsync uses a "quick check" that (by default) checks if each file's size and time of last modification match between the sender and receiver. This option changes this to compare a 128-bit checksum for each file that has a matching size. Generating the checksums means that both sides will expend a lot of disk I/O reading all the data in the files in the transfer, so this can slow things down significantly (and this is prior to any reading that will be done to transfer changed files) The sending side generates its checksums while it is doing the file-system scan that builds the list of the available files. The receiver generates its checksums when it is scanning for changed files, and will checksum any file that has the same size as the corresponding sender's file: files with either a changed size or a changed checksum are selected for transfer. Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option's before- the-transfer "Does this file need to be updated?" check. The checksum used is auto-negotiated between the client and the server, but can be overridden using either the --checksum-choice (--cc) option or an environment variable that is discussed in that option's section. --archive, -a This is equivalent to -rlptgoD. It is a quick way of saying you want recursion and want to preserve almost everything. Be aware that it does not include preserving ACLs (-A), xattrs (-X), atimes (-U), crtimes (-N), nor the finding and preserving of hardlinks (-H). The only exception to the above equivalence is when --files-from is specified, in which case -r is not implied. --no-OPTION You may turn off one or more implied options by prefixing the option name with "no-". Not all positive options have a negated opposite, but a lot do, including those that can be used to disable an implied option (e.g. --no-D, --no- perms) or have different defaults in various circumstances (e.g. --no-whole-file, --no-blocking-io, --no-dirs). Every valid negated option accepts both the short and the long option name after the "no-" prefix (e.g. --no-R is the same as --no-relative). As an example, if you want to use --archive (-a) but don't want --owner (-o), instead of converting -a into -rlptgD, you can specify -a --no-o (aka --archive --no-owner). The order of the options is important: if you specify --no-r -a, the -r option would end up being turned on, the opposite of -a --no-r. Note also that the side-effects of the --files-from option are NOT positional, as it affects the default state of several options and slightly changes the meaning of -a (see the --files-from option for more details). --recursive, -r This tells rsync to copy directories recursively. See also --dirs (-d) for an option that allows the scanning of a single directory. See the --inc-recursive option for a discussion of the incremental recursion for creating the list of files to transfer. --inc-recursive, --i-r This option explicitly enables on incremental recursion when scanning for files, which is enabled by default when using the --recursive option and both sides of the transfer are running rsync 3.0.0 or newer. Incremental recursion uses much less memory than non- incremental, while also beginning the transfer more quickly (since it doesn't need to scan the entire transfer hierarchy before it starts transferring files). If no recursion is enabled in the source files, this option has no effect. Some options require rsync to know the full file list, so these options disable the incremental recursion mode. These include: o --delete-before (the old default of --delete) o --delete-after o --prune-empty-dirs o --delay-updates In order to make --delete compatible with incremental recursion, rsync 3.0.0 made --delete-during the default delete mode (which was first added in 2.6.4). One side-effect of incremental recursion is that any missing sub-directories inside a recursively-scanned directory are (by default) created prior to recursing into the sub-dirs. This earlier creation point (compared to a non-incremental recursion) allows rsync to then set the modify time of the finished directory right away (without having to delay that until a bunch of recursive copying has finished). However, these early directories don't yet have their completed mode, mtime, or ownership set -- they have more restrictive rights until the subdirectory's copying actually begins. This early-creation idiom can be avoided by using the --omit-dir-times option. Incremental recursion can be disabled using the --no-inc- recursive (--no-i-r) option. --no-inc-recursive, --no-i-r Disables the new incremental recursion algorithm of the --recursive option. This makes rsync scan the full file list before it begins to transfer files. See --inc- recursive for more info. --relative, -R Use relative paths. This means that the full path names specified on the command line are sent to the server rather than just the last parts of the filenames. This is particularly useful when you want to send several different directories at the same time. For example, if you used this command: rsync -av /foo/bar/baz.c remote:/tmp/ would create a file named baz.c in /tmp/ on the remote machine. If instead you used rsync -avR /foo/bar/baz.c remote:/tmp/ then a file named /tmp/foo/bar/baz.c would be created on the remote machine, preserving its full path. These extra path elements are called "implied directories" (i.e. the "foo" and the "foo/bar" directories in the above example). Beginning with rsync 3.0.0, rsync always sends these implied directories as real directories in the file list, even if a path element is really a symlink on the sending side. This prevents some really unexpected behaviors when copying the full path of a file that you didn't realize had a symlink in its path. If you want to duplicate a server-side symlink, include both the symlink via its path, and referent directory via its real path. If you're dealing with an older rsync on the sending side, you may need to use the --no-implied-dirs option. It is also possible to limit the amount of path information that is sent as implied directories for each path you specify. With a modern rsync on the sending side (beginning with 2.6.7), you can insert a dot and a slash into the source path, like this: rsync -avR /foo/./bar/baz.c remote:/tmp/ That would create /tmp/bar/baz.c on the remote machine. (Note that the dot must be followed by a slash, so "/foo/." would not be abbreviated.) For older rsync versions, you would need to use a chdir to limit the source path. For example, when pushing files: (cd /foo; rsync -avR bar/baz.c remote:/tmp/) (Note that the parens put the two commands into a sub- shell, so that the "cd" command doesn't remain in effect for future commands.) If you're pulling files from an older rsync, use this idiom (but only for a non-daemon transfer): rsync -avR --rsync-path="cd /foo; rsync" \ remote:bar/baz.c /tmp/ --no-implied-dirs This option affects the default behavior of the --relative option. When it is specified, the attributes of the implied directories from the source names are not included in the transfer. This means that the corresponding path elements on the destination system are left unchanged if they exist, and any missing implied directories are created with default attributes. This even allows these implied path elements to have big differences, such as being a symlink to a directory on the receiving side. For instance, if a command-line arg or a files-from entry told rsync to transfer the file "path/foo/file", the directories "path" and "path/foo" are implied when --relative is used. If "path/foo" is a symlink to "bar" on the destination system, the receiving rsync would ordinarily delete "path/foo", recreate it as a directory, and receive the file into the new directory. With --no- implied-dirs, the receiving rsync updates "path/foo/file" using the existing path elements, which means that the file ends up being created in "path/bar". Another way to accomplish this link preservation is to use the --keep- dirlinks option (which will also affect symlinks to directories in the rest of the transfer). When pulling files from an rsync older than 3.0.0, you may need to use this option if the sending side has a symlink in the path you request and you wish the implied directories to be transferred as normal directories. --backup, -b With this option, preexisting destination files are renamed as each file is transferred or deleted. You can control where the backup file goes and what (if any) suffix gets appended using the --backup-dir and --suffix options. If you don't specify --backup-dir: 1. the --omit-dir-times option will be forced on 2. the use of --delete (without --delete-excluded), causes rsync to add a "protect" filter-rule for the backup suffix to the end of all your existing filters that looks like this: -f "P *~". This rule prevents previously backed-up files from being deleted. Note that if you are supplying your own filter rules, you may need to manually insert your own exclude/protect rule somewhere higher up in the list so that it has a high enough priority to be effective (e.g. if your rules specify a trailing inclusion/exclusion of *, the auto- added rule would never be reached). --backup-dir=DIR This implies the --backup option, and tells rsync to store all backups in the specified directory on the receiving side. This can be used for incremental backups. You can additionally specify a backup suffix using the --suffix option (otherwise the files backed up in the specified directory will keep their original filenames). Note that if you specify a relative path, the backup directory will be relative to the destination directory, so you probably want to specify either an absolute path or a path that starts with "../". If an rsync daemon is the receiver, the backup dir cannot go outside the module's path hierarchy, so take extra care not to delete it or copy into it. --suffix=SUFFIX This option allows you to override the default backup suffix used with the --backup (-b) option. The default suffix is a ~ if no --backup-dir was specified, otherwise it is an empty string. --update, -u This forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. (If an existing destination file has a modification time equal to the source file's, it will be updated if the sizes are different.) Note that this does not affect the copying of dirs, symlinks, or other special files. Also, a difference of file format between the sender and receiver is always considered to be important enough for an update, no matter what date is on the objects. In other words, if the source has a directory where the destination has a file, the transfer would occur regardless of the timestamps. This option is a TRANSFER RULE, so don't expect any exclude side effects. A caution for those that choose to combine --inplace with --update: an interrupted transfer will leave behind a partial file on the receiving side that has a very recent modified time, so re-running the transfer will probably not continue the interrupted file. As such, it is usually best to avoid combining this with --inplace unless you have implemented manual steps to handle any interrupted in-progress files. --inplace This option changes how rsync transfers a file when its data needs to be updated: instead of the default method of creating a new copy of the file and moving it into place when it is complete, rsync instead writes the updated data directly to the destination file. This has several effects: o Hard links are not broken. This means the new data will be visible through other hard links to the destination file. Moreover, attempts to copy differing source files onto a multiply-linked destination file will result in a "tug of war" with the destination data changing back and forth. o In-use binaries cannot be updated (either the OS will prevent this from happening, or binaries that attempt to swap-in their data will misbehave or crash). o The file's data will be in an inconsistent state during the transfer and will be left that way if the transfer is interrupted or if an update fails. o A file that rsync cannot write to cannot be updated. While a super user can update any file, a normal user needs to be granted write permission for the open of the file for writing to be successful. o The efficiency of rsync's delta-transfer algorithm may be reduced if some data in the destination file is overwritten before it can be copied to a position later in the file. This does not apply if you use --backup, since rsync is smart enough to use the backup file as the basis file for the transfer. WARNING: you should not use this option to update files that are being accessed by others, so be careful when choosing to use this for a copy. This option is useful for transferring large files with block-based changes or appended data, and also on systems that are disk bound, not network bound. It can also help keep a copy-on-write filesystem snapshot from diverging the entire contents of a file that only has minor changes. The option implies --partial (since an interrupted transfer does not delete the file), but conflicts with --partial-dir and --delay-updates. Prior to rsync 2.6.4 --inplace was also incompatible with --compare-dest and --link-dest. --append This special copy mode only works to efficiently update files that are known to be growing larger where any existing content on the receiving side is also known to be the same as the content on the sender. The use of --append can be dangerous if you aren't 100% sure that all the files in the transfer are shared, growing files. You should thus use filter rules to ensure that you weed out any files that do not fit this criteria. Rsync updates these growing file in-place without verifying any of the existing content in the file (it only verifies the content that it is appending). Rsync skips any files that exist on the receiving side that are not shorter than the associated file on the sending side (which means that new files are transferred). It also skips any files whose size on the sending side gets shorter during the send negotiations (rsync warns about a "diminished" file when this happens). This does not interfere with the updating of a file's non- content attributes (e.g. permissions, ownership, etc.) when the file does not need to be transferred, nor does it affect the updating of any directories or non-regular files. --append-verify This special copy mode works like --append except that all the data in the file is included in the checksum verification (making it less efficient but also potentially safer). This option can be dangerous if you aren't 100% sure that all the files in the transfer are shared, growing files. See the --append option for more details. Note: prior to rsync 3.0.0, the --append option worked like --append-verify, so if you are interacting with an older rsync (or the transfer is using a protocol prior to 30), specifying either append option will initiate an --append-verify transfer. --dirs, -d Tell the sending side to include any directories that are encountered. Unlike --recursive, a directory's contents are not copied unless the directory name specified is "." or ends with a trailing slash (e.g. ".", "dir/.", "dir/", etc.). Without this option or the --recursive option, rsync will skip all directories it encounters (and output a message to that effect for each one). If you specify both --dirs and --recursive, --recursive takes precedence. The --dirs option is implied by the --files-from option or the --list-only option (including an implied --list-only usage) if --recursive wasn't specified (so that directories are seen in the listing). Specify --no-dirs (or --no-d) if you want to turn this off. There is also a backward-compatibility helper option, --old-dirs (--old-d) that tells rsync to use a hack of -r --exclude='/*/*' to get an older rsync to list a single directory without recursing. --mkpath Create all missing path components of the destination path. By default, rsync allows only the final component of the destination path to not exist, which is an attempt to help you to validate your destination path. With this option, rsync creates all the missing destination-path components, just as if mkdir -p $DEST_PATH had been run on the receiving side. When specifying a destination path, including a trailing slash ensures that the whole path is treated as directory names to be created, even when the file list has a single item. See the COPYING TO A DIFFERENT NAME section for full details on how rsync decides if a final destination-path component should be created as a directory or not. If you would like the newly-created destination dirs to match the dirs on the sending side, you should be using --relative (-R) instead of --mkpath. For instance, the following two commands result in the same destination tree, but only the second command ensures that the "some/extra/path" components match the dirs on the sending side: rsync -ai --mkpath host:some/extra/path/*.c some/extra/path/ rsync -aiR host:some/extra/path/*.c ./ --links, -l Add symlinks to the transferred files instead of noisily ignoring them with a "non-regular file" warning for each symlink encountered. You can alternately silence the warning by specifying --info=nonreg0. The default handling of symlinks is to recreate each symlink's unchanged value on the receiving side. See the SYMBOLIC LINKS section for multi-option info. --copy-links, -L The sender transforms each symlink encountered in the transfer into the referent item, following the symlink chain to the file or directory that it references. If a symlink chain is broken, an error is output and the file is dropped from the transfer. This option supersedes any other options that affect symlinks in the transfer, since there are no symlinks left in the transfer. This option does not change the handling of existing symlinks on the receiving side, unlike versions of rsync prior to 2.6.3 which had the side-effect of telling the receiving side to also follow symlinks. A modern rsync won't forward this option to a remote receiver (since only the sender needs to know about it), so this caveat should only affect someone using an rsync client older than 2.6.7 (which is when -L stopped being forwarded to the receiver). See the --keep-dirlinks (-K) if you need a symlink to a directory to be treated as a real directory on the receiving side. See the SYMBOLIC LINKS section for multi-option info. --copy-unsafe-links This tells rsync to copy the referent of symbolic links that point outside the copied tree. Absolute symlinks are also treated like ordinary files, and so are any symlinks in the source path itself when --relative is used. Note that the cut-off point is the top of the transfer, which is the part of the path that rsync isn't mentioning in the verbose output. If you copy "/src/subdir" to "/dest/" then the "subdir" directory is a name inside the transfer tree, not the top of the transfer (which is /src) so it is legal for created relative symlinks to refer to other names inside the /src and /dest directories. If you instead copy "/src/subdir/" (with a trailing slash) to "/dest/subdir" that would not allow symlinks to any files outside of "subdir". Note that safe symlinks are only copied if --links was also specified or implied. The --copy-unsafe-links option has no extra effect when combined with --copy-links. See the SYMBOLIC LINKS section for multi-option info. --safe-links This tells the receiving rsync to ignore any symbolic links in the transfer which point outside the copied tree. All absolute symlinks are also ignored. Since this ignoring is happening on the receiving side, it will still be effective even when the sending side has munged symlinks (when it is using --munge-links). It also affects deletions, since the file being present in the transfer prevents any matching file on the receiver from being deleted when the symlink is deemed to be unsafe and is skipped. This option must be combined with --links (or --archive) to have any symlinks in the transfer to conditionally ignore. Its effect is superseded by --copy-unsafe-links. Using this option in conjunction with --relative may give unexpected results. See the SYMBOLIC LINKS section for multi-option info. --munge-links This option affects just one side of the transfer and tells rsync to munge symlink values when it is receiving files or unmunge symlink values when it is sending files. The munged values make the symlinks unusable on disk but allows the original contents of the symlinks to be recovered. The server-side rsync often enables this option without the client's knowledge, such as in an rsync daemon's configuration file or by an option given to the rrsync (restricted rsync) script. When specified on the client side, specify the option normally if it is the client side that has/needs the munged symlinks, or use -M--munge-links to give the option to the server when it has/needs the munged symlinks. Note that on a local transfer, the client is the sender, so specifying the option directly unmunges symlinks while specifying it as a remote option munges symlinks. This option has no effect when sent to a daemon via --remote-option because the daemon configures whether it wants munged symlinks via its "munge symlinks" parameter. The symlink value is munged/unmunged once it is in the transfer, so any option that transforms symlinks into non- symlinks occurs prior to the munging/unmunging except for --safe-links, which is a choice that the receiver makes, so it bases its decision on the munged/unmunged value. This does mean that if a receiver has munging enabled, that using --safe-links will cause all symlinks to be ignored (since they are all absolute). The method that rsync uses to munge the symlinks is to prefix each one's value with the string "/rsyncd-munged/". This prevents the links from being used as long as the directory does not exist. When this option is enabled, rsync will refuse to run if that path is a directory or a symlink to a directory (though it only checks at startup). See also the "munge-symlinks" python script in the support directory of the source code for a way to munge/unmunge one or more symlinks in-place. --copy-dirlinks, -k This option causes the sending side to treat a symlink to a directory as though it were a real directory. This is useful if you don't want symlinks to non-directories to be affected, as they would be using --copy-links. Without this option, if the sending side has replaced a directory with a symlink to a directory, the receiving side will delete anything that is in the way of the new symlink, including a directory hierarchy (as long as --force or --delete is in effect). See also --keep-dirlinks for an analogous option for the receiving side. --copy-dirlinks applies to all symlinks to directories in the source. If you want to follow only a few specified symlinks, a trick you can use is to pass them as additional source args with a trailing slash, using --relative to make the paths match up right. For example: rsync -r --relative src/./ src/./follow-me/ dest/ This works because rsync calls lstat(2) on the source arg as given, and the trailing slash makes lstat(2) follow the symlink, giving rise to a directory in the file-list which overrides the symlink found during the scan of "src/./". See the SYMBOLIC LINKS section for multi-option info. --keep-dirlinks, -K This option causes the receiving side to treat a symlink to a directory as though it were a real directory, but only if it matches a real directory from the sender. Without this option, the receiver's symlink would be deleted and replaced with a real directory. For example, suppose you transfer a directory "foo" that contains a file "file", but "foo" is a symlink to directory "bar" on the receiver. Without --keep-dirlinks, the receiver deletes symlink "foo", recreates it as a directory, and receives the file into the new directory. With --keep-dirlinks, the receiver keeps the symlink and "file" ends up in "bar". One note of caution: if you use --keep-dirlinks, you must trust all the symlinks in the copy or enable the --munge- links option on the receiving side! If it is possible for an untrusted user to create their own symlink to any real directory, the user could then (on a subsequent copy) replace the symlink with a real directory and affect the content of whatever directory the symlink references. For backup copies, you are better off using something like a bind mount instead of a symlink to modify your receiving hierarchy. See also --copy-dirlinks for an analogous option for the sending side. See the SYMBOLIC LINKS section for multi-option info. --hard-links, -H This tells rsync to look for hard-linked files in the source and link together the corresponding files on the destination. Without this option, hard-linked files in the source are treated as though they were separate files. This option does NOT necessarily ensure that the pattern of hard links on the destination exactly matches that on the source. Cases in which the destination may end up with extra hard links include the following: o If the destination contains extraneous hard-links (more linking than what is present in the source file list), the copying algorithm will not break them explicitly. However, if one or more of the paths have content differences, the normal file- update process will break those extra links (unless you are using the --inplace option). o If you specify a --link-dest directory that contains hard links, the linking of the destination files against the --link-dest files can cause some paths in the destination to become linked together due to the --link-dest associations. Note that rsync can only detect hard links between files that are inside the transfer set. If rsync updates a file that has extra hard-link connections to files outside the transfer, that linkage will be broken. If you are tempted to use the --inplace option to avoid this breakage, be very careful that you know how your files are being updated so that you are certain that no unintended changes happen due to lingering hard links (and see the --inplace option for more caveats). If incremental recursion is active (see --inc-recursive), rsync may transfer a missing hard-linked file before it finds that another link for that contents exists elsewhere in the hierarchy. This does not affect the accuracy of the transfer (i.e. which files are hard-linked together), just its efficiency (i.e. copying the data for a new, early copy of a hard-linked file that could have been found later in the transfer in another member of the hard- linked set of files). One way to avoid this inefficiency is to disable incremental recursion using the --no-inc- recursive option. --perms, -p This option causes the receiving rsync to set the destination permissions to be the same as the source permissions. (See also the --chmod option for a way to modify what rsync considers to be the source permissions.) When this option is off, permissions are set as follows: o Existing files (including updated files) retain their existing permissions, though the --executability option might change just the execute permission for the file. o New files get their "normal" permission bits set to the source file's permissions masked with the receiving directory's default permissions (either the receiving process's umask, or the permissions specified via the destination directory's default ACL), and their special permission bits disabled except in the case where a new directory inherits a setgid bit from its parent directory. Thus, when --perms and --executability are both disabled, rsync's behavior is the same as that of other file-copy utilities, such as cp(1) and tar(1). In summary: to give destination files (both old and new) the source permissions, use --perms. To give new files the destination-default permissions (while leaving existing files unchanged), make sure that the --perms option is off and use --chmod=ugo=rwX (which ensures that all non-masked bits get enabled). If you'd care to make this latter behavior easier to type, you could define a popt alias for it, such as putting this line in the file ~/.popt (the following defines the -Z option, and includes --no-g to use the default group of the destination dir): rsync alias -Z --no-p --no-g --chmod=ugo=rwX You could then use this new option in a command such as this one: rsync -avZ src/ dest/ (Caveat: make sure that -a does not follow -Z, or it will re-enable the two --no-* options mentioned above.) The preservation of the destination's setgid bit on newly- created directories when --perms is off was added in rsync 2.6.7. Older rsync versions erroneously preserved the three special permission bits for newly-created files when --perms was off, while overriding the destination's setgid bit setting on a newly-created directory. Default ACL observance was added to the ACL patch for rsync 2.6.7, so older (or non-ACL-enabled) rsyncs use the umask even if default ACLs are present. (Keep in mind that it is the version of the receiving rsync that affects these behaviors.) --executability, -E This option causes rsync to preserve the executability (or non-executability) of regular files when --perms is not enabled. A regular file is considered to be executable if at least one 'x' is turned on in its permissions. When an existing destination file's executability differs from that of the corresponding source file, rsync modifies the destination file's permissions as follows: o To make a file non-executable, rsync turns off all its 'x' permissions. o To make a file executable, rsync turns on each 'x' permission that has a corresponding 'r' permission enabled. If --perms is enabled, this option is ignored. --acls, -A This option causes rsync to update the destination ACLs to be the same as the source ACLs. The option also implies --perms. The source and destination systems must have compatible ACL entries for this option to work properly. See the --fake-super option for a way to backup and restore ACLs that are not compatible. --xattrs, -X This option causes rsync to update the destination extended attributes to be the same as the source ones. For systems that support extended-attribute namespaces, a copy being done by a super-user copies all namespaces except system.*. A normal user only copies the user.* namespace. To be able to backup and restore non-user namespaces as a normal user, see the --fake-super option. The above name filtering can be overridden by using one or more filter options with the x modifier. When you specify an xattr-affecting filter rule, rsync requires that you do your own system/user filtering, as well as any additional filtering for what xattr names are copied and what names are allowed to be deleted. For example, to skip the system namespace, you could specify: --filter='-x system.*' To skip all namespaces except the user namespace, you could specify a negated-user match: --filter='-x! user.*' To prevent any attributes from being deleted, you could specify a receiver-only rule that excludes all names: --filter='-xr *' Note that the -X option does not copy rsync's special xattr values (e.g. those used by --fake-super) unless you repeat the option (e.g. -XX). This "copy all xattrs" mode cannot be used with --fake-super. --chmod=CHMOD This option tells rsync to apply one or more comma- separated "chmod" modes to the permission of the files in the transfer. The resulting value is treated as though it were the permissions that the sending side supplied for the file, which means that this option can seem to have no effect on existing files if --perms is not enabled. In addition to the normal parsing rules specified in the chmod(1) manpage, you can specify an item that should only apply to a directory by prefixing it with a 'D', or specify an item that should only apply to a file by prefixing it with a 'F'. For example, the following will ensure that all directories get marked set-gid, that no files are other-writable, that both are user-writable and group-writable, and that both have consistent executability across all bits: --chmod=Dg+s,ug+w,Fo-w,+X Using octal mode numbers is also allowed: --chmod=D2775,F664 It is also legal to specify multiple --chmod options, as each additional option is just appended to the list of changes to make. See the --perms and --executability options for how the resulting permission value can be applied to the files in the transfer. --owner, -o This option causes rsync to set the owner of the destination file to be the same as the source file, but only if the receiving rsync is being run as the super-user (see also the --super and --fake-super options). Without this option, the owner of new and/or transferred files are set to the invoking user on the receiving side. The preservation of ownership will associate matching names by default, but may fall back to using the ID number in some circumstances (see also the --numeric-ids option for a full discussion). --group, -g This option causes rsync to set the group of the destination file to be the same as the source file. If the receiving program is not running as the super-user (or if --no-super was specified), only groups that the invoking user on the receiving side is a member of will be preserved. Without this option, the group is set to the default group of the invoking user on the receiving side. The preservation of group information will associate matching names by default, but may fall back to using the ID number in some circumstances (see also the --numeric- ids option for a full discussion). --devices This option causes rsync to transfer character and block device files to the remote system to recreate these devices. If the receiving rsync is not being run as the super-user, rsync silently skips creating the device files (see also the --super and --fake-super options). By default, rsync generates a "non-regular file" warning for each device file encountered when this option is not set. You can silence the warning by specifying --info=nonreg0. --specials This option causes rsync to transfer special files, such as named sockets and fifos. If the receiving rsync is not being run as the super-user, rsync silently skips creating the special files (see also the --super and --fake-super options). By default, rsync generates a "non-regular file" warning for each special file encountered when this option is not set. You can silence the warning by specifying --info=nonreg0. -D The -D option is equivalent to "--devices --specials". --copy-devices This tells rsync to treat a device on the sending side as a regular file, allowing it to be copied to a normal destination file (or another device if --write-devices was also specified). This option is refused by default by an rsync daemon. --write-devices This tells rsync to treat a device on the receiving side as a regular file, allowing the writing of file data into a device. This option implies the --inplace option. Be careful using this, as you should know what devices are present on the receiving side of the transfer, especially when running rsync as root. This option is refused by default by an rsync daemon. --times, -t This tells rsync to transfer modification times along with the files and update them on the remote system. Note that if this option is not used, the optimization that excludes files that have not been modified cannot be effective; in other words, a missing -t (or -a) will cause the next transfer to behave as if it used --ignore-times (-I), causing all files to be updated (though rsync's delta- transfer algorithm will make the update fairly efficient if the files haven't actually changed, you're much better off using -t). A modern rsync that is using transfer protocol 30 or 31 conveys a modify time using up to 8-bytes. If rsync is forced to speak an older protocol (perhaps due to the remote rsync being older than 3.0.0) a modify time is conveyed using 4-bytes. Prior to 3.2.7, these shorter values could convey a date range of 13-Dec-1901 to 19-Jan-2038. Beginning with 3.2.7, these 4-byte values now convey a date range of 1-Jan-1970 to 7-Feb-2106. If you have files dated older than 1970, make sure your rsync executables are upgraded so that the full range of dates can be conveyed. --atimes, -U This tells rsync to set the access (use) times of the destination files to the same value as the source files. If repeated, it also sets the --open-noatime option, which can help you to make the sending and receiving systems have the same access times on the transferred files without needing to run rsync an extra time after a file is transferred. Note that some older rsync versions (prior to 3.2.0) may have been built with a pre-release --atimes patch that does not imply --open-noatime when this option is repeated. --open-noatime This tells rsync to open files with the O_NOATIME flag (on systems that support it) to avoid changing the access time of the files that are being transferred. If your OS does not support the O_NOATIME flag then rsync will silently ignore this option. Note also that some filesystems are mounted to avoid updating the atime on read access even without the O_NOATIME flag being set. --crtimes, -N, This tells rsync to set the create times (newness) of the destination files to the same value as the source files. --omit-dir-times, -O This tells rsync to omit directories when it is preserving modification, access, and create times. If NFS is sharing the directories on the receiving side, it is a good idea to use -O. This option is inferred if you use --backup without --backup-dir. This option also has the side-effect of avoiding early creation of missing sub-directories when incremental recursion is enabled, as discussed in the --inc-recursive section. --omit-link-times, -J This tells rsync to omit symlinks when it is preserving modification, access, and create times. --super This tells the receiving side to attempt super-user activities even if the receiving rsync wasn't run by the super-user. These activities include: preserving users via the --owner option, preserving all groups (not just the current user's groups) via the --group option, and copying devices via the --devices option. This is useful for systems that allow such activities without being the super-user, and also for ensuring that you will get errors if the receiving side isn't being run as the super-user. To turn off super-user activities, the super-user can use --no-super. --fake-super When this option is enabled, rsync simulates super-user activities by saving/restoring the privileged attributes via special extended attributes that are attached to each file (as needed). This includes the file's owner and group (if it is not the default), the file's device info (device & special files are created as empty text files), and any permission bits that we won't allow to be set on the real file (e.g. the real file gets u-s,g-s,o-t for safety) or that would limit the owner's access (since the real super-user can always access/change a file, the files we create can always be accessed/changed by the creating user). This option also handles ACLs (if --acls was specified) and non-user extended attributes (if --xattrs was specified). This is a good way to backup data without using a super- user, and to store ACLs from incompatible systems. The --fake-super option only affects the side where the option is used. To affect the remote side of a remote- shell connection, use the --remote-option (-M) option: rsync -av -M--fake-super /src/ host:/dest/ For a local copy, this option affects both the source and the destination. If you wish a local copy to enable this option just for the destination files, specify -M--fake- super. If you wish a local copy to enable this option just for the source files, combine --fake-super with -M--super. This option is overridden by both --super and --no-super. See also the fake super setting in the daemon's rsyncd.conf file. --sparse, -S Try to handle sparse files efficiently so they take up less space on the destination. If combined with --inplace the file created might not end up with sparse blocks with some combinations of kernel version and/or filesystem type. If --whole-file is in effect (e.g. for a local copy) then it will always work because rsync truncates the file prior to writing out the updated version. Note that versions of rsync older than 3.1.3 will reject the combination of --sparse and --inplace. --preallocate This tells the receiver to allocate each destination file to its eventual size before writing data to the file. Rsync will only use the real filesystem-level preallocation support provided by Linux's fallocate(2) system call or Cygwin's posix_fallocate(3), not the slow glibc implementation that writes a null byte into each block. Without this option, larger files may not be entirely contiguous on the filesystem, but with this option rsync will probably copy more slowly. If the destination is not an extent-supporting filesystem (such as ext4, xfs, NTFS, etc.), this option may have no positive effect at all. If combined with --sparse, the file will only have sparse blocks (as opposed to allocated sequences of null bytes) if the kernel version and filesystem type support creating holes in the allocated data. --dry-run, -n This makes rsync perform a trial run that doesn't make any changes (and produces mostly the same output as a real run). It is most commonly used in combination with the --verbose (-v) and/or --itemize-changes (-i) options to see what an rsync command is going to do before one actually runs it. The output of --itemize-changes is supposed to be exactly the same on a dry run and a subsequent real run (barring intentional trickery and system call failures); if it isn't, that's a bug. Other output should be mostly unchanged, but may differ in some areas. Notably, a dry run does not send the actual data for file transfers, so --progress has no effect, the "bytes sent", "bytes received", "literal data", and "matched data" statistics are too small, and the "speedup" value is equivalent to a run where no file transfers were needed. --whole-file, -W This option disables rsync's delta-transfer algorithm, which causes all transferred files to be sent whole. The transfer may be faster if this option is used when the bandwidth between the source and destination machines is higher than the bandwidth to disk (especially when the "disk" is actually a networked filesystem). This is the default when both the source and destination are specified as local paths, but only if no batch-writing option is in effect. --no-whole-file, --no-W Disable whole-file updating when it is enabled by default for a local transfer. This usually slows rsync down, but it can be useful if you are trying to minimize the writes to the destination file (if combined with --inplace) or for testing the checksum-based update algorithm. See also the --whole-file option. --checksum-choice=STR, --cc=STR This option overrides the checksum algorithms. If one algorithm name is specified, it is used for both the transfer checksums and (assuming --checksum is specified) the pre-transfer checksums. If two comma-separated names are supplied, the first name affects the transfer checksums, and the second name affects the pre-transfer checksums (-c). The checksum options that you may be able to use are: o auto (the default automatic choice) o xxh128 o xxh3 o xxh64 (aka xxhash) o md5 o md4 o sha1 o none Run rsync --version to see the default checksum list compiled into your version (which may differ from the list above). If "none" is specified for the first (or only) name, the --whole-file option is forced on and no checksum verification is performed on the transferred data. If "none" is specified for the second (or only) name, the --checksum option cannot be used. The "auto" option is the default, where rsync bases its algorithm choice on a negotiation between the client and the server as follows: When both sides of the transfer are at least 3.2.0, rsync chooses the first algorithm in the client's list of choices that is also in the server's list of choices. If no common checksum choice is found, rsync exits with an error. If the remote rsync is too old to support checksum negotiation, a value is chosen based on the protocol version (which chooses between MD5 and various flavors of MD4 based on protocol age). The default order can be customized by setting the environment variable RSYNC_CHECKSUM_LIST to a space- separated list of acceptable checksum names. If the string contains a "&" character, it is separated into the "client string & server string", otherwise the same string applies to both. If the string (or string portion) contains no non-whitespace characters, the default checksum list is used. This method does not allow you to specify the transfer checksum separately from the pre- transfer checksum, and it discards "auto" and all unknown checksum names. A list with only invalid names results in a failed negotiation. The use of the --checksum-choice option overrides this environment list. --one-file-system, -x This tells rsync to avoid crossing a filesystem boundary when recursing. This does not limit the user's ability to specify items to copy from multiple filesystems, just rsync's recursion through the hierarchy of each directory that the user specified, and also the analogous recursion on the receiving side during deletion. Also keep in mind that rsync treats a "bind" mount to the same device as being on the same filesystem. If this option is repeated, rsync omits all mount-point directories from the copy. Otherwise, it includes an empty directory at each mount-point it encounters (using the attributes of the mounted directory because those of the underlying mount-point directory are inaccessible). If rsync has been told to collapse symlinks (via --copy- links or --copy-unsafe-links), a symlink to a directory on another device is treated like a mount-point. Symlinks to non-directories are unaffected by this option. --ignore-non-existing, --existing This tells rsync to skip creating files (including directories) that do not exist yet on the destination. If this option is combined with the --ignore-existing option, no files will be updated (which can be useful if all you want to do is delete extraneous files). This option is a TRANSFER RULE, so don't expect any exclude side effects. --ignore-existing This tells rsync to skip updating files that already exist on the destination (this does not ignore existing directories, or nothing would get done). See also --ignore-non-existing. This option is a TRANSFER RULE, so don't expect any exclude side effects. This option can be useful for those doing backups using the --link-dest option when they need to continue a backup run that got interrupted. Since a --link-dest run is copied into a new directory hierarchy (when it is used properly), using [--ignore-existing will ensure that the already-handled files don't get tweaked (which avoids a change in permissions on the hard-linked files). This does mean that this option is only looking at the existing files in the destination hierarchy itself. When --info=skip2 is used rsync will output "FILENAME exists (INFO)" messages where the INFO indicates one of "type change", "sum change" (requires -c), "file change" (based on the quick check), "attr change", or "uptodate". Using --info=skip1 (which is also implied by 2 -v options) outputs the exists message without the INFO suffix. --remove-source-files This tells rsync to remove from the sending side the files (meaning non-directories) that are a part of the transfer and have been successfully duplicated on the receiving side. Note that you should only use this option on source files that are quiescent. If you are using this to move files that show up in a particular directory over to another host, make sure that the finished files get renamed into the source directory, not directly written into it, so that rsync can't possibly transfer a file that is not yet fully written. If you can't first write the files into a different directory, you should use a naming idiom that lets rsync avoid transferring files that are not yet finished (e.g. name the file "foo.new" when it is written, rename it to "foo" when it is done, and then use the option --exclude='*.new' for the rsync transfer). Starting with 3.1.0, rsync will skip the sender-side removal (and output an error) if the file's size or modify time has not stayed unchanged. Starting with 3.2.6, a local rsync copy will ensure that the sender does not remove a file the receiver just verified, such as when the user accidentally makes the source and destination directory the same path. --delete This tells rsync to delete extraneous files from the receiving side (ones that aren't on the sending side), but only for the directories that are being synchronized. You must have asked rsync to send the whole directory (e.g. "dir" or "dir/") without using a wildcard for the directory's contents (e.g. "dir/*") since the wildcard is expanded by the shell and rsync thus gets a request to transfer individual files, not the files' parent directory. Files that are excluded from the transfer are also excluded from being deleted unless you use the --delete-excluded option or mark the rules as only matching on the sending side (see the include/exclude modifiers in the FILTER RULES section). Prior to rsync 2.6.7, this option would have no effect unless --recursive was enabled. Beginning with 2.6.7, deletions will also occur when --dirs (-d) is enabled, but only for directories whose contents are being copied. This option can be dangerous if used incorrectly! It is a very good idea to first try a run using the --dry-run (-n) option to see what files are going to be deleted. If the sending side detects any I/O errors, then the deletion of any files at the destination will be automatically disabled. This is to prevent temporary filesystem failures (such as NFS errors) on the sending side from causing a massive deletion of files on the destination. You can override this with the --ignore- errors option. The --delete option may be combined with one of the --delete-WHEN options without conflict, as well as --delete-excluded. However, if none of the --delete-WHEN options are specified, rsync will choose the --delete- during algorithm when talking to rsync 3.0.0 or newer, or the --delete-before algorithm when talking to an older rsync. See also --delete-delay and --delete-after. --delete-before Request that the file-deletions on the receiving side be done before the transfer starts. See --delete (which is implied) for more details on file-deletion. Deleting before the transfer is helpful if the filesystem is tight for space and removing extraneous files would help to make the transfer possible. However, it does introduce a delay before the start of the transfer, and this delay might cause the transfer to timeout (if --timeout was specified). It also forces rsync to use the old, non-incremental recursion algorithm that requires rsync to scan all the files in the transfer into memory at once (see --recursive). --delete-during, --del Request that the file-deletions on the receiving side be done incrementally as the transfer happens. The per- directory delete scan is done right before each directory is checked for updates, so it behaves like a more efficient --delete-before, including doing the deletions prior to any per-directory filter files being updated. This option was first added in rsync version 2.6.4. See --delete (which is implied) for more details on file- deletion. --delete-delay Request that the file-deletions on the receiving side be computed during the transfer (like --delete-during), and then removed after the transfer completes. This is useful when combined with --delay-updates and/or --fuzzy, and is more efficient than using --delete-after (but can behave differently, since --delete-after computes the deletions in a separate pass after all updates are done). If the number of removed files overflows an internal buffer, a temporary file will be created on the receiving side to hold the names (it is removed while open, so you shouldn't see it during the transfer). If the creation of the temporary file fails, rsync will try to fall back to using --delete-after (which it cannot do if --recursive is doing an incremental scan). See --delete (which is implied) for more details on file-deletion. --delete-after Request that the file-deletions on the receiving side be done after the transfer has completed. This is useful if you are sending new per-directory merge files as a part of the transfer and you want their exclusions to take effect for the delete phase of the current transfer. It also forces rsync to use the old, non-incremental recursion algorithm that requires rsync to scan all the files in the transfer into memory at once (see --recursive). See --delete (which is implied) for more details on file- deletion. See also the --delete-delay option that might be a faster choice for those that just want the deletions to occur at the end of the transfer. --delete-excluded This option turns any unqualified exclude/include rules into server-side rules that do not affect the receiver's deletions. By default, an exclude or include has both a server-side effect (to "hide" and "show" files when building the server's file list) and a receiver-side effect (to "protect" and "risk" files when deletions are occurring). Any rule that has no modifier to specify what sides it is executed on will be instead treated as if it were a server-side rule only, avoiding any "protect" effects of the rules. A rule can still apply to both sides even with this option specified if the rule is given both the sender & receiver modifier letters (e.g., -f'-sr foo'). Receiver-side protect/risk rules can also be explicitly specified to limit the deletions. This saves you from having to edit a bunch of -f'- foo' rules into -f'-s foo' (aka -f'H foo') rules (not to mention the corresponding includes). See the FILTER RULES section for more information. See --delete (which is implied) for more details on deletion. --ignore-missing-args When rsync is first processing the explicitly requested source files (e.g. command-line arguments or --files-from entries), it is normally an error if the file cannot be found. This option suppresses that error, and does not try to transfer the file. This does not affect subsequent vanished-file errors if a file was initially found to be present and later is no longer there. --delete-missing-args This option takes the behavior of the (implied) --ignore- missing-args option a step farther: each missing arg will become a deletion request of the corresponding destination file on the receiving side (should it exist). If the destination file is a non-empty directory, it will only be successfully deleted if --force or --delete are in effect. Other than that, this option is independent of any other type of delete processing. The missing source files are represented by special file- list entries which display as a "*missing" entry in the --list-only output. --ignore-errors Tells --delete to go ahead and delete files even when there are I/O errors. --force This option tells rsync to delete a non-empty directory when it is to be replaced by a non-directory. This is only relevant if deletions are not active (see --delete for details). Note for older rsync versions: --force used to still be required when using --delete-after, and it used to be non- functional unless the --recursive option was also enabled. --max-delete=NUM This tells rsync not to delete more than NUM files or directories. If that limit is exceeded, all further deletions are skipped through the end of the transfer. At the end, rsync outputs a warning (including a count of the skipped deletions) and exits with an error code of 25 (unless some more important error condition also occurred). Beginning with version 3.0.0, you may specify --max- delete=0 to be warned about any extraneous files in the destination without removing any of them. Older clients interpreted this as "unlimited", so if you don't know what version the client is, you can use the less obvious --max- delete=-1 as a backward-compatible way to specify that no deletions be allowed (though really old versions didn't warn when the limit was exceeded). --max-size=SIZE This tells rsync to avoid transferring any file that is larger than the specified SIZE. A numeric value can be suffixed with a string to indicate the numeric units or left unqualified to specify bytes. Feel free to use a fractional value along with the units, such as --max- size=1.5m. This option is a TRANSFER RULE, so don't expect any exclude side effects. The first letter of a units string can be B (bytes), K (kilo), M (mega), G (giga), T (tera), or P (peta). If the string is a single char or has "ib" added to it (e.g. "G" or "GiB") then the units are multiples of 1024. If you use a two-letter suffix that ends with a "B" (e.g. "kb") then you get units that are multiples of 1000. The string's letters can be any mix of upper and lower-case that you want to use. Finally, if the string ends with either "+1" or "-1", it is offset by one byte in the indicated direction. The largest possible value is usually 8192P-1. Examples: --max-size=1.5mb-1 is 1499999 bytes, and --max- size=2g+1 is 2147483649 bytes. Note that rsync versions prior to 3.1.0 did not allow --max-size=0. --min-size=SIZE This tells rsync to avoid transferring any file that is smaller than the specified SIZE, which can help in not transferring small, junk files. See the --max-size option for a description of SIZE and other info. Note that rsync versions prior to 3.1.0 did not allow --min-size=0. --max-alloc=SIZE By default rsync limits an individual malloc/realloc to about 1GB in size. For most people this limit works just fine and prevents a protocol error causing rsync to request massive amounts of memory. However, if you have many millions of files in a transfer, a large amount of server memory, and you don't want to split up your transfer into multiple parts, you can increase the per- allocation limit to something larger and rsync will consume more memory. Keep in mind that this is not a limit on the total size of allocated memory. It is a sanity-check value for each individual allocation. See the --max-size option for a description of how SIZE can be specified. The default suffix if none is given is bytes. Beginning in 3.2.3, a value of 0 specifies no limit. You can set a default value using the environment variable RSYNC_MAX_ALLOC using the same SIZE values as supported by this option. If the remote rsync doesn't understand the --max-alloc option, you can override an environmental value by specifying --max-alloc=1g, which will make rsync avoid sending the option to the remote side (because "1G" is the default). --block-size=SIZE, -B This forces the block size used in rsync's delta-transfer algorithm to a fixed value. It is normally selected based on the size of each file being updated. See the technical report for details. Beginning in 3.2.3 the SIZE can be specified with a suffix as detailed in the --max-size option. Older versions only accepted a byte count. --rsh=COMMAND, -e This option allows you to choose an alternative remote shell program to use for communication between the local and remote copies of rsync. Typically, rsync is configured to use ssh by default, but you may prefer to use rsh on a local network. If this option is used with [user@]host::module/path, then the remote shell COMMAND will be used to run an rsync daemon on the remote host, and all data will be transmitted through that remote shell connection, rather than through a direct socket connection to a running rsync daemon on the remote host. See the USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION section above. Beginning with rsync 3.2.0, the RSYNC_PORT environment variable will be set when a daemon connection is being made via a remote-shell connection. It is set to 0 if the default daemon port is being assumed, or it is set to the value of the rsync port that was specified via either the --port option or a non-empty port value in an rsync:// URL. This allows the script to discern if a non-default port is being requested, allowing for things such as an SSL or stunnel helper script to connect to a default or alternate port. Command-line arguments are permitted in COMMAND provided that COMMAND is presented to rsync as a single argument. You must use spaces (not tabs or other whitespace) to separate the command and args from each other, and you can use single- and/or double-quotes to preserve spaces in an argument (but not backslashes). Note that doubling a single-quote inside a single-quoted string gives you a single-quote; likewise for double-quotes (though you need to pay attention to which quotes your shell is parsing and which quotes rsync is parsing). Some examples: -e 'ssh -p 2234' -e 'ssh -o "ProxyCommand nohup ssh firewall nc -w1 %h %p"' (Note that ssh users can alternately customize site- specific connect options in their .ssh/config file.) You can also choose the remote shell program using the RSYNC_RSH environment variable, which accepts the same range of values as -e. See also the --blocking-io option which is affected by this option. --rsync-path=PROGRAM Use this to specify what program is to be run on the remote machine to start-up rsync. Often used when rsync is not in the default remote-shell's path (e.g. --rsync- path=/usr/local/bin/rsync). Note that PROGRAM is run with the help of a shell, so it can be any program, script, or command sequence you'd care to run, so long as it does not corrupt the standard-in & standard-out that rsync is using to communicate. One tricky example is to set a different default directory on the remote machine for use with the --relative option. For instance: rsync -avR --rsync-path="cd /a/b && rsync" host:c/d /e/ --remote-option=OPTION, -M This option is used for more advanced situations where you want certain effects to be limited to one side of the transfer only. For instance, if you want to pass --log- file=FILE and --fake-super to the remote system, specify it like this: rsync -av -M --log-file=foo -M--fake-super src/ dest/ If you want to have an option affect only the local side of a transfer when it normally affects both sides, send its negation to the remote side. Like this: rsync -av -x -M--no-x src/ dest/ Be cautious using this, as it is possible to toggle an option that will cause rsync to have a different idea about what data to expect next over the socket, and that will make it fail in a cryptic fashion. Note that you should use a separate -M option for each remote option you want to pass. On older rsync versions, the presence of any spaces in the remote-option arg could cause it to be split into separate remote args, but this requires the use of --old-args in a modern rsync. When performing a local transfer, the "local" side is the sender and the "remote" side is the receiver. Note some versions of the popt option-parsing library have a bug in them that prevents you from using an adjacent arg with an equal in it next to a short option letter (e.g. -M--log-file=/tmp/foo). If this bug affects your version of popt, you can use the version of popt that is included with rsync. --cvs-exclude, -C This is a useful shorthand for excluding a broad range of files that you often don't want to transfer between systems. It uses a similar algorithm to CVS to determine if a file should be ignored. The exclude list is initialized to exclude the following items (these initial items are marked as perishable -- see the FILTER RULES section): RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS .make.state .nse_depinfo *~ #* .#* ,* _$* *$ *.old *.bak *.BAK *.orig *.rej .del-* *.a *.olb *.o *.obj *.so *.exe *.Z *.elc *.ln core .svn/ .git/ .hg/ .bzr/ then, files listed in a $HOME/.cvsignore are added to the list and any files listed in the CVSIGNORE environment variable (all cvsignore names are delimited by whitespace). Finally, any file is ignored if it is in the same directory as a .cvsignore file and matches one of the patterns listed therein. Unlike rsync's filter/exclude files, these patterns are split on whitespace. See the cvs(1) manual for more information. If you're combining -C with your own --filter rules, you should note that these CVS excludes are appended at the end of your own rules, regardless of where the -C was placed on the command-line. This makes them a lower priority than any rules you specified explicitly. If you want to control where these CVS excludes get inserted into your filter rules, you should omit the -C as a command- line option and use a combination of --filter=:C and --filter=-C (either on your command-line or by putting the ":C" and "-C" rules into a filter file with your other rules). The first option turns on the per-directory scanning for the .cvsignore file. The second option does a one-time import of the CVS excludes mentioned above. --filter=RULE, -f This option allows you to add rules to selectively exclude certain files from the list of files to be transferred. This is most useful in combination with a recursive transfer. You may use as many --filter options on the command line as you like to build up the list of files to exclude. If the filter contains whitespace, be sure to quote it so that the shell gives the rule to rsync as a single argument. The text below also mentions that you can use an underscore to replace the space that separates a rule from its arg. See the FILTER RULES section for detailed information on this option. -F The -F option is a shorthand for adding two --filter rules to your command. The first time it is used is a shorthand for this rule: --filter='dir-merge /.rsync-filter' This tells rsync to look for per-directory .rsync-filter files that have been sprinkled through the hierarchy and use their rules to filter the files in the transfer. If -F is repeated, it is a shorthand for this rule: --filter='exclude .rsync-filter' This filters out the .rsync-filter files themselves from the transfer. See the FILTER RULES section for detailed information on how these options work. --exclude=PATTERN This option is a simplified form of the --filter option that specifies an exclude rule and does not allow the full rule-parsing syntax of normal filter rules. This is equivalent to specifying -f'- PATTERN'. See the FILTER RULES section for detailed information on this option. --exclude-from=FILE This option is related to the --exclude option, but it specifies a FILE that contains exclude patterns (one per line). Blank lines in the file are ignored, as are whole- line comments that start with ';' or '#' (filename rules that contain those characters are unaffected). If a line begins with "- " (dash, space) or "+ " (plus, space), then the type of rule is being explicitly specified as an exclude or an include (respectively). Any rules without such a prefix are taken to be an exclude. If a line consists of just "!", then the current filter rules are cleared before adding any further rules. If FILE is '-', the list will be read from standard input. --include=PATTERN This option is a simplified form of the --filter option that specifies an include rule and does not allow the full rule-parsing syntax of normal filter rules. This is equivalent to specifying -f'+ PATTERN'. See the FILTER RULES section for detailed information on this option. --include-from=FILE This option is related to the --include option, but it specifies a FILE that contains include patterns (one per line). Blank lines in the file are ignored, as are whole- line comments that start with ';' or '#' (filename rules that contain those characters are unaffected). If a line begins with "- " (dash, space) or "+ " (plus, space), then the type of rule is being explicitly specified as an exclude or an include (respectively). Any rules without such a prefix are taken to be an include. If a line consists of just "!", then the current filter rules are cleared before adding any further rules. If FILE is '-', the list will be read from standard input. --files-from=FILE Using this option allows you to specify the exact list of files to transfer (as read from the specified FILE or '-' for standard input). It also tweaks the default behavior of rsync to make transferring just the specified files and directories easier: o The --relative (-R) option is implied, which preserves the path information that is specified for each item in the file (use --no-relative or --no-R if you want to turn that off). o The --dirs (-d) option is implied, which will create directories specified in the list on the destination rather than noisily skipping them (use --no-dirs or --no-d if you want to turn that off). o The --archive (-a) option's behavior does not imply --recursive (-r), so specify it explicitly, if you want it. o These side-effects change the default state of rsync, so the position of the --files-from option on the command-line has no bearing on how other options are parsed (e.g. -a works the same before or after --files-from, as does --no-R and all other options). The filenames that are read from the FILE are all relative to the source dir -- any leading slashes are removed and no ".." references are allowed to go higher than the source dir. For example, take this command: rsync -a --files-from=/tmp/foo /usr remote:/backup If /tmp/foo contains the string "bin" (or even "/bin"), the /usr/bin directory will be created as /backup/bin on the remote host. If it contains "bin/" (note the trailing slash), the immediate contents of the directory would also be sent (without needing to be explicitly mentioned in the file -- this began in version 2.6.4). In both cases, if the -r option was enabled, that dir's entire hierarchy would also be transferred (keep in mind that -r needs to be specified explicitly with --files-from, since it is not implied by -a. Also note that the effect of the (enabled by default) -r option is to duplicate only the path info that is read from the file -- it does not force the duplication of the source-spec path (/usr in this case). In addition, the --files-from file can be read from the remote host instead of the local host if you specify a "host:" in front of the file (the host must match one end of the transfer). As a short-cut, you can specify just a prefix of ":" to mean "use the remote end of the transfer". For example: rsync -a --files-from=:/path/file-list src:/ /tmp/copy This would copy all the files specified in the /path/file- list file that was located on the remote "src" host. If the --iconv and --secluded-args options are specified and the --files-from filenames are being sent from one host to another, the filenames will be translated from the sending host's charset to the receiving host's charset. NOTE: sorting the list of files in the --files-from input helps rsync to be more efficient, as it will avoid re- visiting the path elements that are shared between adjacent entries. If the input is not sorted, some path elements (implied directories) may end up being scanned multiple times, and rsync will eventually unduplicate them after they get turned into file-list elements. --from0, -0 This tells rsync that the rules/filenames it reads from a file are terminated by a null ('\0') character, not a NL, CR, or CR+LF. This affects --exclude-from, --include- from, --files-from, and any merged files specified in a --filter rule. It does not affect --cvs-exclude (since all names read from a .cvsignore file are split on whitespace). --old-args This option tells rsync to stop trying to protect the arg values on the remote side from unintended word-splitting or other misinterpretation. It also allows the client to treat an empty arg as a "." instead of generating an error. The default in a modern rsync is for "shell-active" characters (including spaces) to be backslash-escaped in the args that are sent to the remote shell. The wildcard characters *, ?, [, & ] are not escaped in filename args (allowing them to expand into multiple filenames) while being protected in option args, such as --usermap. If you have a script that wants to use old-style arg splitting in its filenames, specify this option once. If the remote shell has a problem with any backslash escapes at all, specify this option twice. You may also control this setting via the RSYNC_OLD_ARGS environment variable. If it has the value "1", rsync will default to a single-option setting. If it has the value "2" (or more), rsync will default to a repeated-option setting. If it is "0", you'll get the default escaping behavior. The environment is always overridden by manually specified positive or negative options (the negative is --no-old-args). Note that this option also disables the extra safety check added in 3.2.5 that ensures that a remote sender isn't including extra top-level items in the file-list that you didn't request. This side-effect is necessary because we can't know for sure what names to expect when the remote shell is interpreting the args. This option conflicts with the --secluded-args option. --secluded-args, -s This option sends all filenames and most options to the remote rsync via the protocol (not the remote shell command line) which avoids letting the remote shell modify them. Wildcards are expanded on the remote host by rsync instead of a shell. This is similar to the default backslash-escaping of args that was added in 3.2.4 (see --old-args) in that it prevents things like space splitting and unwanted special- character side-effects. However, it has the drawbacks of being incompatible with older rsync versions (prior to 3.0.0) and of being refused by restricted shells that want to be able to inspect all the option values for safety. This option is useful for those times that you need the argument's character set to be converted for the remote host, if the remote shell is incompatible with the default backslash-escpaing method, or there is some other reason that you want the majority of the options and arguments to bypass the command-line of the remote shell. If you combine this option with --iconv, the args related to the remote side will be translated from the local to the remote character-set. The translation happens before wild-cards are expanded. See also the --files-from option. You may also control this setting via the RSYNC_PROTECT_ARGS environment variable. If it has a non- zero value, this setting will be enabled by default, otherwise it will be disabled by default. Either state is overridden by a manually specified positive or negative version of this option (note that --no-s and --no- secluded-args are the negative versions). This environment variable is also superseded by a non-zero RSYNC_OLD_ARGS export. This option conflicts with the --old-args option. This option used to be called --protect-args (before 3.2.6) and that older name can still be used (though specifying it as -s is always the easiest and most compatible choice). --trust-sender This option disables two extra validation checks that a local client performs on the file list generated by a remote sender. This option should only be used if you trust the sender to not put something malicious in the file list (something that could possibly be done via a modified rsync, a modified shell, or some other similar manipulation). Normally, the rsync client (as of version 3.2.5) runs two extra validation checks when pulling files from a remote rsync: o It verifies that additional arg items didn't get added at the top of the transfer. o It verifies that none of the items in the file list are names that should have been excluded (if filter rules were specified). Note that various options can turn off one or both of these checks if the option interferes with the validation. For instance: o Using a per-directory filter file reads filter rules that only the server knows about, so the filter checking is disabled. o Using the --old-args option allows the sender to manipulate the requested args, so the arg checking is disabled. o Reading the files-from list from the server side means that the client doesn't know the arg list, so the arg checking is disabled. o Using --read-batch disables both checks since the batch file's contents will have been verified when it was created. This option may help an under-powered client server if the extra pattern matching is slowing things down on a huge transfer. It can also be used to work around a currently- unknown bug in the verification logic for a transfer from a trusted sender. When using this option it is a good idea to specify a dedicated destination directory, as discussed in the MULTI-HOST SECURITY section. --copy-as=USER[:GROUP] This option instructs rsync to use the USER and (if specified after a colon) the GROUP for the copy operations. This only works if the user that is running rsync has the ability to change users. If the group is not specified then the user's default groups are used. This option can help to reduce the risk of an rsync being run as root into or out of a directory that might have live changes happening to it and you want to make sure that root-level read or write actions of system files are not possible. While you could alternatively run all of rsync as the specified user, sometimes you need the root- level host-access credentials to be used, so this allows rsync to drop root for the copying part of the operation after the remote-shell or daemon connection is established. The option only affects one side of the transfer unless the transfer is local, in which case it affects both sides. Use the --remote-option to affect the remote side, such as -M--copy-as=joe. For a local transfer, the lsh (or lsh.sh) support file provides a local-shell helper script that can be used to allow a "localhost:" or "lh:" host-spec to be specified without needing to setup any remote shells, allowing you to specify remote options that affect the side of the transfer that is using the host- spec (and using hostname "lh" avoids the overriding of the remote directory to the user's home dir). For example, the following rsync writes the local files as user "joe": sudo rsync -aiv --copy-as=joe host1:backups/joe/ /home/joe/ This makes all files owned by user "joe", limits the groups to those that are available to that user, and makes it impossible for the joe user to do a timed exploit of the path to induce a change to a file that the joe user has no permissions to change. The following command does a local copy into the "dest/" dir as user "joe" (assuming you've installed support/lsh into a dir on your $PATH): sudo rsync -aive lsh -M--copy-as=joe src/ lh:dest/ --temp-dir=DIR, -T This option instructs rsync to use DIR as a scratch directory when creating temporary copies of the files transferred on the receiving side. The default behavior is to create each temporary file in the same directory as the associated destination file. Beginning with rsync 3.1.1, the temp-file names inside the specified DIR will not be prefixed with an extra dot (though they will still have a random suffix added). This option is most often used when the receiving disk partition does not have enough free space to hold a copy of the largest file in the transfer. In this case (i.e. when the scratch directory is on a different disk partition), rsync will not be able to rename each received temporary file over the top of the associated destination file, but instead must copy it into place. Rsync does this by copying the file over the top of the destination file, which means that the destination file will contain truncated data during this copy. If this were not done this way (even if the destination file were first removed, the data locally copied to a temporary file in the destination directory, and then renamed into place) it would be possible for the old file to continue taking up disk space (if someone had it open), and thus there might not be enough room to fit the new version on the disk at the same time. If you are using this option for reasons other than a shortage of disk space, you may wish to combine it with the --delay-updates option, which will ensure that all copied files get put into subdirectories in the destination hierarchy, awaiting the end of the transfer. If you don't have enough room to duplicate all the arriving files on the destination partition, another way to tell rsync that you aren't overly concerned about disk space is to use the --partial-dir option with a relative path; because this tells rsync that it is OK to stash off a copy of a single file in a subdir in the destination hierarchy, rsync will use the partial-dir as a staging area to bring over the copied file, and then rename it into place from there. (Specifying a --partial-dir with an absolute path does not have this side-effect.) --fuzzy, -y This option tells rsync that it should look for a basis file for any destination file that is missing. The current algorithm looks in the same directory as the destination file for either a file that has an identical size and modified-time, or a similarly-named file. If found, rsync uses the fuzzy basis file to try to speed up the transfer. If the option is repeated, the fuzzy scan will also be done in any matching alternate destination directories that are specified via --compare-dest, --copy-dest, or --link-dest. Note that the use of the --delete option might get rid of any potential fuzzy-match files, so either use --delete- after or specify some filename exclusions if you need to prevent this. --compare-dest=DIR This option instructs rsync to use DIR on the destination machine as an additional hierarchy to compare destination files against doing transfers (if the files are missing in the destination directory). If a file is found in DIR that is identical to the sender's file, the file will NOT be transferred to the destination directory. This is useful for creating a sparse backup of just files that have changed from an earlier backup. This option is typically used to copy into an empty (or newly created) directory. Beginning in version 2.6.4, multiple --compare-dest directories may be provided, which will cause rsync to search the list in the order specified for an exact match. If a match is found that differs only in attributes, a local copy is made and the attributes updated. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. If DIR is a relative path, it is relative to the destination directory. See also --copy-dest and --link- dest. NOTE: beginning with version 3.1.0, rsync will remove a file from a non-empty destination hierarchy if an exact match is found in one of the compare-dest hierarchies (making the end result more closely match a fresh copy). --copy-dest=DIR This option behaves like --compare-dest, but rsync will also copy unchanged files found in DIR to the destination directory using a local copy. This is useful for doing transfers to a new destination while leaving existing files intact, and then doing a flash-cutover when all files have been successfully transferred. Multiple --copy-dest directories may be provided, which will cause rsync to search the list in the order specified for an unchanged file. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. If DIR is a relative path, it is relative to the destination directory. See also --compare-dest and --link-dest. --link-dest=DIR This option behaves like --copy-dest, but unchanged files are hard linked from DIR to the destination directory. The files must be identical in all preserved attributes (e.g. permissions, possibly ownership) in order for the files to be linked together. An example: rsync -av --link-dest=$PWD/prior_dir host:src_dir/ new_dir/ If files aren't linking, double-check their attributes. Also check if some attributes are getting forced outside of rsync's control, such a mount option that squishes root to a single user, or mounts a removable drive with generic ownership (such as OS X's "Ignore ownership on this volume" option). Beginning in version 2.6.4, multiple --link-dest directories may be provided, which will cause rsync to search the list in the order specified for an exact match (there is a limit of 20 such directories). If a match is found that differs only in attributes, a local copy is made and the attributes updated. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. This option works best when copying into an empty destination hierarchy, as existing files may get their attributes tweaked, and that can affect alternate destination files via hard-links. Also, itemizing of changes can get a bit muddled. Note that prior to version 3.1.0, an alternate-directory exact match would never be found (nor linked into the destination) when a destination file already exists. Note that if you combine this option with --ignore-times, rsync will not link any files together because it only links identical files together as a substitute for transferring the file, never as an additional check after the file is updated. If DIR is a relative path, it is relative to the destination directory. See also --compare-dest and --copy-dest. Note that rsync versions prior to 2.6.1 had a bug that could prevent --link-dest from working properly for a non- super-user when --owner (-o) was specified (or implied). You can work-around this bug by avoiding the -o option (or using --no-o) when sending to an old rsync. --compress, -z With this option, rsync compresses the file data as it is sent to the destination machine, which reduces the amount of data being transmitted -- something that is useful over a slow connection. Rsync supports multiple compression methods and will choose one for you unless you force the choice using the --compress-choice (--zc) option. Run rsync --version to see the default compress list compiled into your version. When both sides of the transfer are at least 3.2.0, rsync chooses the first algorithm in the client's list of choices that is also in the server's list of choices. If no common compress choice is found, rsync exits with an error. If the remote rsync is too old to support checksum negotiation, its list is assumed to be "zlib". The default order can be customized by setting the environment variable RSYNC_COMPRESS_LIST to a space- separated list of acceptable compression names. If the string contains a "&" character, it is separated into the "client string & server string", otherwise the same string applies to both. If the string (or string portion) contains no non-whitespace characters, the default compress list is used. Any unknown compression names are discarded from the list, but a list with only invalid names results in a failed negotiation. There are some older rsync versions that were configured to reject a -z option and require the use of -zz because their compression library was not compatible with the default zlib compression method. You can usually ignore this weirdness unless the rsync server complains and tells you to specify -zz. --compress-choice=STR, --zc=STR This option can be used to override the automatic negotiation of the compression algorithm that occurs when --compress is used. The option implies --compress unless "none" was specified, which instead implies --no-compress. The compression options that you may be able to use are: o zstd o lz4 o zlibx o zlib o none Run rsync --version to see the default compress list compiled into your version (which may differ from the list above). Note that if you see an error about an option named --old- compress or --new-compress, this is rsync trying to send the --compress-choice=zlib or --compress-choice=zlibx option in a backward-compatible manner that more rsync versions understand. This error indicates that the older rsync version on the server will not allow you to force the compression type. Note that the "zlibx" compression algorithm is just the "zlib" algorithm with matched data excluded from the compression stream (to try to make it more compatible with an external zlib implementation). --compress-level=NUM, --zl=NUM Explicitly set the compression level to use (see --compress, -z) instead of letting it default. The --compress option is implied as long as the level chosen is not a "don't compress" level for the compression algorithm that is in effect (e.g. zlib compression treats level 0 as "off"). The level values vary depending on the checksum in effect. Because rsync will negotiate a checksum choice by default (when the remote rsync is new enough), it can be good to combine this option with a --compress-choice (--zc) option unless you're sure of the choice in effect. For example: rsync -aiv --zc=zstd --zl=22 host:src/ dest/ For zlib & zlibx compression the valid values are from 1 to 9 with 6 being the default. Specifying --zl=0 turns compression off, and specifying --zl=-1 chooses the default level of 6. For zstd compression the valid values are from -131072 to 22 with 3 being the default. Specifying 0 chooses the default of 3. For lz4 compression there are no levels, so the value is always 0. If you specify a too-large or too-small value, the number is silently limited to a valid value. This allows you to specify something like --zl=999999999 and be assured that you'll end up with the maximum compression level no matter what algorithm was chosen. If you want to know the compression level that is in effect, specify --debug=nstr to see the "negotiated string" results. This will report something like "Client compress: zstd (level 3)" (along with the checksum choice in effect). --skip-compress=LIST NOTE: no compression method currently supports per-file compression changes, so this option has no effect. Override the list of file suffixes that will be compressed as little as possible. Rsync sets the compression level on a per-file basis based on the file's suffix. If the compression algorithm has an "off" level, then no compression occurs for those files. Other algorithms that support changing the streaming level on-the-fly will have the level minimized to reduces the CPU usage as much as possible for a matching file. The LIST should be one or more file suffixes (without the dot) separated by slashes (/). You may specify an empty string to indicate that no files should be skipped. Simple character-class matching is supported: each must consist of a list of letters inside the square brackets (e.g. no special classes, such as "[:alpha:]", are supported, and '-' has no special meaning). The characters asterisk (*) and question-mark (?) have no special meaning. Here's an example that specifies 6 suffixes to skip (since 1 of the 5 rules matches 2 suffixes): --skip-compress=gz/jpg/mp[34]/7z/bz2 The default file suffixes in the skip-compress list in this version of rsync are: 3g2 3gp 7z aac ace apk avi bz2 deb dmg ear f4v flac flv gpg gz iso jar jpeg jpg lrz lz lz4 lzma lzo m1a m1v m2a m2ts m2v m4a m4b m4p m4r m4v mka mkv mov mp1 mp2 mp3 mp4 mpa mpeg mpg mpv mts odb odf odg odi odm odp ods odt oga ogg ogm ogv ogx opus otg oth otp ots ott oxt png qt rar rpm rz rzip spx squashfs sxc sxd sxg sxm sxw sz tbz tbz2 tgz tlz ts txz tzo vob war webm webp xz z zip zst This list will be replaced by your --skip-compress list in all but one situation: a copy from a daemon rsync will add your skipped suffixes to its list of non-compressing files (and its list may be configured to a different default). --numeric-ids With this option rsync will transfer numeric group and user IDs rather than using user and group names and mapping them at both ends. By default rsync will use the username and groupname to determine what ownership to give files. The special uid 0 and the special group 0 are never mapped via user/group names even if the --numeric-ids option is not specified. If a user or group has no name on the source system or it has no match on the destination system, then the numeric ID from the source system is used instead. See also the use chroot setting in the rsyncd.conf manpage for some comments on how the chroot setting affects rsync's ability to look up the names of the users and groups and what you can do about it. --usermap=STRING, --groupmap=STRING These options allow you to specify users and groups that should be mapped to other values by the receiving side. The STRING is one or more FROM:TO pairs of values separated by commas. Any matching FROM value from the sender is replaced with a TO value from the receiver. You may specify usernames or user IDs for the FROM and TO values, and the FROM value may also be a wild-card string, which will be matched against the sender's names (wild- cards do NOT match against ID numbers, though see below for why a '*' matches everything). You may instead specify a range of ID numbers via an inclusive range: LOW- HIGH. For example: --usermap=0-99:nobody,wayne:admin,*:normal --groupmap=usr:1,1:usr The first match in the list is the one that is used. You should specify all your user mappings using a single --usermap option, and/or all your group mappings using a single --groupmap option. Note that the sender's name for the 0 user and group are not transmitted to the receiver, so you should either match these values using a 0, or use the names in effect on the receiving side (typically "root"). All other FROM names match those in use on the sending side. All TO names match those in use on the receiving side. Any IDs that do not have a name on the sending side are treated as having an empty name for the purpose of matching. This allows them to be matched via a "*" or using an empty name. For instance: --usermap=:nobody --groupmap=*:nobody When the --numeric-ids option is used, the sender does not send any names, so all the IDs are treated as having an empty name. This means that you will need to specify numeric FROM values if you want to map these nameless IDs to different values. For the --usermap option to work, the receiver will need to be running as a super-user (see also the --super and --fake-super options). For the --groupmap option to work, the receiver will need to have permissions to set that group. Starting with rsync 3.2.4, the --usermap option implies the --owner (-o) option while the --groupmap option implies the --group (-g) option (since rsync needs to have those options enabled for the mapping options to work). An older rsync client may need to use -s to avoid a complaint about wildcard characters, but a modern rsync handles this automatically. --chown=USER:GROUP This option forces all files to be owned by USER with group GROUP. This is a simpler interface than using --usermap & --groupmap directly, but it is implemented using those options internally so they cannot be mixed. If either the USER or GROUP is empty, no mapping for the omitted user/group will occur. If GROUP is empty, the trailing colon may be omitted, but if USER is empty, a leading colon must be supplied. If you specify "--chown=foo:bar", this is exactly the same as specifying "--usermap=*:foo --groupmap=*:bar", only easier (and with the same implied --owner and/or --group options). An older rsync client may need to use -s to avoid a complaint about wildcard characters, but a modern rsync handles this automatically. --timeout=SECONDS This option allows you to set a maximum I/O timeout in seconds. If no data is transferred for the specified time then rsync will exit. The default is 0, which means no timeout. --contimeout=SECONDS This option allows you to set the amount of time that rsync will wait for its connection to an rsync daemon to succeed. If the timeout is reached, rsync exits with an error. --address=ADDRESS By default rsync will bind to the wildcard address when connecting to an rsync daemon. The --address option allows you to specify a specific IP address (or hostname) to bind to. See also the daemon version of the --address option. --port=PORT This specifies an alternate TCP port number to use rather than the default of 873. This is only needed if you are using the double-colon (::) syntax to connect with an rsync daemon (since the URL syntax has a way to specify the port as a part of the URL). See also the daemon version of the --port option. --sockopts=OPTIONS This option can provide endless fun for people who like to tune their systems to the utmost degree. You can set all sorts of socket options which may make transfers faster (or slower!). Read the manpage for the setsockopt() system call for details on some of the options you may be able to set. By default no special socket options are set. This only affects direct socket connections to a remote rsync daemon. See also the daemon version of the --sockopts option. --blocking-io This tells rsync to use blocking I/O when launching a remote shell transport. If the remote shell is either rsh or remsh, rsync defaults to using blocking I/O, otherwise it defaults to using non-blocking I/O. (Note that ssh prefers non-blocking I/O.) --outbuf=MODE This sets the output buffering mode. The mode can be None (aka Unbuffered), Line, or Block (aka Full). You may specify as little as a single letter for the mode, and use upper or lower case. The main use of this option is to change Full buffering to Line buffering when rsync's output is going to a file or pipe. --itemize-changes, -i Requests a simple itemized list of the changes that are being made to each file, including attribute changes. This is exactly the same as specifying --out- format='%i %n%L'. If you repeat the option, unchanged files will also be output, but only if the receiving rsync is at least version 2.6.7 (you can use -vv with older versions of rsync, but that also turns on the output of other verbose messages). The "%i" escape has a cryptic output that is 11 letters long. The general format is like the string YXcstpoguax, where Y is replaced by the type of update being done, X is replaced by the file-type, and the other letters represent attributes that may be output if they are being modified. The update types that replace the Y are as follows: o A < means that a file is being transferred to the remote host (sent). o A > means that a file is being transferred to the local host (received). o A c means that a local change/creation is occurring for the item (such as the creation of a directory or the changing of a symlink, etc.). o A h means that the item is a hard link to another item (requires --hard-links). o A . means that the item is not being updated (though it might have attributes that are being modified). o A * means that the rest of the itemized-output area contains a message (e.g. "deleting"). The file-types that replace the X are: f for a file, a d for a directory, an L for a symlink, a D for a device, and a S for a special file (e.g. named sockets and fifos). The other letters in the string indicate if some attributes of the file have changed, as follows: o "." - the attribute is unchanged. o "+" - the file is newly created. o " " - all the attributes are unchanged (all dots turn to spaces). o "?" - the change is unknown (when the remote rsync is old). o A letter indicates an attribute is being updated. The attribute that is associated with each letter is as follows: o A c means either that a regular file has a different checksum (requires --checksum) or that a symlink, device, or special file has a changed value. Note that if you are sending files to an rsync prior to 3.0.1, this change flag will be present only for checksum-differing regular files. o A s means the size of a regular file is different and will be updated by the file transfer. o A t means the modification time is different and is being updated to the sender's value (requires --times). An alternate value of T means that the modification time will be set to the transfer time, which happens when a file/symlink/device is updated without --times and when a symlink is changed and the receiver can't set its time. (Note: when using an rsync 3.0.0 client, you might see the s flag combined with t instead of the proper T flag for this time-setting failure.) o A p means the permissions are different and are being updated to the sender's value (requires --perms). o An o means the owner is different and is being updated to the sender's value (requires --owner and super-user privileges). o A g means the group is different and is being updated to the sender's value (requires --group and the authority to set the group). o o A u|n|b indicates the following information: u means the access (use) time is different and is being updated to the sender's value (requires --atimes) o n means the create time (newness) is different and is being updated to the sender's value (requires --crtimes) o b means that both the access and create times are being updated o The a means that the ACL information is being changed. o The x means that the extended attribute information is being changed. One other output is possible: when deleting files, the "%i" will output the string "*deleting" for each item that is being removed (assuming that you are talking to a recent enough rsync that it logs deletions instead of outputting them as a verbose message). --out-format=FORMAT This allows you to specify exactly what the rsync client outputs to the user on a per-update basis. The format is a text string containing embedded single-character escape sequences prefixed with a percent (%) character. A default format of "%n%L" is assumed if either --info=name or -v is specified (this tells you just the name of the file and, if the item is a link, where it points). For a full list of the possible escape characters, see the log format setting in the rsyncd.conf manpage. Specifying the --out-format option implies the --info=name option, which will mention each file, dir, etc. that gets updated in a significant way (a transferred file, a recreated symlink/device, or a touched directory). In addition, if the itemize-changes escape (%i) is included in the string (e.g. if the --itemize-changes option was used), the logging of names increases to mention any item that is changed in any way (as long as the receiving side is at least 2.6.4). See the --itemize-changes option for a description of the output of "%i". Rsync will output the out-format string prior to a file's transfer unless one of the transfer-statistic escapes is requested, in which case the logging is done at the end of the file's transfer. When this late logging is in effect and --progress is also specified, rsync will also output the name of the file being transferred prior to its progress information (followed, of course, by the out- format output). --log-file=FILE This option causes rsync to log what it is doing to a file. This is similar to the logging that a daemon does, but can be requested for the client side and/or the server side of a non-daemon transfer. If specified as a client option, transfer logging will be enabled with a default format of "%i %n%L". See the --log-file-format option if you wish to override this. Here's an example command that requests the remote side to log what is happening: rsync -av --remote-option=--log-file=/tmp/rlog src/ dest/ This is very useful if you need to debug why a connection is closing unexpectedly. See also the daemon version of the --log-file option. --log-file-format=FORMAT This allows you to specify exactly what per-update logging is put into the file specified by the --log-file option (which must also be specified for this option to have any effect). If you specify an empty string, updated files will not be mentioned in the log file. For a list of the possible escape characters, see the log format setting in the rsyncd.conf manpage. The default FORMAT used if --log-file is specified and this option is not is '%i %n%L'. See also the daemon version of the --log-file-format option. --stats This tells rsync to print a verbose set of statistics on the file transfer, allowing you to tell how effective rsync's delta-transfer algorithm is for your data. This option is equivalent to --info=stats2 if combined with 0 or 1 -v options, or --info=stats3 if combined with 2 or more -v options. The current statistics are as follows: o Number of files is the count of all "files" (in the generic sense), which includes directories, symlinks, etc. The total count will be followed by a list of counts by filetype (if the total is non- zero). For example: "(reg: 5, dir: 3, link: 2, dev: 1, special: 1)" lists the totals for regular files, directories, symlinks, devices, and special files. If any of value is 0, it is completely omitted from the list. o Number of created files is the count of how many "files" (generic sense) were created (as opposed to updated). The total count will be followed by a list of counts by filetype (if the total is non- zero). o Number of deleted files is the count of how many "files" (generic sense) were deleted. The total count will be followed by a list of counts by filetype (if the total is non-zero). Note that this line is only output if deletions are in effect, and only if protocol 31 is being used (the default for rsync 3.1.x). o Number of regular files transferred is the count of normal files that were updated via rsync's delta- transfer algorithm, which does not include dirs, symlinks, etc. Note that rsync 3.1.0 added the word "regular" into this heading. o Total file size is the total sum of all file sizes in the transfer. This does not count any size for directories or special files, but does include the size of symlinks. o Total transferred file size is the total sum of all files sizes for just the transferred files. o Literal data is how much unmatched file-update data we had to send to the receiver for it to recreate the updated files. o Matched data is how much data the receiver got locally when recreating the updated files. o File list size is how big the file-list data was when the sender sent it to the receiver. This is smaller than the in-memory size for the file list due to some compressing of duplicated data when rsync sends the list. o File list generation time is the number of seconds that the sender spent creating the file list. This requires a modern rsync on the sending side for this to be present. o File list transfer time is the number of seconds that the sender spent sending the file list to the receiver. o Total bytes sent is the count of all the bytes that rsync sent from the client side to the server side. o Total bytes received is the count of all non- message bytes that rsync received by the client side from the server side. "Non-message" bytes means that we don't count the bytes for a verbose message that the server sent to us, which makes the stats more consistent. --8-bit-output, -8 This tells rsync to leave all high-bit characters unescaped in the output instead of trying to test them to see if they're valid in the current locale and escaping the invalid ones. All control characters (but never tabs) are always escaped, regardless of this option's setting. The escape idiom that started in 2.6.7 is to output a literal backslash (\) and a hash (#), followed by exactly 3 octal digits. For example, a newline would output as "\#012". A literal backslash that is in a filename is not escaped unless it is followed by a hash and 3 digits (0-9). --human-readable, -h Output numbers in a more human-readable format. There are 3 possible levels: 1. output numbers with a separator between each set of 3 digits (either a comma or a period, depending on if the decimal point is represented by a period or a comma). 2. output numbers in units of 1000 (with a character suffix for larger units -- see below). 3. output numbers in units of 1024. The default is human-readable level 1. Each -h option increases the level by one. You can take the level down to 0 (to output numbers as pure digits) by specifying the --no-human-readable (--no-h) option. The unit letters that are appended in levels 2 and 3 are: K (kilo), M (mega), G (giga), T (tera), or P (peta). For example, a 1234567-byte file would output as 1.23M in level-2 (assuming that a period is your local decimal point). Backward compatibility note: versions of rsync prior to 3.1.0 do not support human-readable level 1, and they default to level 0. Thus, specifying one or two -h options will behave in a comparable manner in old and new versions as long as you didn't specify a --no-h option prior to one or more -h options. See the --list-only option for one difference. --partial By default, rsync will delete any partially transferred file if the transfer is interrupted. In some circumstances it is more desirable to keep partially transferred files. Using the --partial option tells rsync to keep the partial file which should make a subsequent transfer of the rest of the file much faster. --partial-dir=DIR This option modifies the behavior of the --partial option while also implying that it be enabled. This enhanced partial-file method puts any partially transferred files into the specified DIR instead of writing the partial file out to the destination file. On the next transfer, rsync will use a file found in this dir as data to speed up the resumption of the transfer and then delete it after it has served its purpose. Note that if --whole-file is specified (or implied), any partial-dir files that are found for a file that is being updated will simply be removed (since rsync is sending files without using rsync's delta-transfer algorithm). Rsync will create the DIR if it is missing, but just the last dir -- not the whole path. This makes it easy to use a relative path (such as "--partial-dir=.rsync-partial") to have rsync create the partial-directory in the destination file's directory when it is needed, and then remove it again when the partial file is deleted. Note that this directory removal is only done for a relative pathname, as it is expected that an absolute path is to a directory that is reserved for partial-dir work. If the partial-dir value is not an absolute path, rsync will add an exclude rule at the end of all your existing excludes. This will prevent the sending of any partial- dir files that may exist on the sending side, and will also prevent the untimely deletion of partial-dir items on the receiving side. An example: the above --partial-dir option would add the equivalent of this "perishable" exclude at the end of any other filter rules: -f '-p .rsync-partial/' If you are supplying your own exclude rules, you may need to add your own exclude/hide/protect rule for the partial- dir because: 1. the auto-added rule may be ineffective at the end of your other rules, or 2. you may wish to override rsync's exclude choice. For instance, if you want to make rsync clean-up any left- over partial-dirs that may be lying around, you should specify --delete-after and add a "risk" filter rule, e.g. -f 'R .rsync-partial/'. Avoid using --delete-before or --delete-during unless you don't need rsync to use any of the left-over partial-dir data during the current run. IMPORTANT: the --partial-dir should not be writable by other users or it is a security risk! E.g. AVOID "/tmp"! You can also set the partial-dir value the RSYNC_PARTIAL_DIR environment variable. Setting this in the environment does not force --partial to be enabled, but rather it affects where partial files go when --partial is specified. For instance, instead of using --partial-dir=.rsync-tmp along with --progress, you could set RSYNC_PARTIAL_DIR=.rsync-tmp in your environment and then use the -P option to turn on the use of the .rsync- tmp dir for partial transfers. The only times that the --partial option does not look for this environment value are: 1. when --inplace was specified (since --inplace conflicts with --partial-dir), and 2. when --delay-updates was specified (see below). When a modern rsync resumes the transfer of a file in the partial-dir, that partial file is now updated in-place instead of creating yet another tmp-file copy (so it maxes out at dest + tmp instead of dest + partial + tmp). This requires both ends of the transfer to be at least version 3.2.0. For the purposes of the daemon-config's "refuse options" setting, --partial-dir does not imply --partial. This is so that a refusal of the --partial option can be used to disallow the overwriting of destination files with a partial transfer, while still allowing the safer idiom provided by --partial-dir. --delay-updates This option puts the temporary file from each updated file into a holding directory until the end of the transfer, at which time all the files are renamed into place in rapid succession. This attempts to make the updating of the files a little more atomic. By default the files are placed into a directory named .~tmp~ in each file's destination directory, but if you've specified the --partial-dir option, that directory will be used instead. See the comments in the --partial-dir section for a discussion of how this .~tmp~ dir will be excluded from the transfer, and what you can do if you want rsync to cleanup old .~tmp~ dirs that might be lying around. Conflicts with --inplace and --append. This option implies --no-inc-recursive since it needs the full file list in memory in order to be able to iterate over it at the end. This option uses more memory on the receiving side (one bit per file transferred) and also requires enough free disk space on the receiving side to hold an additional copy of all the updated files. Note also that you should not use an absolute path to --partial-dir unless: 1. there is no chance of any of the files in the transfer having the same name (since all the updated files will be put into a single directory if the path is absolute), and 2. there are no mount points in the hierarchy (since the delayed updates will fail if they can't be renamed into place). See also the "atomic-rsync" python script in the "support" subdir for an update algorithm that is even more atomic (it uses --link-dest and a parallel hierarchy of files). --prune-empty-dirs, -m This option tells the receiving rsync to get rid of empty directories from the file-list, including nested directories that have no non-directory children. This is useful for avoiding the creation of a bunch of useless directories when the sending rsync is recursively scanning a hierarchy of files using include/exclude/filter rules. This option can still leave empty directories on the receiving side if you make use of TRANSFER_RULES. Because the file-list is actually being pruned, this option also affects what directories get deleted when a delete is active. However, keep in mind that excluded files and directories can prevent existing items from being deleted due to an exclude both hiding source files and protecting destination files. See the perishable filter-rule option for how to avoid this. You can prevent the pruning of certain empty directories from the file-list by using a global "protect" filter. For instance, this option would ensure that the directory "emptydir" was kept in the file-list: --filter 'protect emptydir/' Here's an example that copies all .pdf files in a hierarchy, only creating the necessary destination directories to hold the .pdf files, and ensures that any superfluous files and directories in the destination are removed (note the hide filter of non-directories being used instead of an exclude): rsync -avm --del --include='*.pdf' -f 'hide,! */' src/ dest If you didn't want to remove superfluous destination files, the more time-honored options of --include='*/' --exclude='*' would work fine in place of the hide-filter (if that is more natural to you). --progress This option tells rsync to print information showing the progress of the transfer. This gives a bored user something to watch. With a modern rsync this is the same as specifying --info=flist2,name,progress, but any user- supplied settings for those info flags takes precedence (e.g. --info=flist0 --progress). While rsync is transferring a regular file, it updates a progress line that looks like this: 782448 63% 110.64kB/s 0:00:04 In this example, the receiver has reconstructed 782448 bytes or 63% of the sender's file, which is being reconstructed at a rate of 110.64 kilobytes per second, and the transfer will finish in 4 seconds if the current rate is maintained until the end. These statistics can be misleading if rsync's delta- transfer algorithm is in use. For example, if the sender's file consists of the basis file followed by additional data, the reported rate will probably drop dramatically when the receiver gets to the literal data, and the transfer will probably take much longer to finish than the receiver estimated as it was finishing the matched part of the file. When the file transfer finishes, rsync replaces the progress line with a summary line that looks like this: 1,238,099 100% 146.38kB/s 0:00:08 (xfr#5, to-chk=169/396) In this example, the file was 1,238,099 bytes long in total, the average rate of transfer for the whole file was 146.38 kilobytes per second over the 8 seconds that it took to complete, it was the 5th transfer of a regular file during the current rsync session, and there are 169 more files for the receiver to check (to see if they are up-to-date or not) remaining out of the 396 total files in the file-list. In an incremental recursion scan, rsync won't know the total number of files in the file-list until it reaches the ends of the scan, but since it starts to transfer files during the scan, it will display a line with the text "ir-chk" (for incremental recursion check) instead of "to-chk" until the point that it knows the full size of the list, at which point it will switch to using "to-chk". Thus, seeing "ir-chk" lets you know that the total count of files in the file list is still going to increase (and each time it does, the count of files left to check will increase by the number of the files added to the list). -P The -P option is equivalent to "--partial --progress". Its purpose is to make it much easier to specify these two options for a long transfer that may be interrupted. There is also a --info=progress2 option that outputs statistics based on the whole transfer, rather than individual files. Use this flag without outputting a filename (e.g. avoid -v or specify --info=name0) if you want to see how the transfer is doing without scrolling the screen with a lot of names. (You don't need to specify the --progress option in order to use --info=progress2.) Finally, you can get an instant progress report by sending rsync a signal of either SIGINFO or SIGVTALRM. On BSD systems, a SIGINFO is generated by typing a Ctrl+T (Linux doesn't currently support a SIGINFO signal). When the client-side process receives one of those signals, it sets a flag to output a single progress report which is output when the current file transfer finishes (so it may take a little time if a big file is being handled when the signal arrives). A filename is output (if needed) followed by the --info=progress2 format of progress info. If you don't know which of the 3 rsync processes is the client process, it's OK to signal all of them (since the non- client processes ignore the signal). CAUTION: sending SIGVTALRM to an older rsync (pre-3.2.0) will kill it. --password-file=FILE This option allows you to provide a password for accessing an rsync daemon via a file or via standard input if FILE is -. The file should contain just the password on the first line (all other lines are ignored). Rsync will exit with an error if FILE is world readable or if a root-run rsync command finds a non-root-owned file. This option does not supply a password to a remote shell transport such as ssh; to learn how to do that, consult the remote shell's documentation. When accessing an rsync daemon using a remote shell as the transport, this option only comes into effect after the remote shell finishes its authentication (i.e. if you have also specified a password in the daemon's config file). --early-input=FILE This option allows rsync to send up to 5K of data to the "early exec" script on its stdin. One possible use of this data is to give the script a secret that can be used to mount an encrypted filesystem (which you should unmount in the the "post-xfer exec" script). The daemon must be at least version 3.2.1. --list-only This option will cause the source files to be listed instead of transferred. This option is inferred if there is a single source arg and no destination specified, so its main uses are: 1. to turn a copy command that includes a destination arg into a file-listing command, or 2. to be able to specify more than one source arg. Note: be sure to include the destination. CAUTION: keep in mind that a source arg with a wild-card is expanded by the shell into multiple args, so it is never safe to try to specify a single wild-card arg to try to infer this option. A safe example is: rsync -av --list-only foo* dest/ This option always uses an output format that looks similar to this: drwxrwxr-x 4,096 2022/09/30 12:53:11 support -rw-rw-r-- 80 2005/01/11 10:37:37 support/Makefile The only option that affects this output style is (as of 3.1.0) the --human-readable (-h) option. The default is to output sizes as byte counts with digit separators (in a 14-character-width column). Specifying at least one -h option makes the sizes output with unit suffixes. If you want old-style bytecount sizes without digit separators (and an 11-character-width column) use --no-h. Compatibility note: when requesting a remote listing of files from an rsync that is version 2.6.3 or older, you may encounter an error if you ask for a non-recursive listing. This is because a file listing implies the --dirs option w/o --recursive, and older rsyncs don't have that option. To avoid this problem, either specify the --no-dirs option (if you don't need to expand a directory's content), or turn on recursion and exclude the content of subdirectories: -r --exclude='/*/*'. --bwlimit=RATE This option allows you to specify the maximum transfer rate for the data sent over the socket, specified in units per second. The RATE value can be suffixed with a string to indicate a size multiplier, and may be a fractional value (e.g. --bwlimit=1.5m). If no suffix is specified, the value will be assumed to be in units of 1024 bytes (as if "K" or "KiB" had been appended). See the --max-size option for a description of all the available suffixes. A value of 0 specifies no limit. For backward-compatibility reasons, the rate limit will be rounded to the nearest KiB unit, so no rate smaller than 1024 bytes per second is possible. Rsync writes data over the socket in blocks, and this option both limits the size of the blocks that rsync writes, and tries to keep the average transfer rate at the requested limit. Some burstiness may be seen where rsync writes out a block of data and then sleeps to bring the average rate into compliance. Due to the internal buffering of data, the --progress option may not be an accurate reflection on how fast the data is being sent. This is because some files can show up as being rapidly sent when the data is quickly buffered, while other can show up as very slow when the flushing of the output buffer occurs. This may be fixed in a future version. See also the daemon version of the --bwlimit option. --stop-after=MINS, (--time-limit=MINS) This option tells rsync to stop copying when the specified number of minutes has elapsed. For maximal flexibility, rsync does not communicate this option to the remote rsync since it is usually enough that one side of the connection quits as specified. This allows the option's use even when only one side of the connection supports it. You can tell the remote side about the time limit using --remote-option (-M), should the need arise. The --time-limit version of this option is deprecated. --stop-at=y-m-dTh:m This option tells rsync to stop copying when the specified point in time has been reached. The date & time can be fully specified in a numeric format of year-month- dayThour:minute (e.g. 2000-12-31T23:59) in the local timezone. You may choose to separate the date numbers using slashes instead of dashes. The value can also be abbreviated in a variety of ways, such as specifying a 2-digit year and/or leaving off various values. In all cases, the value will be taken to be the next possible point in time where the supplied information matches. If the value specifies the current time or a past time, rsync exits with an error. For example, "1-30" specifies the next January 30th (at midnight local time), "14:00" specifies the next 2 P.M., "1" specifies the next 1st of the month at midnight, "31" specifies the next month where we can stop on its 31st day, and ":59" specifies the next 59th minute after the hour. For maximal flexibility, rsync does not communicate this option to the remote rsync since it is usually enough that one side of the connection quits as specified. This allows the option's use even when only one side of the connection supports it. You can tell the remote side about the time limit using --remote-option (-M), should the need arise. Do keep in mind that the remote host may have a different default timezone than your local host. --fsync Cause the receiving side to fsync each finished file. This may slow down the transfer, but can help to provide peace of mind when updating critical files. --write-batch=FILE Record a file that can later be applied to another identical destination with --read-batch. See the "BATCH MODE" section for details, and also the --only-write-batch option. This option overrides the negotiated checksum & compress lists and always negotiates a choice based on old-school md5/md4/zlib choices. If you want a more modern choice, use the --checksum-choice (--cc) and/or --compress-choice (--zc) options. --only-write-batch=FILE Works like --write-batch, except that no updates are made on the destination system when creating the batch. This lets you transport the changes to the destination system via some other means and then apply the changes via --read-batch. Note that you can feel free to write the batch directly to some portable media: if this media fills to capacity before the end of the transfer, you can just apply that partial transfer to the destination and repeat the whole process to get the rest of the changes (as long as you don't mind a partially updated destination system while the multi-update cycle is happening). Also note that you only save bandwidth when pushing changes to a remote system because this allows the batched data to be diverted from the sender into the batch file without having to flow over the wire to the receiver (when pulling, the sender is remote, and thus can't write the batch). --read-batch=FILE Apply all of the changes stored in FILE, a file previously generated by --write-batch. If FILE is -, the batch data will be read from standard input. See the "BATCH MODE" section for details. --protocol=NUM Force an older protocol version to be used. This is useful for creating a batch file that is compatible with an older version of rsync. For instance, if rsync 2.6.4 is being used with the --write-batch option, but rsync 2.6.3 is what will be used to run the --read-batch option, you should use "--protocol=28" when creating the batch file to force the older protocol version to be used in the batch file (assuming you can't upgrade the rsync on the reading system). --iconv=CONVERT_SPEC Rsync can convert filenames between character sets using this option. Using a CONVERT_SPEC of "." tells rsync to look up the default character-set via the locale setting. Alternately, you can fully specify what conversion to do by giving a local and a remote charset separated by a comma in the order --iconv=LOCAL,REMOTE, e.g. --iconv=utf8,iso88591. This order ensures that the option will stay the same whether you're pushing or pulling files. Finally, you can specify either --no-iconv or a CONVERT_SPEC of "-" to turn off any conversion. The default setting of this option is site-specific, and can also be affected via the RSYNC_ICONV environment variable. For a list of what charset names your local iconv library supports, you can run "iconv --list". If you specify the --secluded-args (-s) option, rsync will translate the filenames you specify on the command-line that are being sent to the remote host. See also the --files-from option. Note that rsync does not do any conversion of names in filter files (including include/exclude files). It is up to you to ensure that you're specifying matching rules that can match on both sides of the transfer. For instance, you can specify extra include/exclude rules if there are filename differences on the two sides that need to be accounted for. When you pass an --iconv option to an rsync daemon that allows it, the daemon uses the charset specified in its "charset" configuration parameter regardless of the remote charset you actually pass. Thus, you may feel free to specify just the local charset for a daemon transfer (e.g. --iconv=utf8). --ipv4, -4 or --ipv6, -6 Tells rsync to prefer IPv4/IPv6 when creating sockets or running ssh. This affects sockets that rsync has direct control over, such as the outgoing socket when directly contacting an rsync daemon, as well as the forwarding of the -4 or -6 option to ssh when rsync can deduce that ssh is being used as the remote shell. For other remote shells you'll need to specify the "--rsh SHELL -4" option directly (or whatever IPv4/IPv6 hint options it uses). See also the daemon version of these options. If rsync was compiled without support for IPv6, the --ipv6 option will have no effect. The rsync --version output will contain "no IPv6" if is the case. --checksum-seed=NUM Set the checksum seed to the integer NUM. This 4 byte checksum seed is included in each block and MD4 file checksum calculation (the more modern MD5 file checksums don't use a seed). By default the checksum seed is generated by the server and defaults to the current time(). This option is used to set a specific checksum seed, which is useful for applications that want repeatable block checksums, or in the case where the user wants a more random checksum seed. Setting NUM to 0 causes rsync to use the default of time() for checksum seed. DAEMON OPTIONS top The options allowed when starting an rsync daemon are as follows: --daemon This tells rsync that it is to run as a daemon. The daemon you start running may be accessed using an rsync client using the host::module or rsync://host/module/ syntax. If standard input is a socket then rsync will assume that it is being run via inetd, otherwise it will detach from the current terminal and become a background daemon. The daemon will read the config file (rsyncd.conf) on each connect made by a client and respond to requests accordingly. See the rsyncd.conf(5) manpage for more details. --address=ADDRESS By default rsync will bind to the wildcard address when run as a daemon with the --daemon option. The --address option allows you to specify a specific IP address (or hostname) to bind to. This makes virtual hosting possible in conjunction with the --config option. See also the address global option in the rsyncd.conf manpage and the client version of the --address option. --bwlimit=RATE This option allows you to specify the maximum transfer rate for the data the daemon sends over the socket. The client can still specify a smaller --bwlimit value, but no larger value will be allowed. See the client version of the --bwlimit option for some extra details. --config=FILE This specifies an alternate config file than the default. This is only relevant when --daemon is specified. The default is /etc/rsyncd.conf unless the daemon is running over a remote shell program and the remote user is not the super-user; in that case the default is rsyncd.conf in the current directory (typically $HOME). --dparam=OVERRIDE, -M This option can be used to set a daemon-config parameter when starting up rsync in daemon mode. It is equivalent to adding the parameter at the end of the global settings prior to the first module's definition. The parameter names can be specified without spaces, if you so desire. For instance: rsync --daemon -M pidfile=/path/rsync.pid --no-detach When running as a daemon, this option instructs rsync to not detach itself and become a background process. This option is required when running as a service on Cygwin, and may also be useful when rsync is supervised by a program such as daemontools or AIX's System Resource Controller. --no-detach is also recommended when rsync is run under a debugger. This option has no effect if rsync is run from inetd or sshd. --port=PORT This specifies an alternate TCP port number for the daemon to listen on rather than the default of 873. See also the client version of the --port option and the port global setting in the rsyncd.conf manpage. --log-file=FILE This option tells the rsync daemon to use the given log- file name instead of using the "log file" setting in the config file. See also the client version of the --log-file option. --log-file-format=FORMAT This option tells the rsync daemon to use the given FORMAT string instead of using the "log format" setting in the config file. It also enables "transfer logging" unless the string is empty, in which case transfer logging is turned off. See also the client version of the --log-file-format option. --sockopts This overrides the socket options setting in the rsyncd.conf file and has the same syntax. See also the client version of the --sockopts option. --verbose, -v This option increases the amount of information the daemon logs during its startup phase. After the client connects, the daemon's verbosity level will be controlled by the options that the client used and the "max verbosity" setting in the module's config section. See also the client version of the --verbose option. --ipv4, -4 or --ipv6, -6 Tells rsync to prefer IPv4/IPv6 when creating the incoming sockets that the rsync daemon will use to listen for connections. One of these options may be required in older versions of Linux to work around an IPv6 bug in the kernel (if you see an "address already in use" error when nothing else is using the port, try specifying --ipv6 or --ipv4 when starting the daemon). See also the client version of these options. If rsync was compiled without support for IPv6, the --ipv6 option will have no effect. The rsync --version output will contain "no IPv6" if is the case. --help, -h When specified after --daemon, print a short help page describing the options available for starting an rsync daemon. FILTER RULES top The filter rules allow for custom control of several aspects of how files are handled: o Control which files the sending side puts into the file list that describes the transfer hierarchy o Control which files the receiving side protects from deletion when the file is not in the sender's file list o Control which extended attribute names are skipped when copying xattrs The rules are either directly specified via option arguments or they can be read in from one or more files. The filter-rule files can even be a part of the hierarchy of files being copied, affecting different parts of the tree in different ways. SIMPLE INCLUDE/EXCLUDE RULES We will first cover the basics of how include & exclude rules affect what files are transferred, ignoring any deletion side- effects. Filter rules mainly affect the contents of directories that rsync is "recursing" into, but they can also affect a top- level item in the transfer that was specified as a argument. The default for any unmatched file/dir is for it to be included in the transfer, which puts the file/dir into the sender's file list. The use of an exclude rule causes one or more matching files/dirs to be left out of the sender's file list. An include rule can be used to limit the effect of an exclude rule that is matching too many files. The order of the rules is important because the first rule that matches is the one that takes effect. Thus, if an early rule excludes a file, no include rule that comes after it can have any effect. This means that you must place any include overrides somewhere prior to the exclude that it is intended to limit. When a directory is excluded, all its contents and sub-contents are also excluded. The sender doesn't scan through any of it at all, which can save a lot of time when skipping large unneeded sub-trees. It is also important to understand that the include/exclude rules are applied to every file and directory that the sender is recursing into. Thus, if you want a particular deep file to be included, you have to make sure that none of the directories that must be traversed on the way down to that file are excluded or else the file will never be discovered to be included. As an example, if the directory "a/path" was given as a transfer argument and you want to ensure that the file "a/path/down/deep/wanted.txt" is a part of the transfer, then the sender must not exclude the directories "a/path", "a/path/down", or "a/path/down/deep" as it makes it way scanning through the file tree. When you are working on the rules, it can be helpful to ask rsync to tell you what is being excluded/included and why. Specifying --debug=FILTER or (when pulling files) -M--debug=FILTER turns on level 1 of the FILTER debug information that will output a message any time that a file or directory is included or excluded and which rule it matched. Beginning in 3.2.4 it will also warn if a filter rule has trailing whitespace, since an exclude of "foo " (with a trailing space) will not exclude a file named "foo". Exclude and include rules can specify wildcard PATTERN MATCHING RULES (similar to shell wildcards) that allow you to match things like a file suffix or a portion of a filename. A rule can be limited to only affecting a directory by putting a trailing slash onto the filename. SIMPLE INCLUDE/EXCLUDE EXAMPLE With the following file tree created on the sending side: mkdir x/ touch x/file.txt mkdir x/y/ touch x/y/file.txt touch x/y/zzz.txt mkdir x/z/ touch x/z/file.txt Then the following rsync command will transfer the file "x/y/file.txt" and the directories needed to hold it, resulting in the path "/tmp/x/y/file.txt" existing on the remote host: rsync -ai -f'+ x/' -f'+ x/y/' -f'+ x/y/file.txt' -f'- *' x host:/tmp/ Aside: this copy could also have been accomplished using the -R option (though the 2 commands behave differently if deletions are enabled): rsync -aiR x/y/file.txt host:/tmp/ The following command does not need an include of the "x" directory because it is not a part of the transfer (note the traililng slash). Running this command would copy just "/tmp/x/file.txt" because the "y" and "z" dirs get excluded: rsync -ai -f'+ file.txt' -f'- *' x/ host:/tmp/x/ This command would omit the zzz.txt file while copying "x" and everything else it contains: rsync -ai -f'- zzz.txt' x host:/tmp/ FILTER RULES WHEN DELETING By default the include & exclude filter rules affect both the sender (as it creates its file list) and the receiver (as it creates its file lists for calculating deletions). If no delete option is in effect, the receiver skips creating the delete- related file lists. This two-sided default can be manually overridden so that you are only specifying sender rules or receiver rules, as described in the FILTER RULES IN DEPTH section. When deleting, an exclude protects a file from being removed on the receiving side while an include overrides that protection (putting the file at risk of deletion). The default is for a file to be at risk -- its safety depends on it matching a corresponding file from the sender. An example of the two-sided exclude effect can be illustrated by the copying of a C development directory between 2 systems. When doing a touch-up copy, you might want to skip copying the built executable and the .o files (sender hide) so that the receiving side can build their own and not lose any object files that are already correct (receiver protect). For instance: rsync -ai --del -f'- *.o' -f'- cmd' src host:/dest/ Note that using -f'-p *.o' is even better than -f'- *.o' if there is a chance that the directory structure may have changed. The "p" modifier is discussed in FILTER RULE MODIFIERS. One final note, if your shell doesn't mind unexpanded wildcards, you could simplify the typing of the filter options by using an underscore in place of the space and leaving off the quotes. For instance, -f -_*.o -f -_cmd (and similar) could be used instead of the filter options above. FILTER RULES IN DEPTH Rsync supports old-style include/exclude rules and new-style filter rules. The older rules are specified using --include and --exclude as well as the --include-from and --exclude-from. These are limited in behavior but they don't require a "-" or "+" prefix. An old-style exclude rule is turned into a "- name" filter rule (with no modifiers) and an old-style include rule is turned into a "+ name" filter rule (with no modifiers). Rsync builds an ordered list of filter rules as specified on the command-line and/or read-in from files. New style filter rules have the following syntax: RULE [PATTERN_OR_FILENAME] RULE,MODIFIERS [PATTERN_OR_FILENAME] You have your choice of using either short or long RULE names, as described below. If you use a short-named rule, the ',' separating the RULE from the MODIFIERS is optional. The PATTERN or FILENAME that follows (when present) must come after either a single space or an underscore (_). Any additional spaces and/or underscores are considered to be a part of the pattern name. Here are the available rule prefixes: exclude, '-' specifies an exclude pattern that (by default) is both a hide and a protect. include, '+' specifies an include pattern that (by default) is both a show and a risk. merge, '.' specifies a merge-file on the client side to read for more rules. dir-merge, ':' specifies a per-directory merge-file. Using this kind of filter rule requires that you trust the sending side's filter checking, so it has the side-effect mentioned under the --trust-sender option. hide, 'H' specifies a pattern for hiding files from the transfer. Equivalent to a sender-only exclude, so -f'H foo' could also be specified as -f'-s foo'. show, 'S' files that match the pattern are not hidden. Equivalent to a sender-only include, so -f'S foo' could also be specified as -f'+s foo'. protect, 'P' specifies a pattern for protecting files from deletion. Equivalent to a receiver-only exclude, so -f'P foo' could also be specified as -f'-r foo'. risk, 'R' files that match the pattern are not protected. Equivalent to a receiver-only include, so -f'R foo' could also be specified as -f'+r foo'. clear, '!' clears the current include/exclude list (takes no arg) When rules are being read from a file (using merge or dir-merge), empty lines are ignored, as are whole-line comments that start with a '#' (filename rules that contain a hash character are unaffected). Note also that the --filter, --include, and --exclude options take one rule/pattern each. To add multiple ones, you can repeat the options on the command-line, use the merge-file syntax of the --filter option, or the --include-from / --exclude-from options. PATTERN MATCHING RULES Most of the rules mentioned above take an argument that specifies what the rule should match. If rsync is recursing through a directory hierarchy, keep in mind that each pattern is matched against the name of every directory in the descent path as rsync finds the filenames to send. The matching rules for the pattern argument take several forms: o If a pattern contains a / (not counting a trailing slash) or a "**" (which can match a slash), then the pattern is matched against the full pathname, including any leading directories within the transfer. If the pattern doesn't contain a (non-trailing) / or a "**", then it is matched only against the final component of the filename or pathname. For example, foo means that the final path component must be "foo" while foo/bar would match the last 2 elements of the path (as long as both elements are within the transfer). o A pattern that ends with a / only matches a directory, not a regular file, symlink, or device. o A pattern that starts with a / is anchored to the start of the transfer path instead of the end. For example, /foo/** or /foo/bar/** match only leading elements in the path. If the rule is read from a per-directory filter file, the transfer path being matched will begin at the level of the filter file instead of the top of the transfer. See the section on ANCHORING INCLUDE/EXCLUDE PATTERNS for a full discussion of how to specify a pattern that matches at the root of the transfer. Rsync chooses between doing a simple string match and wildcard matching by checking if the pattern contains one of these three wildcard characters: '*', '?', and '[' : o a '?' matches any single character except a slash (/). o a '*' matches zero or more non-slash characters. o a '**' matches zero or more characters, including slashes. o a '[' introduces a character class, such as [a-z] or [[:alpha:]], that must match one character. o a trailing *** in the pattern is a shorthand that allows you to match a directory and all its contents using a single rule. For example, specifying "dir_name/***" will match both the "dir_name" directory (as if "dir_name/" had been specified) and everything in the directory (as if "dir_name/**" had been specified). o a backslash can be used to escape a wildcard character, but it is only interpreted as an escape character if at least one wildcard character is present in the match pattern. For instance, the pattern "foo\bar" matches that single backslash literally, while the pattern "foo\bar*" would need to be changed to "foo\\bar*" to avoid the "\b" becoming just "b". Here are some examples of exclude/include matching: o Option -f'- *.o' would exclude all filenames ending with .o o Option -f'- /foo' would exclude a file (or directory) named foo in the transfer-root directory o Option -f'- foo/' would exclude any directory named foo o Option -f'- foo/*/bar' would exclude any file/dir named bar which is at two levels below a directory named foo (if foo is in the transfer) o Option -f'- /foo/**/bar' would exclude any file/dir named bar that was two or more levels below a top-level directory named foo (note that /foo/bar is not excluded by this) o Options -f'+ */' -f'+ *.c' -f'- *' would include all directories and .c source files but nothing else o Options -f'+ foo/' -f'+ foo/bar.c' -f'- *' would include only the foo directory and foo/bar.c (the foo directory must be explicitly included or it would be excluded by the "- *") FILTER RULE MODIFIERS The following modifiers are accepted after an include (+) or exclude (-) rule: o A / specifies that the include/exclude rule should be matched against the absolute pathname of the current item. For example, -f'-/ /etc/passwd' would exclude the passwd file any time the transfer was sending files from the "/etc" directory, and "-/ subdir/foo" would always exclude "foo" when it is in a dir named "subdir", even if "foo" is at the root of the current transfer. o A ! specifies that the include/exclude should take effect if the pattern fails to match. For instance, -f'-! */' would exclude all non-directories. o A C is used to indicate that all the global CVS-exclude rules should be inserted as excludes in place of the "-C". No arg should follow. o An s is used to indicate that the rule applies to the sending side. When a rule affects the sending side, it affects what files are put into the sender's file list. The default is for a rule to affect both sides unless --delete-excluded was specified, in which case default rules become sender-side only. See also the hide (H) and show (S) rules, which are an alternate way to specify sending-side includes/excludes. o An r is used to indicate that the rule applies to the receiving side. When a rule affects the receiving side, it prevents files from being deleted. See the s modifier for more info. See also the protect (P) and risk (R) rules, which are an alternate way to specify receiver-side includes/excludes. o A p indicates that a rule is perishable, meaning that it is ignored in directories that are being deleted. For instance, the --cvs-exclude (-C) option's default rules that exclude things like "CVS" and "*.o" are marked as perishable, and will not prevent a directory that was removed on the source from being deleted on the destination. o An x indicates that a rule affects xattr names in xattr copy/delete operations (and is thus ignored when matching file/dir names). If no xattr-matching rules are specified, a default xattr filtering rule is used (see the --xattrs option). MERGE-FILE FILTER RULES You can merge whole files into your filter rules by specifying either a merge (.) or a dir-merge (:) filter rule (as introduced in the FILTER RULES section above). There are two kinds of merged files -- single-instance ('.') and per-directory (':'). A single-instance merge file is read one time, and its rules are incorporated into the filter list in the place of the "." rule. For per-directory merge files, rsync will scan every directory that it traverses for the named file, merging its contents when the file exists into the current list of inherited rules. These per-directory rule files must be created on the sending side because it is the sending side that is being scanned for the available files to transfer. These rule files may also need to be transferred to the receiving side if you want them to affect what files don't get deleted (see PER- DIRECTORY RULES AND DELETE below). Some examples: merge /etc/rsync/default.rules . /etc/rsync/default.rules dir-merge .per-dir-filter dir-merge,n- .non-inherited-per-dir-excludes :n- .non-inherited-per-dir-excludes The following modifiers are accepted after a merge or dir-merge rule: o A - specifies that the file should consist of only exclude patterns, with no other rule-parsing except for in-file comments. o A + specifies that the file should consist of only include patterns, with no other rule-parsing except for in-file comments. o A C is a way to specify that the file should be read in a CVS-compatible manner. This turns on 'n', 'w', and '-', but also allows the list-clearing token (!) to be specified. If no filename is provided, ".cvsignore" is assumed. o A e will exclude the merge-file name from the transfer; e.g. "dir-merge,e .rules" is like "dir-merge .rules" and "- .rules". o An n specifies that the rules are not inherited by subdirectories. o A w specifies that the rules are word-split on whitespace instead of the normal line-splitting. This also turns off comments. Note: the space that separates the prefix from the rule is treated specially, so "- foo + bar" is parsed as two rules (assuming that prefix-parsing wasn't also disabled). o You may also specify any of the modifiers for the "+" or "-" rules (above) in order to have the rules that are read in from the file default to having that modifier set (except for the ! modifier, which would not be useful). For instance, "merge,-/ .excl" would treat the contents of .excl as absolute-path excludes, while "dir-merge,s .filt" and ":sC" would each make all their per-directory rules apply only on the sending side. If the merge rule specifies sides to affect (via the s or r modifier or both), then the rules in the file must not specify sides (via a modifier or a rule prefix such as hide). Per-directory rules are inherited in all subdirectories of the directory where the merge-file was found unless the 'n' modifier was used. Each subdirectory's rules are prefixed to the inherited per-directory rules from its parents, which gives the newest rules a higher priority than the inherited rules. The entire set of dir-merge rules are grouped together in the spot where the merge-file was specified, so it is possible to override dir-merge rules via a rule that got specified earlier in the list of global rules. When the list-clearing rule ("!") is read from a per-directory file, it only clears the inherited rules for the current merge file. Another way to prevent a single rule from a dir-merge file from being inherited is to anchor it with a leading slash. Anchored rules in a per-directory merge-file are relative to the merge- file's directory, so a pattern "/foo" would only match the file "foo" in the directory where the dir-merge filter file was found. Here's an example filter file which you'd specify via --filter=". file": merge /home/user/.global-filter - *.gz dir-merge .rules + *.[ch] - *.o - foo* This will merge the contents of the /home/user/.global-filter file at the start of the list and also turns the ".rules" filename into a per-directory filter file. All rules read in prior to the start of the directory scan follow the global anchoring rules (i.e. a leading slash matches at the root of the transfer). If a per-directory merge-file is specified with a path that is a parent directory of the first transfer directory, rsync will scan all the parent dirs from that starting point to the transfer directory for the indicated per-directory file. For instance, here is a common filter (see -F): --filter=': /.rsync-filter' That rule tells rsync to scan for the file .rsync-filter in all directories from the root down through the parent directory of the transfer prior to the start of the normal directory scan of the file in the directories that are sent as a part of the transfer. (Note: for an rsync daemon, the root is always the same as the module's "path".) Some examples of this pre-scanning for per-directory files: rsync -avF /src/path/ /dest/dir rsync -av --filter=': ../../.rsync-filter' /src/path/ /dest/dir rsync -av --filter=': .rsync-filter' /src/path/ /dest/dir The first two commands above will look for ".rsync-filter" in "/" and "/src" before the normal scan begins looking for the file in "/src/path" and its subdirectories. The last command avoids the parent-dir scan and only looks for the ".rsync-filter" files in each directory that is a part of the transfer. If you want to include the contents of a ".cvsignore" in your patterns, you should use the rule ":C", which creates a dir-merge of the .cvsignore file, but parsed in a CVS-compatible manner. You can use this to affect where the --cvs-exclude (-C) option's inclusion of the per-directory .cvsignore file gets placed into your rules by putting the ":C" wherever you like in your filter rules. Without this, rsync would add the dir-merge rule for the .cvsignore file at the end of all your other rules (giving it a lower priority than your command-line rules). For example: cat <<EOT | rsync -avC --filter='. -' a/ b + foo.o :C - *.old EOT rsync -avC --include=foo.o -f :C --exclude='*.old' a/ b Both of the above rsync commands are identical. Each one will merge all the per-directory .cvsignore rules in the middle of the list rather than at the end. This allows their dir-specific rules to supersede the rules that follow the :C instead of being subservient to all your rules. To affect the other CVS exclude rules (i.e. the default list of exclusions, the contents of $HOME/.cvsignore, and the value of $CVSIGNORE) you should omit the -C command-line option and instead insert a "-C" rule into your filter rules; e.g. "--filter=-C". LIST-CLEARING FILTER RULE You can clear the current include/exclude list by using the "!" filter rule (as introduced in the FILTER RULES section above). The "current" list is either the global list of rules (if the rule is encountered while parsing the filter options) or a set of per-directory rules (which are inherited in their own sub-list, so a subdirectory can use this to clear out the parent's rules). ANCHORING INCLUDE/EXCLUDE PATTERNS As mentioned earlier, global include/exclude patterns are anchored at the "root of the transfer" (as opposed to per- directory patterns, which are anchored at the merge-file's directory). If you think of the transfer as a subtree of names that are being sent from sender to receiver, the transfer-root is where the tree starts to be duplicated in the destination directory. This root governs where patterns that start with a / match. Because the matching is relative to the transfer-root, changing the trailing slash on a source path or changing your use of the --relative option affects the path you need to use in your matching (in addition to changing how much of the file tree is duplicated on the destination host). The following examples demonstrate this. Let's say that we want to match two source files, one with an absolute path of "/home/me/foo/bar", and one with a path of "/home/you/bar/baz". Here is how the various command choices differ for a 2-source transfer: Example cmd: rsync -a /home/me /home/you /dest +/- pattern: /me/foo/bar +/- pattern: /you/bar/baz Target file: /dest/me/foo/bar Target file: /dest/you/bar/baz Example cmd: rsync -a /home/me/ /home/you/ /dest +/- pattern: /foo/bar (note missing "me") +/- pattern: /bar/baz (note missing "you") Target file: /dest/foo/bar Target file: /dest/bar/baz Example cmd: rsync -a --relative /home/me/ /home/you /dest +/- pattern: /home/me/foo/bar (note full path) +/- pattern: /home/you/bar/baz (ditto) Target file: /dest/home/me/foo/bar Target file: /dest/home/you/bar/baz Example cmd: cd /home; rsync -a --relative me/foo you/ /dest +/- pattern: /me/foo/bar (starts at specified path) +/- pattern: /you/bar/baz (ditto) Target file: /dest/me/foo/bar Target file: /dest/you/bar/baz The easiest way to see what name you should filter is to just look at the output when using --verbose and put a / in front of the name (use the --dry-run option if you're not yet ready to copy any files). PER-DIRECTORY RULES AND DELETE Without a delete option, per-directory rules are only relevant on the sending side, so you can feel free to exclude the merge files themselves without affecting the transfer. To make this easy, the 'e' modifier adds this exclude for you, as seen in these two equivalent commands: rsync -av --filter=': .excl' --exclude=.excl host:src/dir /dest rsync -av --filter=':e .excl' host:src/dir /dest However, if you want to do a delete on the receiving side AND you want some files to be excluded from being deleted, you'll need to be sure that the receiving side knows what files to exclude. The easiest way is to include the per-directory merge files in the transfer and use --delete-after, because this ensures that the receiving side gets all the same exclude rules as the sending side before it tries to delete anything: rsync -avF --delete-after host:src/dir /dest However, if the merge files are not a part of the transfer, you'll need to either specify some global exclude rules (i.e. specified on the command line), or you'll need to maintain your own per-directory merge files on the receiving side. An example of the first is this (assume that the remote .rules files exclude themselves): rsync -av --filter=': .rules' --filter='. /my/extra.rules' --delete host:src/dir /dest In the above example the extra.rules file can affect both sides of the transfer, but (on the sending side) the rules are subservient to the rules merged from the .rules files because they were specified after the per-directory merge rule. In one final example, the remote side is excluding the .rsync- filter files from the transfer, but we want to use our own .rsync-filter files to control what gets deleted on the receiving side. To do this we must specifically exclude the per-directory merge files (so that they don't get deleted) and then put rules into the local files to control what else should not get deleted. Like one of these commands: rsync -av --filter=':e /.rsync-filter' --delete \ host:src/dir /dest rsync -avFF --delete host:src/dir /dest TRANSFER RULES top In addition to the FILTER RULES that affect the recursive file scans that generate the file list on the sending and (when deleting) receiving sides, there are transfer rules. These rules affect which files the generator decides need to be transferred without the side effects of an exclude filter rule. Transfer rules affect only files and never directories. Because a transfer rule does not affect what goes into the sender's (and receiver's) file list, it cannot have any effect on which files get deleted on the receiving side. For example, if the file "foo" is present in the sender's list but its size is such that it is omitted due to a transfer rule, the receiving side does not request the file. However, its presence in the file list means that a delete pass will not remove a matching file named "foo" on the receiving side. On the other hand, a server-side exclude (hide) of the file "foo" leaves the file out of the server's file list, and absent a receiver-side exclude (protect) the receiver will remove a matching file named "foo" if deletions are requested. Given that the files are still in the sender's file list, the --prune-empty-dirs option will not judge a directory as being empty even if it contains only files that the transfer rules omitted. Similarly, a transfer rule does not have any extra effect on which files are deleted on the receiving side, so setting a maximum file size for the transfer does not prevent big files from being deleted. Examples of transfer rules include the default "quick check" algorithm (which compares size & modify time), the --update option, the --max-size option, the --ignore-non-existing option, and a few others. BATCH MODE top Batch mode can be used to apply the same set of updates to many identical systems. Suppose one has a tree which is replicated on a number of hosts. Now suppose some changes have been made to this source tree and those changes need to be propagated to the other hosts. In order to do this using batch mode, rsync is run with the write-batch option to apply the changes made to the source tree to one of the destination trees. The write-batch option causes the rsync client to store in a "batch file" all the information needed to repeat this operation against other, identical destination trees. Generating the batch file once saves having to perform the file status, checksum, and data block generation more than once when updating multiple destination trees. Multicast transport protocols can be used to transfer the batch update files in parallel to many hosts at once, instead of sending the same data to every host individually. To apply the recorded changes to another destination tree, run rsync with the read-batch option, specifying the name of the same batch file, and the destination tree. Rsync updates the destination tree using the information stored in the batch file. For your convenience, a script file is also created when the write-batch option is used: it will be named the same as the batch file with ".sh" appended. This script file contains a command-line suitable for updating a destination tree using the associated batch file. It can be executed using a Bourne (or Bourne-like) shell, optionally passing in an alternate destination tree pathname which is then used instead of the original destination path. This is useful when the destination tree path on the current host differs from the one used to create the batch file. Examples: $ rsync --write-batch=foo -a host:/source/dir/ /adest/dir/ $ scp foo* remote: $ ssh remote ./foo.sh /bdest/dir/ $ rsync --write-batch=foo -a /source/dir/ /adest/dir/ $ ssh remote rsync --read-batch=- -a /bdest/dir/ <foo In these examples, rsync is used to update /adest/dir/ from /source/dir/ and the information to repeat this operation is stored in "foo" and "foo.sh". The host "remote" is then updated with the batched data going into the directory /bdest/dir. The differences between the two examples reveals some of the flexibility you have in how you deal with batches: o The first example shows that the initial copy doesn't have to be local -- you can push or pull data to/from a remote host using either the remote-shell syntax or rsync daemon syntax, as desired. o The first example uses the created "foo.sh" file to get the right rsync options when running the read-batch command on the remote host. o The second example reads the batch data via standard input so that the batch file doesn't need to be copied to the remote machine first. This example avoids the foo.sh script because it needed to use a modified --read-batch option, but you could edit the script file if you wished to make use of it (just be sure that no other option is trying to use standard input, such as the --exclude-from=- option). Caveats: The read-batch option expects the destination tree that it is updating to be identical to the destination tree that was used to create the batch update fileset. When a difference between the destination trees is encountered the update might be discarded with a warning (if the file appears to be up-to-date already) or the file-update may be attempted and then, if the file fails to verify, the update discarded with an error. This means that it should be safe to re-run a read-batch operation if the command got interrupted. If you wish to force the batched-update to always be attempted regardless of the file's size and date, use the -I option (when reading the batch). If an error occurs, the destination tree will probably be in a partially updated state. In that case, rsync can be used in its regular (non-batch) mode of operation to fix up the destination tree. The rsync version used on all destinations must be at least as new as the one used to generate the batch file. Rsync will die with an error if the protocol version in the batch file is too new for the batch-reading rsync to handle. See also the --protocol option for a way to have the creating rsync generate a batch file that an older rsync can understand. (Note that batch files changed format in version 2.6.3, so mixing versions older than that with newer versions will not work.) When reading a batch file, rsync will force the value of certain options to match the data in the batch file if you didn't set them to the same as the batch-writing command. Other options can (and should) be changed. For instance --write-batch changes to --read-batch, --files-from is dropped, and the --filter / --include / --exclude options are not needed unless one of the --delete options is specified. The code that creates the BATCH.sh file transforms any filter/include/exclude options into a single list that is appended as a "here" document to the shell script file. An advanced user can use this to modify the exclude list if a change in what gets deleted by --delete is desired. A normal user can ignore this detail and just use the shell script as an easy way to run the appropriate --read-batch command for the batched data. The original batch mode in rsync was based on "rsync+", but the latest version uses a new implementation. SYMBOLIC LINKS top Three basic behaviors are possible when rsync encounters a symbolic link in the source directory. By default, symbolic links are not transferred at all. A message "skipping non-regular" file is emitted for any symlinks that exist. If --links is specified, then symlinks are added to the transfer (instead of being noisily ignored), and the default handling is to recreate them with the same target on the destination. Note that --archive implies --links. If --copy-links is specified, then symlinks are "collapsed" by copying their referent, rather than the symlink. Rsync can also distinguish "safe" and "unsafe" symbolic links. An example where this might be used is a web site mirror that wishes to ensure that the rsync module that is copied does not include symbolic links to /etc/passwd in the public section of the site. Using --copy-unsafe-links will cause any links to be copied as the file they point to on the destination. Using --safe-links will cause unsafe links to be omitted by the receiver. (Note that you must specify or imply --links for --safe-links to have any effect.) Symbolic links are considered unsafe if they are absolute symlinks (start with /), empty, or if they contain enough ".." components to ascend from the top of the transfer. Here's a summary of how the symlink options are interpreted. The list is in order of precedence, so if your combination of options isn't mentioned, use the first line that is a complete subset of your options: --copy-links Turn all symlinks into normal files and directories (leaving no symlinks in the transfer for any other options to affect). --copy-dirlinks Turn just symlinks to directories into real directories, leaving all other symlinks to be handled as described below. --links --copy-unsafe-links Turn all unsafe symlinks into files and create all safe symlinks. --copy-unsafe-links Turn all unsafe symlinks into files, noisily skip all safe symlinks. --links --safe-links The receiver skips creating unsafe symlinks found in the transfer and creates the safe ones. --links Create all symlinks. For the effect of --munge-links, see the discussion in that option's section. Note that the --keep-dirlinks option does not effect symlinks in the transfer but instead affects how rsync treats a symlink to a directory that already exists on the receiving side. See that option's section for a warning. DIAGNOSTICS top Rsync occasionally produces error messages that may seem a little cryptic. The one that seems to cause the most confusion is "protocol version mismatch -- is your shell clean?". This message is usually caused by your startup scripts or remote shell facility producing unwanted garbage on the stream that rsync is using for its transport. The way to diagnose this problem is to run your remote shell like this: ssh remotehost /bin/true > out.dat then look at out.dat. If everything is working correctly then out.dat should be a zero length file. If you are getting the above error from rsync then you will probably find that out.dat contains some text or data. Look at the contents and try to work out what is producing it. The most common cause is incorrectly configured shell startup scripts (such as .cshrc or .profile) that contain output statements for non-interactive logins. If you are having trouble debugging filter patterns, then try specifying the -vv option. At this level of verbosity rsync will show why each individual file is included or excluded. EXIT VALUES top o 0 - Success o 1 - Syntax or usage error o 2 - Protocol incompatibility o 3 - Errors selecting input/output files, dirs o o 4 - Requested action not supported. Either: an attempt was made to manipulate 64-bit files on a platform that cannot support them o an option was specified that is supported by the client and not by the server o 5 - Error starting client-server protocol o 6 - Daemon unable to append to log-file o 10 - Error in socket I/O o 11 - Error in file I/O o 12 - Error in rsync protocol data stream o 13 - Errors with program diagnostics o 14 - Error in IPC code o 20 - Received SIGUSR1 or SIGINT o 21 - Some error returned by waitpid() o 22 - Error allocating core memory buffers o 23 - Partial transfer due to error o 24 - Partial transfer due to vanished source files o 25 - The --max-delete limit stopped deletions o 30 - Timeout in data send/receive o 35 - Timeout waiting for daemon connection ENVIRONMENT VARIABLES top CVSIGNORE The CVSIGNORE environment variable supplements any ignore patterns in .cvsignore files. See the --cvs-exclude option for more details. RSYNC_ICONV Specify a default --iconv setting using this environment variable. First supported in 3.0.0. RSYNC_OLD_ARGS Specify a "1" if you want the --old-args option to be enabled by default, a "2" (or more) if you want it to be enabled in the repeated-option state, or a "0" to make sure that it is disabled by default. When this environment variable is set to a non-zero value, it supersedes the RSYNC_PROTECT_ARGS variable. This variable is ignored if --old-args, --no-old-args, or --secluded-args is specified on the command line. First supported in 3.2.4. RSYNC_PROTECT_ARGS Specify a non-zero numeric value if you want the --secluded-args option to be enabled by default, or a zero value to make sure that it is disabled by default. This variable is ignored if --secluded-args, --no- secluded-args, or --old-args is specified on the command line. First supported in 3.1.0. Starting in 3.2.4, this variable is ignored if RSYNC_OLD_ARGS is set to a non-zero value. RSYNC_RSH This environment variable allows you to override the default shell used as the transport for rsync. Command line options are permitted after the command name, just as in the --rsh (-e) option. RSYNC_PROXY This environment variable allows you to redirect your rsync client to use a web proxy when connecting to an rsync daemon. You should set RSYNC_PROXY to a hostname:port pair. RSYNC_PASSWORD This environment variable allows you to set the password for an rsync daemon connection, which avoids the password prompt. Note that this does not supply a password to a remote shell transport such as ssh (consult its documentation for how to do that). USER or LOGNAME The USER or LOGNAME environment variables are used to determine the default username sent to an rsync daemon. If neither is set, the username defaults to "nobody". If both are set, USER takes precedence. RSYNC_PARTIAL_DIR This environment variable specifies the directory to use for a --partial transfer without implying that partial transfers be enabled. See the --partial-dir option for full details. RSYNC_COMPRESS_LIST This environment variable allows you to customize the negotiation of the compression algorithm by specifying an alternate order or a reduced list of names. Use the command rsync --version to see the available compression names. See the --compress option for full details. RSYNC_CHECKSUM_LIST This environment variable allows you to customize the negotiation of the checksum algorithm by specifying an alternate order or a reduced list of names. Use the command rsync --version to see the available checksum names. See the --checksum-choice option for full details. RSYNC_MAX_ALLOC This environment variable sets an allocation maximum as if you had used the --max-alloc option. RSYNC_PORT This environment variable is not read by rsync, but is instead set in its sub-environment when rsync is running the remote shell in combination with a daemon connection. This allows a script such as rsync-ssl to be able to know the port number that the user specified on the command line. HOME This environment variable is used to find the user's default .cvsignore file. RSYNC_CONNECT_PROG This environment variable is mainly used in debug setups to set the program to use when making a daemon connection. See CONNECTING TO AN RSYNC DAEMON for full details. RSYNC_SHELL This environment variable is mainly used in debug setups to set the program to use to run the program specified by RSYNC_CONNECT_PROG. See CONNECTING TO AN RSYNC DAEMON for full details. FILES top /etc/rsyncd.conf or rsyncd.conf SEE ALSO top rsync-ssl(1), rsyncd.conf(5), rrsync(1) BUGS top o Times are transferred as *nix time_t values. o When transferring to FAT filesystems rsync may re-sync unmodified files. See the comments on the --modify-window option. o File permissions, devices, etc. are transferred as native numerical values. o See also the comments on the --delete option. Please report bugs! See the web site at https://rsync.samba.org/. VERSION top This manpage is current for version 3.2.7 of rsync. INTERNAL OPTIONS top The options --server and --sender are used internally by rsync, and should never be typed by a user under normal circumstances. Some awareness of these options may be needed in certain scenarios, such as when setting up a login that can only run an rsync command. For instance, the support directory of the rsync distribution has an example script named rrsync (for restricted rsync) that can be used with a restricted ssh login. CREDITS top Rsync is distributed under the GNU General Public License. See the file COPYING for details. An rsync web site is available at https://rsync.samba.org/. The site includes an FAQ-O-Matic which may cover questions unanswered by this manual page. The rsync github project is https://github.com/WayneD/rsync. We would be delighted to hear from you if you like this program. Please contact the mailing-list at rsync@lists.samba.org. This program uses the excellent zlib compression library written by Jean-loup Gailly and Mark Adler. THANKS top Special thanks go out to: John Van Essen, Matt McCutchen, Wesley W. Terpstra, David Dykstra, Jos Backus, Sebastian Krahmer, Martin Pool, and our gone-but-not-forgotten compadre, J.W. Schultz. Thanks also to Richard Brent, Brendan Mackay, Bill Waite, Stephen Rothwell and David Bell. I've probably missed some people, my apologies if I have. AUTHOR top Rsync was originally written by Andrew Tridgell and Paul Mackerras. Many people have later contributed to it. It is currently maintained by Wayne Davison. Mailing lists for support and development are available at https://lists.samba.org/. COLOPHON top This page is part of the rsync (a fast, versatile, remote (and local) file-copying tool) project. Information about the project can be found at https://rsync.samba.org/. If you have a bug report for this manual page, see https://rsync.samba.org/bugzilla.html. This page was obtained from the tarball fetched from https://download.samba.org/pub/rsync/ 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 rsync 3.2.7 20 Oct 2022 rsync(1) Pages that refer to this page: pmlogger_daily(1), rrsync(1), rsync-ssl(1), rsyncd.conf(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: Copy "./export" recursively to "/path/to/webroot" preserving permissions Bash Command:<START>rsync -pr ./export /path/to/webroot<END>
Copy "/Users/username/path/on/machine/" to "username@server.ip.address.here:/home/username/path/on/server/" and convert encoding from UTF-8-MAC to UTF-8
rsync --iconv=UTF-8-MAC,UTF-8 /Users/username/path/on/machine/ 'username@server.ip.address.here:/home/username/path/on/server/'
['rsync']
Output a Bash command to accomplish the following task. Task: Copy "/Users/username/path/on/machine/" to "username@server.ip.address.here:/home/username/path/on/server/" and convert encoding from UTF-8-MAC to UTF-8 Bash Command:<START>rsync --iconv=UTF-8-MAC,UTF-8 /Users/username/path/on/machine/ 'username@server.ip.address.here:/home/username/path/on/server/'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # rsync\n\n> Transfer files either to or from a remote host (but not between two remote hosts), by default using SSH.\n> To specify a remote path, use `user@host:path/to/file_or_directory`.\n> More information: <https://download.samba.org/pub/rsync/rsync.1>.\n\n- Transfer a file:\n\n`rsync {{path/to/source}} {{path/to/destination}}`\n\n- Use archive mode (recursively copy directories, copy symlinks without resolving, and preserve permissions, ownership and modification times):\n\n`rsync --archive {{path/to/source}} {{path/to/destination}}`\n\n- Compress the data as it is sent to the destination, display verbose and human-readable progress, and keep partially transferred files if interrupted:\n\n`rsync --compress --verbose --human-readable --partial --progress {{path/to/source}} {{path/to/destination}}`\n\n- Recursively copy directories:\n\n`rsync --recursive {{path/to/source}} {{path/to/destination}}`\n\n- Transfer directory contents, but not the directory itself:\n\n`rsync --recursive {{path/to/source}}/ {{path/to/destination}}`\n\n- Use archive mode, resolve symlinks and skip files that are newer on the destination:\n\n`rsync --archive --update --copy-links {{path/to/source}} {{path/to/destination}}`\n\n- Transfer a directory to a remote host running `rsyncd` and delete files on the destination that do not exist on the source:\n\n`rsync --recursive --delete rsync://{{host}}:{{path/to/source}} {{path/to/destination}}`\n\n- Transfer a file over SSH using a different port than the default (22) and show global progress:\n\n`rsync --rsh 'ssh -p {{port}}' --info=progress2 {{host}}:{{path/to/source}} {{path/to/destination}}`\n Task: Copy "/Users/username/path/on/machine/" to "username@server.ip.address.here:/home/username/path/on/server/" and convert encoding from UTF-8-MAC to UTF-8 Bash Command:<START>rsync --iconv=UTF-8-MAC,UTF-8 /Users/username/path/on/machine/ 'username@server.ip.address.here:/home/username/path/on/server/'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: rsync(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rsync(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | GENERAL | SETUP | USAGE | COPYING TO A DIFFERENT NAME | SORTED TRANSFER ORDER | MULTI-HOST SECURITY | ADVANCED USAGE | CONNECTING TO AN RSYNC DAEMON | USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION | STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS | EXAMPLES | OPTION SUMMARY | OPTIONS | DAEMON OPTIONS | FILTER RULES | TRANSFER RULES | BATCH MODE | SYMBOLIC LINKS | DIAGNOSTICS | EXIT VALUES | ENVIRONMENT VARIABLES | FILES | SEE ALSO | BUGS | VERSION | INTERNAL OPTIONS | CREDITS | THANKS | AUTHOR | COLOPHON rsync(1) User Commands rsync(1) NAME top rsync - a fast, versatile, remote (and local) file-copying tool SYNOPSIS top Local: rsync [OPTION...] SRC... [DEST] Access via remote shell: Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST] Push: rsync [OPTION...] SRC... [USER@]HOST:DEST Access via rsync daemon: Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST] rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST] Push: rsync [OPTION...] SRC... [USER@]HOST::DEST rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST) Usages with just one SRC arg and no DEST arg will list the source files instead of copying. The online version of this manpage (that includes cross-linking of topics) is available at https://download.samba.org/pub/rsync/rsync.1. DESCRIPTION top Rsync is a fast and extraordinarily versatile file copying tool. It can copy locally, to/from another host over any remote shell, or to/from a remote rsync daemon. It offers a large number of options that control every aspect of its behavior and permit very flexible specification of the set of files to be copied. It is famous for its delta-transfer algorithm, which reduces the amount of data sent over the network by sending only the differences between the source files and the existing files in the destination. Rsync is widely used for backups and mirroring and as an improved copy command for everyday use. Rsync finds files that need to be transferred using a "quick check" algorithm (by default) that looks for files that have changed in size or in last-modified time. Any changes in the other preserved attributes (as requested by options) are made on the destination file directly when the quick check indicates that the file's data does not need to be updated. Some of the additional features of rsync are: o support for copying links, devices, owners, groups, and permissions o exclude and exclude-from options similar to GNU tar o a CVS exclude mode for ignoring the same files that CVS would ignore o can use any transparent remote shell, including ssh or rsh o does not require super-user privileges o pipelining of file transfers to minimize latency costs o support for anonymous or authenticated rsync daemons (ideal for mirroring) GENERAL top Rsync copies files either to or from a remote host, or locally on the current host (it does not support copying files between two remote hosts). There are two different ways for rsync to contact a remote system: using a remote-shell program as the transport (such as ssh or rsh) or contacting an rsync daemon directly via TCP. The remote-shell transport is used whenever the source or destination path contains a single colon (:) separator after a host specification. Contacting an rsync daemon directly happens when the source or destination path contains a double colon (::) separator after a host specification, OR when an rsync:// URL is specified (see also the USING RSYNC-DAEMON FEATURES VIA A REMOTE- SHELL CONNECTION section for an exception to this latter rule). As a special case, if a single source arg is specified without a destination, the files are listed in an output format similar to "ls -l". As expected, if neither the source or destination path specify a remote host, the copy occurs locally (see also the --list-only option). Rsync refers to the local side as the client and the remote side as the server. Don't confuse server with an rsync daemon. A daemon is always a server, but a server can be either a daemon or a remote-shell spawned process. SETUP top See the file README.md for installation instructions. Once installed, you can use rsync to any machine that you can access via a remote shell (as well as some that you can access using the rsync daemon-mode protocol). For remote transfers, a modern rsync uses ssh for its communications, but it may have been configured to use a different remote shell by default, such as rsh or remsh. You can also specify any remote shell you like, either by using the -e command line option, or by setting the RSYNC_RSH environment variable. Note that rsync must be installed on both the source and destination machines. USAGE top You use rsync in the same way you use rcp. You must specify a source and a destination, one of which may be remote. Perhaps the best way to explain the syntax is with some examples: rsync -t *.c foo:src/ This would transfer all files matching the pattern *.c from the current directory to the directory src on the machine foo. If any of the files already exist on the remote system then the rsync remote-update protocol is used to update the file by sending only the differences in the data. Note that the expansion of wildcards on the command-line (*.c) into a list of files is handled by the shell before it runs rsync and not by rsync itself (exactly the same as all other Posix-style programs). rsync -avz foo:src/bar /data/tmp This would recursively transfer all files from the directory src/bar on the machine foo into the /data/tmp/bar directory on the local machine. The files are transferred in archive mode, which ensures that symbolic links, devices, attributes, permissions, ownerships, etc. are preserved in the transfer. Additionally, compression will be used to reduce the size of data portions of the transfer. rsync -avz foo:src/bar/ /data/tmp A trailing slash on the source changes this behavior to avoid creating an additional directory level at the destination. You can think of a trailing / on a source as meaning "copy the contents of this directory" as opposed to "copy the directory by name", but in both cases the attributes of the containing directory are transferred to the containing directory on the destination. In other words, each of the following commands copies the files in the same way, including their setting of the attributes of /dest/foo: rsync -av /src/foo /dest rsync -av /src/foo/ /dest/foo Note also that host and module references don't require a trailing slash to copy the contents of the default directory. For example, both of these copy the remote directory's contents into "/dest": rsync -av host: /dest rsync -av host::module /dest You can also use rsync in local-only mode, where both the source and destination don't have a ':' in the name. In this case it behaves like an improved copy command. Finally, you can list all the (listable) modules available from a particular rsync daemon by leaving off the module name: rsync somehost.mydomain.com:: COPYING TO A DIFFERENT NAME top When you want to copy a directory to a different name, use a trailing slash on the source directory to put the contents of the directory into any destination directory you like: rsync -ai foo/ bar/ Rsync also has the ability to customize a destination file's name when copying a single item. The rules for this are: o The transfer list must consist of a single item (either a file or an empty directory) o The final element of the destination path must not exist as a directory o The destination path must not have been specified with a trailing slash Under those circumstances, rsync will set the name of the destination's single item to the last element of the destination path. Keep in mind that it is best to only use this idiom when copying a file and use the above trailing-slash idiom when copying a directory. The following example copies the foo.c file as bar.c in the save dir (assuming that bar.c isn't a directory): rsync -ai src/foo.c save/bar.c The single-item copy rule might accidentally bite you if you unknowingly copy a single item and specify a destination dir that doesn't exist (without using a trailing slash). For example, if src/*.c matches one file and save/dir doesn't exist, this will confuse you by naming the destination file save/dir: rsync -ai src/*.c save/dir To prevent such an accident, either make sure the destination dir exists or specify the destination path with a trailing slash: rsync -ai src/*.c save/dir/ SORTED TRANSFER ORDER top Rsync always sorts the specified filenames into its internal transfer list. This handles the merging together of the contents of identically named directories, makes it easy to remove duplicate filenames. It can, however, confuse someone when the files are transferred in a different order than what was given on the command-line. If you need a particular file to be transferred prior to another, either separate the files into different rsync calls, or consider using --delay-updates (which doesn't affect the sorted transfer order, but does make the final file-updating phase happen much more rapidly). MULTI-HOST SECURITY top Rsync takes steps to ensure that the file requests that are shared in a transfer are protected against various security issues. Most of the potential problems arise on the receiving side where rsync takes steps to ensure that the list of files being transferred remains within the bounds of what was requested. Toward this end, rsync 3.1.2 and later have aborted when a file list contains an absolute or relative path that tries to escape out of the top of the transfer. Also, beginning with version 3.2.5, rsync does two more safety checks of the file list to (1) ensure that no extra source arguments were added into the transfer other than those that the client requested and (2) ensure that the file list obeys the exclude rules that were sent to the sender. For those that don't yet have a 3.2.5 client rsync (or those that want to be extra careful), it is safest to do a copy into a dedicated destination directory for the remote files when you don't trust the remote host. For example, instead of doing an rsync copy into your home directory: rsync -aiv host1:dir1 ~ Dedicate a "host1-files" dir to the remote content: rsync -aiv host1:dir1 ~/host1-files See the --trust-sender option for additional details. CAUTION: it is not particularly safe to use rsync to copy files from a case-preserving filesystem to a case-ignoring filesystem. If you must perform such a copy, you should either disable symlinks via --no-links or enable the munging of symlinks via --munge-links (and make sure you use the right local or remote option). This will prevent rsync from doing potentially dangerous things if a symlink name overlaps with a file or directory. It does not, however, ensure that you get a full copy of all the files (since that may not be possible when the names overlap). A potentially better solution is to list all the source files and create a safe list of filenames that you pass to the --files-from option. Any files that conflict in name would need to be copied to different destination directories using more than one copy. While a copy of a case-ignoring filesystem to a case-ignoring filesystem can work out fairly well, if no --delete-during or --delete-before option is active, rsync can potentially update an existing file on the receiveing side without noticing that the upper-/lower-case of the filename should be changed to match the sender. ADVANCED USAGE top The syntax for requesting multiple files from a remote host is done by specifying additional remote-host args in the same style as the first, or with the hostname omitted. For instance, all these work: rsync -aiv host:file1 :file2 host:file{3,4} /dest/ rsync -aiv host::modname/file{1,2} host::modname/extra /dest/ rsync -aiv host::modname/first ::extra-file{1,2} /dest/ Note that a daemon connection only supports accessing one module per copy command, so if the start of a follow-up path doesn't begin with the modname of the first path, it is assumed to be a path in the module (such as the extra-file1 & extra-file2 that are grabbed above). Really old versions of rsync (2.6.9 and before) only allowed specifying one remote-source arg, so some people have instead relied on the remote-shell performing space splitting to break up an arg into multiple paths. Such unintuitive behavior is no longer supported by default (though you can request it, as described below). Starting in 3.2.4, filenames are passed to a remote shell in such a way as to preserve the characters you give it. Thus, if you ask for a file with spaces in the name, that's what the remote rsync looks for: rsync -aiv host:'a simple file.pdf' /dest/ If you use scripts that have been written to manually apply extra quoting to the remote rsync args (or to require remote arg splitting), you can ask rsync to let your script handle the extra escaping. This is done by either adding the --old-args option to the rsync runs in the script (which requires a new rsync) or exporting RSYNC_OLD_ARGS=1 and RSYNC_PROTECT_ARGS=0 (which works with old or new rsync versions). CONNECTING TO AN RSYNC DAEMON top It is also possible to use rsync without a remote shell as the transport. In this case you will directly connect to a remote rsync daemon, typically using TCP port 873. (This obviously requires the daemon to be running on the remote system, so refer to the STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS section below for information on that.) Using rsync in this way is the same as using it with a remote shell except that: o Use either double-colon syntax or rsync:// URL syntax instead of the single-colon (remote shell) syntax. o The first element of the "path" is actually a module name. o Additional remote source args can use an abbreviated syntax that omits the hostname and/or the module name, as discussed in ADVANCED USAGE. o The remote daemon may print a "message of the day" when you connect. o If you specify only the host (with no module or path) then a list of accessible modules on the daemon is output. o If you specify a remote source path but no destination, a listing of the matching files on the remote daemon is output. o The --rsh (-e) option must be omitted to avoid changing the connection style from using a socket connection to USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION. An example that copies all the files in a remote module named "src": rsync -av host::src /dest Some modules on the remote daemon may require authentication. If so, you will receive a password prompt when you connect. You can avoid the password prompt by setting the environment variable RSYNC_PASSWORD to the password you want to use or using the --password-file option. This may be useful when scripting rsync. WARNING: On some systems environment variables are visible to all users. On those systems using --password-file is recommended. You may establish the connection via a web proxy by setting the environment variable RSYNC_PROXY to a hostname:port pair pointing to your web proxy. Note that your web proxy's configuration must support proxy connections to port 873. You may also establish a daemon connection using a program as a proxy by setting the environment variable RSYNC_CONNECT_PROG to the commands you wish to run in place of making a direct socket connection. The string may contain the escape "%H" to represent the hostname specified in the rsync command (so use "%%" if you need a single "%" in your string). For example: export RSYNC_CONNECT_PROG='ssh proxyhost nc %H 873' rsync -av targethost1::module/src/ /dest/ rsync -av rsync://targethost2/module/src/ /dest/ The command specified above uses ssh to run nc (netcat) on a proxyhost, which forwards all data to port 873 (the rsync daemon) on the targethost (%H). Note also that if the RSYNC_SHELL environment variable is set, that program will be used to run the RSYNC_CONNECT_PROG command instead of using the default shell of the system() call. USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION top It is sometimes useful to use various features of an rsync daemon (such as named modules) without actually allowing any new socket connections into a system (other than what is already required to allow remote-shell access). Rsync supports connecting to a host using a remote shell and then spawning a single-use "daemon" server that expects to read its config file in the home dir of the remote user. This can be useful if you want to encrypt a daemon-style transfer's data, but since the daemon is started up fresh by the remote user, you may not be able to use features such as chroot or change the uid used by the daemon. (For another way to encrypt a daemon transfer, consider using ssh to tunnel a local port to a remote machine and configure a normal rsync daemon on that remote host to only allow connections from "localhost".) From the user's perspective, a daemon transfer via a remote-shell connection uses nearly the same command-line syntax as a normal rsync-daemon transfer, with the only exception being that you must explicitly set the remote shell program on the command-line with the --rsh=COMMAND option. (Setting the RSYNC_RSH in the environment will not turn on this functionality.) For example: rsync -av --rsh=ssh host::module /dest If you need to specify a different remote-shell user, keep in mind that the user@ prefix in front of the host is specifying the rsync-user value (for a module that requires user-based authentication). This means that you must give the '-l user' option to ssh when specifying the remote-shell, as in this example that uses the short version of the --rsh option: rsync -av -e "ssh -l ssh-user" rsync-user@host::module /dest The "ssh-user" will be used at the ssh level; the "rsync-user" will be used to log-in to the "module". In this setup, the daemon is started by the ssh command that is accessing the system (which can be forced via the ~/.ssh/authorized_keys file, if desired). However, when accessing a daemon directly, it needs to be started beforehand. STARTING AN RSYNC DAEMON TO ACCEPT CONNECTIONS top In order to connect to an rsync daemon, the remote system needs to have a daemon already running (or it needs to have configured something like inetd to spawn an rsync daemon for incoming connections on a particular port). For full information on how to start a daemon that will handling incoming socket connections, see the rsyncd.conf(5) manpage -- that is the config file for the daemon, and it contains the full details for how to run the daemon (including stand-alone and inetd configurations). If you're using one of the remote-shell transports for the transfer, there is no need to manually start an rsync daemon. EXAMPLES top Here are some examples of how rsync can be used. To backup a home directory, which consists of large MS Word files and mail folders, a per-user cron job can be used that runs this each day: rsync -aiz . bkhost:backup/joe/ To move some files from a remote host to the local host, you could run: rsync -aiv --remove-source-files rhost:/tmp/{file1,file2}.c ~/src/ OPTION SUMMARY top Here is a short summary of the options available in rsync. Each option also has its own detailed description later in this manpage. --verbose, -v increase verbosity --info=FLAGS fine-grained informational verbosity --debug=FLAGS fine-grained debug verbosity --stderr=e|a|c change stderr output mode (default: errors) --quiet, -q suppress non-error messages --no-motd suppress daemon-mode MOTD --checksum, -c skip based on checksum, not mod-time & size --archive, -a archive mode is -rlptgoD (no -A,-X,-U,-N,-H) --no-OPTION turn off an implied OPTION (e.g. --no-D) --recursive, -r recurse into directories --relative, -R use relative path names --no-implied-dirs don't send implied dirs with --relative --backup, -b make backups (see --suffix & --backup-dir) --backup-dir=DIR make backups into hierarchy based in DIR --suffix=SUFFIX backup suffix (default ~ w/o --backup-dir) --update, -u skip files that are newer on the receiver --inplace update destination files in-place --append append data onto shorter files --append-verify --append w/old data in file checksum --dirs, -d transfer directories without recursing --old-dirs, --old-d works like --dirs when talking to old rsync --mkpath create destination's missing path components --links, -l copy symlinks as symlinks --copy-links, -L transform symlink into referent file/dir --copy-unsafe-links only "unsafe" symlinks are transformed --safe-links ignore symlinks that point outside the tree --munge-links munge symlinks to make them safe & unusable --copy-dirlinks, -k transform symlink to dir into referent dir --keep-dirlinks, -K treat symlinked dir on receiver as dir --hard-links, -H preserve hard links --perms, -p preserve permissions --executability, -E preserve executability --chmod=CHMOD affect file and/or directory permissions --acls, -A preserve ACLs (implies --perms) --xattrs, -X preserve extended attributes --owner, -o preserve owner (super-user only) --group, -g preserve group --devices preserve device files (super-user only) --copy-devices copy device contents as a regular file --write-devices write to devices as files (implies --inplace) --specials preserve special files -D same as --devices --specials --times, -t preserve modification times --atimes, -U preserve access (use) times --open-noatime avoid changing the atime on opened files --crtimes, -N preserve create times (newness) --omit-dir-times, -O omit directories from --times --omit-link-times, -J omit symlinks from --times --super receiver attempts super-user activities --fake-super store/recover privileged attrs using xattrs --sparse, -S turn sequences of nulls into sparse blocks --preallocate allocate dest files before writing them --dry-run, -n perform a trial run with no changes made --whole-file, -W copy files whole (w/o delta-xfer algorithm) --checksum-choice=STR choose the checksum algorithm (aka --cc) --one-file-system, -x don't cross filesystem boundaries --block-size=SIZE, -B force a fixed checksum block-size --rsh=COMMAND, -e specify the remote shell to use --rsync-path=PROGRAM specify the rsync to run on remote machine --existing skip creating new files on receiver --ignore-existing skip updating files that exist on receiver --remove-source-files sender removes synchronized files (non-dir) --del an alias for --delete-during --delete delete extraneous files from dest dirs --delete-before receiver deletes before xfer, not during --delete-during receiver deletes during the transfer --delete-delay find deletions during, delete after --delete-after receiver deletes after transfer, not during --delete-excluded also delete excluded files from dest dirs --ignore-missing-args ignore missing source args without error --delete-missing-args delete missing source args from destination --ignore-errors delete even if there are I/O errors --force force deletion of dirs even if not empty --max-delete=NUM don't delete more than NUM files --max-size=SIZE don't transfer any file larger than SIZE --min-size=SIZE don't transfer any file smaller than SIZE --max-alloc=SIZE change a limit relating to memory alloc --partial keep partially transferred files --partial-dir=DIR put a partially transferred file into DIR --delay-updates put all updated files into place at end --prune-empty-dirs, -m prune empty directory chains from file-list --numeric-ids don't map uid/gid values by user/group name --usermap=STRING custom username mapping --groupmap=STRING custom groupname mapping --chown=USER:GROUP simple username/groupname mapping --timeout=SECONDS set I/O timeout in seconds --contimeout=SECONDS set daemon connection timeout in seconds --ignore-times, -I don't skip files that match size and time --size-only skip files that match in size --modify-window=NUM, -@ set the accuracy for mod-time comparisons --temp-dir=DIR, -T create temporary files in directory DIR --fuzzy, -y find similar file for basis if no dest file --compare-dest=DIR also compare destination files relative to DIR --copy-dest=DIR ... and include copies of unchanged files --link-dest=DIR hardlink to files in DIR when unchanged --compress, -z compress file data during the transfer --compress-choice=STR choose the compression algorithm (aka --zc) --compress-level=NUM explicitly set compression level (aka --zl) --skip-compress=LIST skip compressing files with suffix in LIST --cvs-exclude, -C auto-ignore files in the same way CVS does --filter=RULE, -f add a file-filtering RULE -F same as --filter='dir-merge /.rsync-filter' repeated: --filter='- .rsync-filter' --exclude=PATTERN exclude files matching PATTERN --exclude-from=FILE read exclude patterns from FILE --include=PATTERN don't exclude files matching PATTERN --include-from=FILE read include patterns from FILE --files-from=FILE read list of source-file names from FILE --from0, -0 all *-from/filter files are delimited by 0s --old-args disable the modern arg-protection idiom --secluded-args, -s use the protocol to safely send the args --trust-sender trust the remote sender's file list --copy-as=USER[:GROUP] specify user & optional group for the copy --address=ADDRESS bind address for outgoing socket to daemon --port=PORT specify double-colon alternate port number --sockopts=OPTIONS specify custom TCP options --blocking-io use blocking I/O for the remote shell --outbuf=N|L|B set out buffering to None, Line, or Block --stats give some file-transfer stats --8-bit-output, -8 leave high-bit chars unescaped in output --human-readable, -h output numbers in a human-readable format --progress show progress during transfer -P same as --partial --progress --itemize-changes, -i output a change-summary for all updates --remote-option=OPT, -M send OPTION to the remote side only --out-format=FORMAT output updates using the specified FORMAT --log-file=FILE log what we're doing to the specified FILE --log-file-format=FMT log updates using the specified FMT --password-file=FILE read daemon-access password from FILE --early-input=FILE use FILE for daemon's early exec input --list-only list the files instead of copying them --bwlimit=RATE limit socket I/O bandwidth --stop-after=MINS Stop rsync after MINS minutes have elapsed --stop-at=y-m-dTh:m Stop rsync at the specified point in time --fsync fsync every written file --write-batch=FILE write a batched update to FILE --only-write-batch=FILE like --write-batch but w/o updating dest --read-batch=FILE read a batched update from FILE --protocol=NUM force an older protocol version to be used --iconv=CONVERT_SPEC request charset conversion of filenames --checksum-seed=NUM set block/file checksum seed (advanced) --ipv4, -4 prefer IPv4 --ipv6, -6 prefer IPv6 --version, -V print the version + other info and exit --help, -h (*) show this help (* -h is help only on its own) Rsync can also be run as a daemon, in which case the following options are accepted: --daemon run as an rsync daemon --address=ADDRESS bind to the specified address --bwlimit=RATE limit socket I/O bandwidth --config=FILE specify alternate rsyncd.conf file --dparam=OVERRIDE, -M override global daemon config parameter --no-detach do not detach from the parent --port=PORT listen on alternate port number --log-file=FILE override the "log file" setting --log-file-format=FMT override the "log format" setting --sockopts=OPTIONS specify custom TCP options --verbose, -v increase verbosity --ipv4, -4 prefer IPv4 --ipv6, -6 prefer IPv6 --help, -h show this help (when used with --daemon) OPTIONS top Rsync accepts both long (double-dash + word) and short (single- dash + letter) options. The full list of the available options are described below. If an option can be specified in more than one way, the choices are comma-separated. Some options only have a long variant, not a short. If the option takes a parameter, the parameter is only listed after the long variant, even though it must also be specified for the short. When specifying a parameter, you can either use the form --option=param, --option param, -o=param, -o param, or -oparam (the latter choices assume that your option has a short variant). The parameter may need to be quoted in some manner for it to survive the shell's command-line parsing. Also keep in mind that a leading tilde (~) in a pathname is substituted by your shell, so make sure that you separate the option name from the pathname using a space if you want the local shell to expand it. --help Print a short help page describing the options available in rsync and exit. You can also use -h for --help when it is used without any other options (since it normally means --human-readable). --version, -V Print the rsync version plus other info and exit. When repeated, the information is output is a JSON format that is still fairly readable (client side only). The output includes a list of compiled-in capabilities, a list of optimizations, the default list of checksum algorithms, the default list of compression algorithms, the default list of daemon auth digests, a link to the rsync web site, and a few other items. --verbose, -v This option increases the amount of information you are given during the transfer. By default, rsync works silently. A single -v will give you information about what files are being transferred and a brief summary at the end. Two -v options will give you information on what files are being skipped and slightly more information at the end. More than two -v options should only be used if you are debugging rsync. The end-of-run summary tells you the number of bytes sent to the remote rsync (which is the receiving side on a local copy), the number of bytes received from the remote host, and the average bytes per second of the transferred data computed over the entire length of the rsync run. The second line shows the total size (in bytes), which is the sum of all the file sizes that rsync considered transferring. It also shows a "speedup" value, which is a ratio of the total file size divided by the sum of the sent and received bytes (which is really just a feel-good bigger-is-better number). Note that these byte values can be made more (or less) human-readable by using the --human-readable (or --no-human-readable) options. In a modern rsync, the -v option is equivalent to the setting of groups of --info and --debug options. You can choose to use these newer options in addition to, or in place of using --verbose, as any fine-grained settings override the implied settings of -v. Both --info and --debug have a way to ask for help that tells you exactly what flags are set for each increase in verbosity. However, do keep in mind that a daemon's "max verbosity" setting will limit how high of a level the various individual flags can be set on the daemon side. For instance, if the max is 2, then any info and/or debug flag that is set to a higher value than what would be set by -vv will be downgraded to the -vv level in the daemon's logging. --info=FLAGS This option lets you have fine-grained control over the information output you want to see. An individual flag name may be followed by a level number, with 0 meaning to silence that output, 1 being the default output level, and higher numbers increasing the output of that flag (for those that support higher levels). Use --info=help to see all the available flag names, what they output, and what flag names are added for each increase in the verbose level. Some examples: rsync -a --info=progress2 src/ dest/ rsync -avv --info=stats2,misc1,flist0 src/ dest/ Note that --info=name's output is affected by the --out- format and --itemize-changes (-i) options. See those options for more information on what is output and when. This option was added to 3.1.0, so an older rsync on the server side might reject your attempts at fine-grained control (if one or more flags needed to be send to the server and the server was too old to understand them). See also the "max verbosity" caveat above when dealing with a daemon. --debug=FLAGS This option lets you have fine-grained control over the debug output you want to see. An individual flag name may be followed by a level number, with 0 meaning to silence that output, 1 being the default output level, and higher numbers increasing the output of that flag (for those that support higher levels). Use --debug=help to see all the available flag names, what they output, and what flag names are added for each increase in the verbose level. Some examples: rsync -avvv --debug=none src/ dest/ rsync -avA --del --debug=del2,acl src/ dest/ Note that some debug messages will only be output when the --stderr=all option is specified, especially those pertaining to I/O and buffer debugging. Beginning in 3.2.0, this option is no longer auto- forwarded to the server side in order to allow you to specify different debug values for each side of the transfer, as well as to specify a new debug option that is only present in one of the rsync versions. If you want to duplicate the same option on both sides, using brace expansion is an easy way to save you some typing. This works in zsh and bash: rsync -aiv {-M,}--debug=del2 src/ dest/ --stderr=errors|all|client This option controls which processes output to stderr and if info messages are also changed to stderr. The mode strings can be abbreviated, so feel free to use a single letter value. The 3 possible choices are: o errors - (the default) causes all the rsync processes to send an error directly to stderr, even if the process is on the remote side of the transfer. Info messages are sent to the client side via the protocol stream. If stderr is not available (i.e. when directly connecting with a daemon via a socket) errors fall back to being sent via the protocol stream. o all - causes all rsync messages (info and error) to get written directly to stderr from all (possible) processes. This causes stderr to become line- buffered (instead of raw) and eliminates the ability to divide up the info and error messages by file handle. For those doing debugging or using several levels of verbosity, this option can help to avoid clogging up the transfer stream (which should prevent any chance of a deadlock bug hanging things up). It also allows --debug to enable some extra I/O related messages. o client - causes all rsync messages to be sent to the client side via the protocol stream. One client process outputs all messages, with errors on stderr and info messages on stdout. This was the default in older rsync versions, but can cause error delays when a lot of transfer data is ahead of the messages. If you're pushing files to an older rsync, you may want to use --stderr=all since that idiom has been around for several releases. This option was added in rsync 3.2.3. This version also began the forwarding of a non-default setting to the remote side, though rsync uses the backward-compatible options --msgs2stderr and --no-msgs2stderr to represent the all and client settings, respectively. A newer rsync will continue to accept these older option names to maintain compatibility. --quiet, -q This option decreases the amount of information you are given during the transfer, notably suppressing information messages from the remote server. This option is useful when invoking rsync from cron. --no-motd This option affects the information that is output by the client at the start of a daemon transfer. This suppresses the message-of-the-day (MOTD) text, but it also affects the list of modules that the daemon sends in response to the "rsync host::" request (due to a limitation in the rsync protocol), so omit this option if you want to request the list of modules from the daemon. --ignore-times, -I Normally rsync will skip any files that are already the same size and have the same modification timestamp. This option turns off this "quick check" behavior, causing all files to be updated. This option can be confusing compared to --ignore-existing and --ignore-non-existing in that that they cause rsync to transfer fewer files, while this option causes rsync to transfer more files. --size-only This modifies rsync's "quick check" algorithm for finding files that need to be transferred, changing it from the default of transferring files with either a changed size or a changed last-modified time to just looking for files that have changed in size. This is useful when starting to use rsync after using another mirroring system which may not preserve timestamps exactly. --modify-window=NUM, -@ When comparing two timestamps, rsync treats the timestamps as being equal if they differ by no more than the modify- window value. The default is 0, which matches just integer seconds. If you specify a negative value (and the receiver is at least version 3.1.3) then nanoseconds will also be taken into account. Specifying 1 is useful for copies to/from MS Windows FAT filesystems, because FAT represents times with a 2-second resolution (allowing times to differ from the original by up to 1 second). If you want all your transfers to default to comparing nanoseconds, you can create a ~/.popt file and put these lines in it: rsync alias -a -a@-1 rsync alias -t -t@-1 With that as the default, you'd need to specify --modify- window=0 (aka -@0) to override it and ignore nanoseconds, e.g. if you're copying between ext3 and ext4, or if the receiving rsync is older than 3.1.3. --checksum, -c This changes the way rsync checks if the files have been changed and are in need of a transfer. Without this option, rsync uses a "quick check" that (by default) checks if each file's size and time of last modification match between the sender and receiver. This option changes this to compare a 128-bit checksum for each file that has a matching size. Generating the checksums means that both sides will expend a lot of disk I/O reading all the data in the files in the transfer, so this can slow things down significantly (and this is prior to any reading that will be done to transfer changed files) The sending side generates its checksums while it is doing the file-system scan that builds the list of the available files. The receiver generates its checksums when it is scanning for changed files, and will checksum any file that has the same size as the corresponding sender's file: files with either a changed size or a changed checksum are selected for transfer. Note that rsync always verifies that each transferred file was correctly reconstructed on the receiving side by checking a whole-file checksum that is generated as the file is transferred, but that automatic after-the-transfer verification has nothing to do with this option's before- the-transfer "Does this file need to be updated?" check. The checksum used is auto-negotiated between the client and the server, but can be overridden using either the --checksum-choice (--cc) option or an environment variable that is discussed in that option's section. --archive, -a This is equivalent to -rlptgoD. It is a quick way of saying you want recursion and want to preserve almost everything. Be aware that it does not include preserving ACLs (-A), xattrs (-X), atimes (-U), crtimes (-N), nor the finding and preserving of hardlinks (-H). The only exception to the above equivalence is when --files-from is specified, in which case -r is not implied. --no-OPTION You may turn off one or more implied options by prefixing the option name with "no-". Not all positive options have a negated opposite, but a lot do, including those that can be used to disable an implied option (e.g. --no-D, --no- perms) or have different defaults in various circumstances (e.g. --no-whole-file, --no-blocking-io, --no-dirs). Every valid negated option accepts both the short and the long option name after the "no-" prefix (e.g. --no-R is the same as --no-relative). As an example, if you want to use --archive (-a) but don't want --owner (-o), instead of converting -a into -rlptgD, you can specify -a --no-o (aka --archive --no-owner). The order of the options is important: if you specify --no-r -a, the -r option would end up being turned on, the opposite of -a --no-r. Note also that the side-effects of the --files-from option are NOT positional, as it affects the default state of several options and slightly changes the meaning of -a (see the --files-from option for more details). --recursive, -r This tells rsync to copy directories recursively. See also --dirs (-d) for an option that allows the scanning of a single directory. See the --inc-recursive option for a discussion of the incremental recursion for creating the list of files to transfer. --inc-recursive, --i-r This option explicitly enables on incremental recursion when scanning for files, which is enabled by default when using the --recursive option and both sides of the transfer are running rsync 3.0.0 or newer. Incremental recursion uses much less memory than non- incremental, while also beginning the transfer more quickly (since it doesn't need to scan the entire transfer hierarchy before it starts transferring files). If no recursion is enabled in the source files, this option has no effect. Some options require rsync to know the full file list, so these options disable the incremental recursion mode. These include: o --delete-before (the old default of --delete) o --delete-after o --prune-empty-dirs o --delay-updates In order to make --delete compatible with incremental recursion, rsync 3.0.0 made --delete-during the default delete mode (which was first added in 2.6.4). One side-effect of incremental recursion is that any missing sub-directories inside a recursively-scanned directory are (by default) created prior to recursing into the sub-dirs. This earlier creation point (compared to a non-incremental recursion) allows rsync to then set the modify time of the finished directory right away (without having to delay that until a bunch of recursive copying has finished). However, these early directories don't yet have their completed mode, mtime, or ownership set -- they have more restrictive rights until the subdirectory's copying actually begins. This early-creation idiom can be avoided by using the --omit-dir-times option. Incremental recursion can be disabled using the --no-inc- recursive (--no-i-r) option. --no-inc-recursive, --no-i-r Disables the new incremental recursion algorithm of the --recursive option. This makes rsync scan the full file list before it begins to transfer files. See --inc- recursive for more info. --relative, -R Use relative paths. This means that the full path names specified on the command line are sent to the server rather than just the last parts of the filenames. This is particularly useful when you want to send several different directories at the same time. For example, if you used this command: rsync -av /foo/bar/baz.c remote:/tmp/ would create a file named baz.c in /tmp/ on the remote machine. If instead you used rsync -avR /foo/bar/baz.c remote:/tmp/ then a file named /tmp/foo/bar/baz.c would be created on the remote machine, preserving its full path. These extra path elements are called "implied directories" (i.e. the "foo" and the "foo/bar" directories in the above example). Beginning with rsync 3.0.0, rsync always sends these implied directories as real directories in the file list, even if a path element is really a symlink on the sending side. This prevents some really unexpected behaviors when copying the full path of a file that you didn't realize had a symlink in its path. If you want to duplicate a server-side symlink, include both the symlink via its path, and referent directory via its real path. If you're dealing with an older rsync on the sending side, you may need to use the --no-implied-dirs option. It is also possible to limit the amount of path information that is sent as implied directories for each path you specify. With a modern rsync on the sending side (beginning with 2.6.7), you can insert a dot and a slash into the source path, like this: rsync -avR /foo/./bar/baz.c remote:/tmp/ That would create /tmp/bar/baz.c on the remote machine. (Note that the dot must be followed by a slash, so "/foo/." would not be abbreviated.) For older rsync versions, you would need to use a chdir to limit the source path. For example, when pushing files: (cd /foo; rsync -avR bar/baz.c remote:/tmp/) (Note that the parens put the two commands into a sub- shell, so that the "cd" command doesn't remain in effect for future commands.) If you're pulling files from an older rsync, use this idiom (but only for a non-daemon transfer): rsync -avR --rsync-path="cd /foo; rsync" \ remote:bar/baz.c /tmp/ --no-implied-dirs This option affects the default behavior of the --relative option. When it is specified, the attributes of the implied directories from the source names are not included in the transfer. This means that the corresponding path elements on the destination system are left unchanged if they exist, and any missing implied directories are created with default attributes. This even allows these implied path elements to have big differences, such as being a symlink to a directory on the receiving side. For instance, if a command-line arg or a files-from entry told rsync to transfer the file "path/foo/file", the directories "path" and "path/foo" are implied when --relative is used. If "path/foo" is a symlink to "bar" on the destination system, the receiving rsync would ordinarily delete "path/foo", recreate it as a directory, and receive the file into the new directory. With --no- implied-dirs, the receiving rsync updates "path/foo/file" using the existing path elements, which means that the file ends up being created in "path/bar". Another way to accomplish this link preservation is to use the --keep- dirlinks option (which will also affect symlinks to directories in the rest of the transfer). When pulling files from an rsync older than 3.0.0, you may need to use this option if the sending side has a symlink in the path you request and you wish the implied directories to be transferred as normal directories. --backup, -b With this option, preexisting destination files are renamed as each file is transferred or deleted. You can control where the backup file goes and what (if any) suffix gets appended using the --backup-dir and --suffix options. If you don't specify --backup-dir: 1. the --omit-dir-times option will be forced on 2. the use of --delete (without --delete-excluded), causes rsync to add a "protect" filter-rule for the backup suffix to the end of all your existing filters that looks like this: -f "P *~". This rule prevents previously backed-up files from being deleted. Note that if you are supplying your own filter rules, you may need to manually insert your own exclude/protect rule somewhere higher up in the list so that it has a high enough priority to be effective (e.g. if your rules specify a trailing inclusion/exclusion of *, the auto- added rule would never be reached). --backup-dir=DIR This implies the --backup option, and tells rsync to store all backups in the specified directory on the receiving side. This can be used for incremental backups. You can additionally specify a backup suffix using the --suffix option (otherwise the files backed up in the specified directory will keep their original filenames). Note that if you specify a relative path, the backup directory will be relative to the destination directory, so you probably want to specify either an absolute path or a path that starts with "../". If an rsync daemon is the receiver, the backup dir cannot go outside the module's path hierarchy, so take extra care not to delete it or copy into it. --suffix=SUFFIX This option allows you to override the default backup suffix used with the --backup (-b) option. The default suffix is a ~ if no --backup-dir was specified, otherwise it is an empty string. --update, -u This forces rsync to skip any files which exist on the destination and have a modified time that is newer than the source file. (If an existing destination file has a modification time equal to the source file's, it will be updated if the sizes are different.) Note that this does not affect the copying of dirs, symlinks, or other special files. Also, a difference of file format between the sender and receiver is always considered to be important enough for an update, no matter what date is on the objects. In other words, if the source has a directory where the destination has a file, the transfer would occur regardless of the timestamps. This option is a TRANSFER RULE, so don't expect any exclude side effects. A caution for those that choose to combine --inplace with --update: an interrupted transfer will leave behind a partial file on the receiving side that has a very recent modified time, so re-running the transfer will probably not continue the interrupted file. As such, it is usually best to avoid combining this with --inplace unless you have implemented manual steps to handle any interrupted in-progress files. --inplace This option changes how rsync transfers a file when its data needs to be updated: instead of the default method of creating a new copy of the file and moving it into place when it is complete, rsync instead writes the updated data directly to the destination file. This has several effects: o Hard links are not broken. This means the new data will be visible through other hard links to the destination file. Moreover, attempts to copy differing source files onto a multiply-linked destination file will result in a "tug of war" with the destination data changing back and forth. o In-use binaries cannot be updated (either the OS will prevent this from happening, or binaries that attempt to swap-in their data will misbehave or crash). o The file's data will be in an inconsistent state during the transfer and will be left that way if the transfer is interrupted or if an update fails. o A file that rsync cannot write to cannot be updated. While a super user can update any file, a normal user needs to be granted write permission for the open of the file for writing to be successful. o The efficiency of rsync's delta-transfer algorithm may be reduced if some data in the destination file is overwritten before it can be copied to a position later in the file. This does not apply if you use --backup, since rsync is smart enough to use the backup file as the basis file for the transfer. WARNING: you should not use this option to update files that are being accessed by others, so be careful when choosing to use this for a copy. This option is useful for transferring large files with block-based changes or appended data, and also on systems that are disk bound, not network bound. It can also help keep a copy-on-write filesystem snapshot from diverging the entire contents of a file that only has minor changes. The option implies --partial (since an interrupted transfer does not delete the file), but conflicts with --partial-dir and --delay-updates. Prior to rsync 2.6.4 --inplace was also incompatible with --compare-dest and --link-dest. --append This special copy mode only works to efficiently update files that are known to be growing larger where any existing content on the receiving side is also known to be the same as the content on the sender. The use of --append can be dangerous if you aren't 100% sure that all the files in the transfer are shared, growing files. You should thus use filter rules to ensure that you weed out any files that do not fit this criteria. Rsync updates these growing file in-place without verifying any of the existing content in the file (it only verifies the content that it is appending). Rsync skips any files that exist on the receiving side that are not shorter than the associated file on the sending side (which means that new files are transferred). It also skips any files whose size on the sending side gets shorter during the send negotiations (rsync warns about a "diminished" file when this happens). This does not interfere with the updating of a file's non- content attributes (e.g. permissions, ownership, etc.) when the file does not need to be transferred, nor does it affect the updating of any directories or non-regular files. --append-verify This special copy mode works like --append except that all the data in the file is included in the checksum verification (making it less efficient but also potentially safer). This option can be dangerous if you aren't 100% sure that all the files in the transfer are shared, growing files. See the --append option for more details. Note: prior to rsync 3.0.0, the --append option worked like --append-verify, so if you are interacting with an older rsync (or the transfer is using a protocol prior to 30), specifying either append option will initiate an --append-verify transfer. --dirs, -d Tell the sending side to include any directories that are encountered. Unlike --recursive, a directory's contents are not copied unless the directory name specified is "." or ends with a trailing slash (e.g. ".", "dir/.", "dir/", etc.). Without this option or the --recursive option, rsync will skip all directories it encounters (and output a message to that effect for each one). If you specify both --dirs and --recursive, --recursive takes precedence. The --dirs option is implied by the --files-from option or the --list-only option (including an implied --list-only usage) if --recursive wasn't specified (so that directories are seen in the listing). Specify --no-dirs (or --no-d) if you want to turn this off. There is also a backward-compatibility helper option, --old-dirs (--old-d) that tells rsync to use a hack of -r --exclude='/*/*' to get an older rsync to list a single directory without recursing. --mkpath Create all missing path components of the destination path. By default, rsync allows only the final component of the destination path to not exist, which is an attempt to help you to validate your destination path. With this option, rsync creates all the missing destination-path components, just as if mkdir -p $DEST_PATH had been run on the receiving side. When specifying a destination path, including a trailing slash ensures that the whole path is treated as directory names to be created, even when the file list has a single item. See the COPYING TO A DIFFERENT NAME section for full details on how rsync decides if a final destination-path component should be created as a directory or not. If you would like the newly-created destination dirs to match the dirs on the sending side, you should be using --relative (-R) instead of --mkpath. For instance, the following two commands result in the same destination tree, but only the second command ensures that the "some/extra/path" components match the dirs on the sending side: rsync -ai --mkpath host:some/extra/path/*.c some/extra/path/ rsync -aiR host:some/extra/path/*.c ./ --links, -l Add symlinks to the transferred files instead of noisily ignoring them with a "non-regular file" warning for each symlink encountered. You can alternately silence the warning by specifying --info=nonreg0. The default handling of symlinks is to recreate each symlink's unchanged value on the receiving side. See the SYMBOLIC LINKS section for multi-option info. --copy-links, -L The sender transforms each symlink encountered in the transfer into the referent item, following the symlink chain to the file or directory that it references. If a symlink chain is broken, an error is output and the file is dropped from the transfer. This option supersedes any other options that affect symlinks in the transfer, since there are no symlinks left in the transfer. This option does not change the handling of existing symlinks on the receiving side, unlike versions of rsync prior to 2.6.3 which had the side-effect of telling the receiving side to also follow symlinks. A modern rsync won't forward this option to a remote receiver (since only the sender needs to know about it), so this caveat should only affect someone using an rsync client older than 2.6.7 (which is when -L stopped being forwarded to the receiver). See the --keep-dirlinks (-K) if you need a symlink to a directory to be treated as a real directory on the receiving side. See the SYMBOLIC LINKS section for multi-option info. --copy-unsafe-links This tells rsync to copy the referent of symbolic links that point outside the copied tree. Absolute symlinks are also treated like ordinary files, and so are any symlinks in the source path itself when --relative is used. Note that the cut-off point is the top of the transfer, which is the part of the path that rsync isn't mentioning in the verbose output. If you copy "/src/subdir" to "/dest/" then the "subdir" directory is a name inside the transfer tree, not the top of the transfer (which is /src) so it is legal for created relative symlinks to refer to other names inside the /src and /dest directories. If you instead copy "/src/subdir/" (with a trailing slash) to "/dest/subdir" that would not allow symlinks to any files outside of "subdir". Note that safe symlinks are only copied if --links was also specified or implied. The --copy-unsafe-links option has no extra effect when combined with --copy-links. See the SYMBOLIC LINKS section for multi-option info. --safe-links This tells the receiving rsync to ignore any symbolic links in the transfer which point outside the copied tree. All absolute symlinks are also ignored. Since this ignoring is happening on the receiving side, it will still be effective even when the sending side has munged symlinks (when it is using --munge-links). It also affects deletions, since the file being present in the transfer prevents any matching file on the receiver from being deleted when the symlink is deemed to be unsafe and is skipped. This option must be combined with --links (or --archive) to have any symlinks in the transfer to conditionally ignore. Its effect is superseded by --copy-unsafe-links. Using this option in conjunction with --relative may give unexpected results. See the SYMBOLIC LINKS section for multi-option info. --munge-links This option affects just one side of the transfer and tells rsync to munge symlink values when it is receiving files or unmunge symlink values when it is sending files. The munged values make the symlinks unusable on disk but allows the original contents of the symlinks to be recovered. The server-side rsync often enables this option without the client's knowledge, such as in an rsync daemon's configuration file or by an option given to the rrsync (restricted rsync) script. When specified on the client side, specify the option normally if it is the client side that has/needs the munged symlinks, or use -M--munge-links to give the option to the server when it has/needs the munged symlinks. Note that on a local transfer, the client is the sender, so specifying the option directly unmunges symlinks while specifying it as a remote option munges symlinks. This option has no effect when sent to a daemon via --remote-option because the daemon configures whether it wants munged symlinks via its "munge symlinks" parameter. The symlink value is munged/unmunged once it is in the transfer, so any option that transforms symlinks into non- symlinks occurs prior to the munging/unmunging except for --safe-links, which is a choice that the receiver makes, so it bases its decision on the munged/unmunged value. This does mean that if a receiver has munging enabled, that using --safe-links will cause all symlinks to be ignored (since they are all absolute). The method that rsync uses to munge the symlinks is to prefix each one's value with the string "/rsyncd-munged/". This prevents the links from being used as long as the directory does not exist. When this option is enabled, rsync will refuse to run if that path is a directory or a symlink to a directory (though it only checks at startup). See also the "munge-symlinks" python script in the support directory of the source code for a way to munge/unmunge one or more symlinks in-place. --copy-dirlinks, -k This option causes the sending side to treat a symlink to a directory as though it were a real directory. This is useful if you don't want symlinks to non-directories to be affected, as they would be using --copy-links. Without this option, if the sending side has replaced a directory with a symlink to a directory, the receiving side will delete anything that is in the way of the new symlink, including a directory hierarchy (as long as --force or --delete is in effect). See also --keep-dirlinks for an analogous option for the receiving side. --copy-dirlinks applies to all symlinks to directories in the source. If you want to follow only a few specified symlinks, a trick you can use is to pass them as additional source args with a trailing slash, using --relative to make the paths match up right. For example: rsync -r --relative src/./ src/./follow-me/ dest/ This works because rsync calls lstat(2) on the source arg as given, and the trailing slash makes lstat(2) follow the symlink, giving rise to a directory in the file-list which overrides the symlink found during the scan of "src/./". See the SYMBOLIC LINKS section for multi-option info. --keep-dirlinks, -K This option causes the receiving side to treat a symlink to a directory as though it were a real directory, but only if it matches a real directory from the sender. Without this option, the receiver's symlink would be deleted and replaced with a real directory. For example, suppose you transfer a directory "foo" that contains a file "file", but "foo" is a symlink to directory "bar" on the receiver. Without --keep-dirlinks, the receiver deletes symlink "foo", recreates it as a directory, and receives the file into the new directory. With --keep-dirlinks, the receiver keeps the symlink and "file" ends up in "bar". One note of caution: if you use --keep-dirlinks, you must trust all the symlinks in the copy or enable the --munge- links option on the receiving side! If it is possible for an untrusted user to create their own symlink to any real directory, the user could then (on a subsequent copy) replace the symlink with a real directory and affect the content of whatever directory the symlink references. For backup copies, you are better off using something like a bind mount instead of a symlink to modify your receiving hierarchy. See also --copy-dirlinks for an analogous option for the sending side. See the SYMBOLIC LINKS section for multi-option info. --hard-links, -H This tells rsync to look for hard-linked files in the source and link together the corresponding files on the destination. Without this option, hard-linked files in the source are treated as though they were separate files. This option does NOT necessarily ensure that the pattern of hard links on the destination exactly matches that on the source. Cases in which the destination may end up with extra hard links include the following: o If the destination contains extraneous hard-links (more linking than what is present in the source file list), the copying algorithm will not break them explicitly. However, if one or more of the paths have content differences, the normal file- update process will break those extra links (unless you are using the --inplace option). o If you specify a --link-dest directory that contains hard links, the linking of the destination files against the --link-dest files can cause some paths in the destination to become linked together due to the --link-dest associations. Note that rsync can only detect hard links between files that are inside the transfer set. If rsync updates a file that has extra hard-link connections to files outside the transfer, that linkage will be broken. If you are tempted to use the --inplace option to avoid this breakage, be very careful that you know how your files are being updated so that you are certain that no unintended changes happen due to lingering hard links (and see the --inplace option for more caveats). If incremental recursion is active (see --inc-recursive), rsync may transfer a missing hard-linked file before it finds that another link for that contents exists elsewhere in the hierarchy. This does not affect the accuracy of the transfer (i.e. which files are hard-linked together), just its efficiency (i.e. copying the data for a new, early copy of a hard-linked file that could have been found later in the transfer in another member of the hard- linked set of files). One way to avoid this inefficiency is to disable incremental recursion using the --no-inc- recursive option. --perms, -p This option causes the receiving rsync to set the destination permissions to be the same as the source permissions. (See also the --chmod option for a way to modify what rsync considers to be the source permissions.) When this option is off, permissions are set as follows: o Existing files (including updated files) retain their existing permissions, though the --executability option might change just the execute permission for the file. o New files get their "normal" permission bits set to the source file's permissions masked with the receiving directory's default permissions (either the receiving process's umask, or the permissions specified via the destination directory's default ACL), and their special permission bits disabled except in the case where a new directory inherits a setgid bit from its parent directory. Thus, when --perms and --executability are both disabled, rsync's behavior is the same as that of other file-copy utilities, such as cp(1) and tar(1). In summary: to give destination files (both old and new) the source permissions, use --perms. To give new files the destination-default permissions (while leaving existing files unchanged), make sure that the --perms option is off and use --chmod=ugo=rwX (which ensures that all non-masked bits get enabled). If you'd care to make this latter behavior easier to type, you could define a popt alias for it, such as putting this line in the file ~/.popt (the following defines the -Z option, and includes --no-g to use the default group of the destination dir): rsync alias -Z --no-p --no-g --chmod=ugo=rwX You could then use this new option in a command such as this one: rsync -avZ src/ dest/ (Caveat: make sure that -a does not follow -Z, or it will re-enable the two --no-* options mentioned above.) The preservation of the destination's setgid bit on newly- created directories when --perms is off was added in rsync 2.6.7. Older rsync versions erroneously preserved the three special permission bits for newly-created files when --perms was off, while overriding the destination's setgid bit setting on a newly-created directory. Default ACL observance was added to the ACL patch for rsync 2.6.7, so older (or non-ACL-enabled) rsyncs use the umask even if default ACLs are present. (Keep in mind that it is the version of the receiving rsync that affects these behaviors.) --executability, -E This option causes rsync to preserve the executability (or non-executability) of regular files when --perms is not enabled. A regular file is considered to be executable if at least one 'x' is turned on in its permissions. When an existing destination file's executability differs from that of the corresponding source file, rsync modifies the destination file's permissions as follows: o To make a file non-executable, rsync turns off all its 'x' permissions. o To make a file executable, rsync turns on each 'x' permission that has a corresponding 'r' permission enabled. If --perms is enabled, this option is ignored. --acls, -A This option causes rsync to update the destination ACLs to be the same as the source ACLs. The option also implies --perms. The source and destination systems must have compatible ACL entries for this option to work properly. See the --fake-super option for a way to backup and restore ACLs that are not compatible. --xattrs, -X This option causes rsync to update the destination extended attributes to be the same as the source ones. For systems that support extended-attribute namespaces, a copy being done by a super-user copies all namespaces except system.*. A normal user only copies the user.* namespace. To be able to backup and restore non-user namespaces as a normal user, see the --fake-super option. The above name filtering can be overridden by using one or more filter options with the x modifier. When you specify an xattr-affecting filter rule, rsync requires that you do your own system/user filtering, as well as any additional filtering for what xattr names are copied and what names are allowed to be deleted. For example, to skip the system namespace, you could specify: --filter='-x system.*' To skip all namespaces except the user namespace, you could specify a negated-user match: --filter='-x! user.*' To prevent any attributes from being deleted, you could specify a receiver-only rule that excludes all names: --filter='-xr *' Note that the -X option does not copy rsync's special xattr values (e.g. those used by --fake-super) unless you repeat the option (e.g. -XX). This "copy all xattrs" mode cannot be used with --fake-super. --chmod=CHMOD This option tells rsync to apply one or more comma- separated "chmod" modes to the permission of the files in the transfer. The resulting value is treated as though it were the permissions that the sending side supplied for the file, which means that this option can seem to have no effect on existing files if --perms is not enabled. In addition to the normal parsing rules specified in the chmod(1) manpage, you can specify an item that should only apply to a directory by prefixing it with a 'D', or specify an item that should only apply to a file by prefixing it with a 'F'. For example, the following will ensure that all directories get marked set-gid, that no files are other-writable, that both are user-writable and group-writable, and that both have consistent executability across all bits: --chmod=Dg+s,ug+w,Fo-w,+X Using octal mode numbers is also allowed: --chmod=D2775,F664 It is also legal to specify multiple --chmod options, as each additional option is just appended to the list of changes to make. See the --perms and --executability options for how the resulting permission value can be applied to the files in the transfer. --owner, -o This option causes rsync to set the owner of the destination file to be the same as the source file, but only if the receiving rsync is being run as the super-user (see also the --super and --fake-super options). Without this option, the owner of new and/or transferred files are set to the invoking user on the receiving side. The preservation of ownership will associate matching names by default, but may fall back to using the ID number in some circumstances (see also the --numeric-ids option for a full discussion). --group, -g This option causes rsync to set the group of the destination file to be the same as the source file. If the receiving program is not running as the super-user (or if --no-super was specified), only groups that the invoking user on the receiving side is a member of will be preserved. Without this option, the group is set to the default group of the invoking user on the receiving side. The preservation of group information will associate matching names by default, but may fall back to using the ID number in some circumstances (see also the --numeric- ids option for a full discussion). --devices This option causes rsync to transfer character and block device files to the remote system to recreate these devices. If the receiving rsync is not being run as the super-user, rsync silently skips creating the device files (see also the --super and --fake-super options). By default, rsync generates a "non-regular file" warning for each device file encountered when this option is not set. You can silence the warning by specifying --info=nonreg0. --specials This option causes rsync to transfer special files, such as named sockets and fifos. If the receiving rsync is not being run as the super-user, rsync silently skips creating the special files (see also the --super and --fake-super options). By default, rsync generates a "non-regular file" warning for each special file encountered when this option is not set. You can silence the warning by specifying --info=nonreg0. -D The -D option is equivalent to "--devices --specials". --copy-devices This tells rsync to treat a device on the sending side as a regular file, allowing it to be copied to a normal destination file (or another device if --write-devices was also specified). This option is refused by default by an rsync daemon. --write-devices This tells rsync to treat a device on the receiving side as a regular file, allowing the writing of file data into a device. This option implies the --inplace option. Be careful using this, as you should know what devices are present on the receiving side of the transfer, especially when running rsync as root. This option is refused by default by an rsync daemon. --times, -t This tells rsync to transfer modification times along with the files and update them on the remote system. Note that if this option is not used, the optimization that excludes files that have not been modified cannot be effective; in other words, a missing -t (or -a) will cause the next transfer to behave as if it used --ignore-times (-I), causing all files to be updated (though rsync's delta- transfer algorithm will make the update fairly efficient if the files haven't actually changed, you're much better off using -t). A modern rsync that is using transfer protocol 30 or 31 conveys a modify time using up to 8-bytes. If rsync is forced to speak an older protocol (perhaps due to the remote rsync being older than 3.0.0) a modify time is conveyed using 4-bytes. Prior to 3.2.7, these shorter values could convey a date range of 13-Dec-1901 to 19-Jan-2038. Beginning with 3.2.7, these 4-byte values now convey a date range of 1-Jan-1970 to 7-Feb-2106. If you have files dated older than 1970, make sure your rsync executables are upgraded so that the full range of dates can be conveyed. --atimes, -U This tells rsync to set the access (use) times of the destination files to the same value as the source files. If repeated, it also sets the --open-noatime option, which can help you to make the sending and receiving systems have the same access times on the transferred files without needing to run rsync an extra time after a file is transferred. Note that some older rsync versions (prior to 3.2.0) may have been built with a pre-release --atimes patch that does not imply --open-noatime when this option is repeated. --open-noatime This tells rsync to open files with the O_NOATIME flag (on systems that support it) to avoid changing the access time of the files that are being transferred. If your OS does not support the O_NOATIME flag then rsync will silently ignore this option. Note also that some filesystems are mounted to avoid updating the atime on read access even without the O_NOATIME flag being set. --crtimes, -N, This tells rsync to set the create times (newness) of the destination files to the same value as the source files. --omit-dir-times, -O This tells rsync to omit directories when it is preserving modification, access, and create times. If NFS is sharing the directories on the receiving side, it is a good idea to use -O. This option is inferred if you use --backup without --backup-dir. This option also has the side-effect of avoiding early creation of missing sub-directories when incremental recursion is enabled, as discussed in the --inc-recursive section. --omit-link-times, -J This tells rsync to omit symlinks when it is preserving modification, access, and create times. --super This tells the receiving side to attempt super-user activities even if the receiving rsync wasn't run by the super-user. These activities include: preserving users via the --owner option, preserving all groups (not just the current user's groups) via the --group option, and copying devices via the --devices option. This is useful for systems that allow such activities without being the super-user, and also for ensuring that you will get errors if the receiving side isn't being run as the super-user. To turn off super-user activities, the super-user can use --no-super. --fake-super When this option is enabled, rsync simulates super-user activities by saving/restoring the privileged attributes via special extended attributes that are attached to each file (as needed). This includes the file's owner and group (if it is not the default), the file's device info (device & special files are created as empty text files), and any permission bits that we won't allow to be set on the real file (e.g. the real file gets u-s,g-s,o-t for safety) or that would limit the owner's access (since the real super-user can always access/change a file, the files we create can always be accessed/changed by the creating user). This option also handles ACLs (if --acls was specified) and non-user extended attributes (if --xattrs was specified). This is a good way to backup data without using a super- user, and to store ACLs from incompatible systems. The --fake-super option only affects the side where the option is used. To affect the remote side of a remote- shell connection, use the --remote-option (-M) option: rsync -av -M--fake-super /src/ host:/dest/ For a local copy, this option affects both the source and the destination. If you wish a local copy to enable this option just for the destination files, specify -M--fake- super. If you wish a local copy to enable this option just for the source files, combine --fake-super with -M--super. This option is overridden by both --super and --no-super. See also the fake super setting in the daemon's rsyncd.conf file. --sparse, -S Try to handle sparse files efficiently so they take up less space on the destination. If combined with --inplace the file created might not end up with sparse blocks with some combinations of kernel version and/or filesystem type. If --whole-file is in effect (e.g. for a local copy) then it will always work because rsync truncates the file prior to writing out the updated version. Note that versions of rsync older than 3.1.3 will reject the combination of --sparse and --inplace. --preallocate This tells the receiver to allocate each destination file to its eventual size before writing data to the file. Rsync will only use the real filesystem-level preallocation support provided by Linux's fallocate(2) system call or Cygwin's posix_fallocate(3), not the slow glibc implementation that writes a null byte into each block. Without this option, larger files may not be entirely contiguous on the filesystem, but with this option rsync will probably copy more slowly. If the destination is not an extent-supporting filesystem (such as ext4, xfs, NTFS, etc.), this option may have no positive effect at all. If combined with --sparse, the file will only have sparse blocks (as opposed to allocated sequences of null bytes) if the kernel version and filesystem type support creating holes in the allocated data. --dry-run, -n This makes rsync perform a trial run that doesn't make any changes (and produces mostly the same output as a real run). It is most commonly used in combination with the --verbose (-v) and/or --itemize-changes (-i) options to see what an rsync command is going to do before one actually runs it. The output of --itemize-changes is supposed to be exactly the same on a dry run and a subsequent real run (barring intentional trickery and system call failures); if it isn't, that's a bug. Other output should be mostly unchanged, but may differ in some areas. Notably, a dry run does not send the actual data for file transfers, so --progress has no effect, the "bytes sent", "bytes received", "literal data", and "matched data" statistics are too small, and the "speedup" value is equivalent to a run where no file transfers were needed. --whole-file, -W This option disables rsync's delta-transfer algorithm, which causes all transferred files to be sent whole. The transfer may be faster if this option is used when the bandwidth between the source and destination machines is higher than the bandwidth to disk (especially when the "disk" is actually a networked filesystem). This is the default when both the source and destination are specified as local paths, but only if no batch-writing option is in effect. --no-whole-file, --no-W Disable whole-file updating when it is enabled by default for a local transfer. This usually slows rsync down, but it can be useful if you are trying to minimize the writes to the destination file (if combined with --inplace) or for testing the checksum-based update algorithm. See also the --whole-file option. --checksum-choice=STR, --cc=STR This option overrides the checksum algorithms. If one algorithm name is specified, it is used for both the transfer checksums and (assuming --checksum is specified) the pre-transfer checksums. If two comma-separated names are supplied, the first name affects the transfer checksums, and the second name affects the pre-transfer checksums (-c). The checksum options that you may be able to use are: o auto (the default automatic choice) o xxh128 o xxh3 o xxh64 (aka xxhash) o md5 o md4 o sha1 o none Run rsync --version to see the default checksum list compiled into your version (which may differ from the list above). If "none" is specified for the first (or only) name, the --whole-file option is forced on and no checksum verification is performed on the transferred data. If "none" is specified for the second (or only) name, the --checksum option cannot be used. The "auto" option is the default, where rsync bases its algorithm choice on a negotiation between the client and the server as follows: When both sides of the transfer are at least 3.2.0, rsync chooses the first algorithm in the client's list of choices that is also in the server's list of choices. If no common checksum choice is found, rsync exits with an error. If the remote rsync is too old to support checksum negotiation, a value is chosen based on the protocol version (which chooses between MD5 and various flavors of MD4 based on protocol age). The default order can be customized by setting the environment variable RSYNC_CHECKSUM_LIST to a space- separated list of acceptable checksum names. If the string contains a "&" character, it is separated into the "client string & server string", otherwise the same string applies to both. If the string (or string portion) contains no non-whitespace characters, the default checksum list is used. This method does not allow you to specify the transfer checksum separately from the pre- transfer checksum, and it discards "auto" and all unknown checksum names. A list with only invalid names results in a failed negotiation. The use of the --checksum-choice option overrides this environment list. --one-file-system, -x This tells rsync to avoid crossing a filesystem boundary when recursing. This does not limit the user's ability to specify items to copy from multiple filesystems, just rsync's recursion through the hierarchy of each directory that the user specified, and also the analogous recursion on the receiving side during deletion. Also keep in mind that rsync treats a "bind" mount to the same device as being on the same filesystem. If this option is repeated, rsync omits all mount-point directories from the copy. Otherwise, it includes an empty directory at each mount-point it encounters (using the attributes of the mounted directory because those of the underlying mount-point directory are inaccessible). If rsync has been told to collapse symlinks (via --copy- links or --copy-unsafe-links), a symlink to a directory on another device is treated like a mount-point. Symlinks to non-directories are unaffected by this option. --ignore-non-existing, --existing This tells rsync to skip creating files (including directories) that do not exist yet on the destination. If this option is combined with the --ignore-existing option, no files will be updated (which can be useful if all you want to do is delete extraneous files). This option is a TRANSFER RULE, so don't expect any exclude side effects. --ignore-existing This tells rsync to skip updating files that already exist on the destination (this does not ignore existing directories, or nothing would get done). See also --ignore-non-existing. This option is a TRANSFER RULE, so don't expect any exclude side effects. This option can be useful for those doing backups using the --link-dest option when they need to continue a backup run that got interrupted. Since a --link-dest run is copied into a new directory hierarchy (when it is used properly), using [--ignore-existing will ensure that the already-handled files don't get tweaked (which avoids a change in permissions on the hard-linked files). This does mean that this option is only looking at the existing files in the destination hierarchy itself. When --info=skip2 is used rsync will output "FILENAME exists (INFO)" messages where the INFO indicates one of "type change", "sum change" (requires -c), "file change" (based on the quick check), "attr change", or "uptodate". Using --info=skip1 (which is also implied by 2 -v options) outputs the exists message without the INFO suffix. --remove-source-files This tells rsync to remove from the sending side the files (meaning non-directories) that are a part of the transfer and have been successfully duplicated on the receiving side. Note that you should only use this option on source files that are quiescent. If you are using this to move files that show up in a particular directory over to another host, make sure that the finished files get renamed into the source directory, not directly written into it, so that rsync can't possibly transfer a file that is not yet fully written. If you can't first write the files into a different directory, you should use a naming idiom that lets rsync avoid transferring files that are not yet finished (e.g. name the file "foo.new" when it is written, rename it to "foo" when it is done, and then use the option --exclude='*.new' for the rsync transfer). Starting with 3.1.0, rsync will skip the sender-side removal (and output an error) if the file's size or modify time has not stayed unchanged. Starting with 3.2.6, a local rsync copy will ensure that the sender does not remove a file the receiver just verified, such as when the user accidentally makes the source and destination directory the same path. --delete This tells rsync to delete extraneous files from the receiving side (ones that aren't on the sending side), but only for the directories that are being synchronized. You must have asked rsync to send the whole directory (e.g. "dir" or "dir/") without using a wildcard for the directory's contents (e.g. "dir/*") since the wildcard is expanded by the shell and rsync thus gets a request to transfer individual files, not the files' parent directory. Files that are excluded from the transfer are also excluded from being deleted unless you use the --delete-excluded option or mark the rules as only matching on the sending side (see the include/exclude modifiers in the FILTER RULES section). Prior to rsync 2.6.7, this option would have no effect unless --recursive was enabled. Beginning with 2.6.7, deletions will also occur when --dirs (-d) is enabled, but only for directories whose contents are being copied. This option can be dangerous if used incorrectly! It is a very good idea to first try a run using the --dry-run (-n) option to see what files are going to be deleted. If the sending side detects any I/O errors, then the deletion of any files at the destination will be automatically disabled. This is to prevent temporary filesystem failures (such as NFS errors) on the sending side from causing a massive deletion of files on the destination. You can override this with the --ignore- errors option. The --delete option may be combined with one of the --delete-WHEN options without conflict, as well as --delete-excluded. However, if none of the --delete-WHEN options are specified, rsync will choose the --delete- during algorithm when talking to rsync 3.0.0 or newer, or the --delete-before algorithm when talking to an older rsync. See also --delete-delay and --delete-after. --delete-before Request that the file-deletions on the receiving side be done before the transfer starts. See --delete (which is implied) for more details on file-deletion. Deleting before the transfer is helpful if the filesystem is tight for space and removing extraneous files would help to make the transfer possible. However, it does introduce a delay before the start of the transfer, and this delay might cause the transfer to timeout (if --timeout was specified). It also forces rsync to use the old, non-incremental recursion algorithm that requires rsync to scan all the files in the transfer into memory at once (see --recursive). --delete-during, --del Request that the file-deletions on the receiving side be done incrementally as the transfer happens. The per- directory delete scan is done right before each directory is checked for updates, so it behaves like a more efficient --delete-before, including doing the deletions prior to any per-directory filter files being updated. This option was first added in rsync version 2.6.4. See --delete (which is implied) for more details on file- deletion. --delete-delay Request that the file-deletions on the receiving side be computed during the transfer (like --delete-during), and then removed after the transfer completes. This is useful when combined with --delay-updates and/or --fuzzy, and is more efficient than using --delete-after (but can behave differently, since --delete-after computes the deletions in a separate pass after all updates are done). If the number of removed files overflows an internal buffer, a temporary file will be created on the receiving side to hold the names (it is removed while open, so you shouldn't see it during the transfer). If the creation of the temporary file fails, rsync will try to fall back to using --delete-after (which it cannot do if --recursive is doing an incremental scan). See --delete (which is implied) for more details on file-deletion. --delete-after Request that the file-deletions on the receiving side be done after the transfer has completed. This is useful if you are sending new per-directory merge files as a part of the transfer and you want their exclusions to take effect for the delete phase of the current transfer. It also forces rsync to use the old, non-incremental recursion algorithm that requires rsync to scan all the files in the transfer into memory at once (see --recursive). See --delete (which is implied) for more details on file- deletion. See also the --delete-delay option that might be a faster choice for those that just want the deletions to occur at the end of the transfer. --delete-excluded This option turns any unqualified exclude/include rules into server-side rules that do not affect the receiver's deletions. By default, an exclude or include has both a server-side effect (to "hide" and "show" files when building the server's file list) and a receiver-side effect (to "protect" and "risk" files when deletions are occurring). Any rule that has no modifier to specify what sides it is executed on will be instead treated as if it were a server-side rule only, avoiding any "protect" effects of the rules. A rule can still apply to both sides even with this option specified if the rule is given both the sender & receiver modifier letters (e.g., -f'-sr foo'). Receiver-side protect/risk rules can also be explicitly specified to limit the deletions. This saves you from having to edit a bunch of -f'- foo' rules into -f'-s foo' (aka -f'H foo') rules (not to mention the corresponding includes). See the FILTER RULES section for more information. See --delete (which is implied) for more details on deletion. --ignore-missing-args When rsync is first processing the explicitly requested source files (e.g. command-line arguments or --files-from entries), it is normally an error if the file cannot be found. This option suppresses that error, and does not try to transfer the file. This does not affect subsequent vanished-file errors if a file was initially found to be present and later is no longer there. --delete-missing-args This option takes the behavior of the (implied) --ignore- missing-args option a step farther: each missing arg will become a deletion request of the corresponding destination file on the receiving side (should it exist). If the destination file is a non-empty directory, it will only be successfully deleted if --force or --delete are in effect. Other than that, this option is independent of any other type of delete processing. The missing source files are represented by special file- list entries which display as a "*missing" entry in the --list-only output. --ignore-errors Tells --delete to go ahead and delete files even when there are I/O errors. --force This option tells rsync to delete a non-empty directory when it is to be replaced by a non-directory. This is only relevant if deletions are not active (see --delete for details). Note for older rsync versions: --force used to still be required when using --delete-after, and it used to be non- functional unless the --recursive option was also enabled. --max-delete=NUM This tells rsync not to delete more than NUM files or directories. If that limit is exceeded, all further deletions are skipped through the end of the transfer. At the end, rsync outputs a warning (including a count of the skipped deletions) and exits with an error code of 25 (unless some more important error condition also occurred). Beginning with version 3.0.0, you may specify --max- delete=0 to be warned about any extraneous files in the destination without removing any of them. Older clients interpreted this as "unlimited", so if you don't know what version the client is, you can use the less obvious --max- delete=-1 as a backward-compatible way to specify that no deletions be allowed (though really old versions didn't warn when the limit was exceeded). --max-size=SIZE This tells rsync to avoid transferring any file that is larger than the specified SIZE. A numeric value can be suffixed with a string to indicate the numeric units or left unqualified to specify bytes. Feel free to use a fractional value along with the units, such as --max- size=1.5m. This option is a TRANSFER RULE, so don't expect any exclude side effects. The first letter of a units string can be B (bytes), K (kilo), M (mega), G (giga), T (tera), or P (peta). If the string is a single char or has "ib" added to it (e.g. "G" or "GiB") then the units are multiples of 1024. If you use a two-letter suffix that ends with a "B" (e.g. "kb") then you get units that are multiples of 1000. The string's letters can be any mix of upper and lower-case that you want to use. Finally, if the string ends with either "+1" or "-1", it is offset by one byte in the indicated direction. The largest possible value is usually 8192P-1. Examples: --max-size=1.5mb-1 is 1499999 bytes, and --max- size=2g+1 is 2147483649 bytes. Note that rsync versions prior to 3.1.0 did not allow --max-size=0. --min-size=SIZE This tells rsync to avoid transferring any file that is smaller than the specified SIZE, which can help in not transferring small, junk files. See the --max-size option for a description of SIZE and other info. Note that rsync versions prior to 3.1.0 did not allow --min-size=0. --max-alloc=SIZE By default rsync limits an individual malloc/realloc to about 1GB in size. For most people this limit works just fine and prevents a protocol error causing rsync to request massive amounts of memory. However, if you have many millions of files in a transfer, a large amount of server memory, and you don't want to split up your transfer into multiple parts, you can increase the per- allocation limit to something larger and rsync will consume more memory. Keep in mind that this is not a limit on the total size of allocated memory. It is a sanity-check value for each individual allocation. See the --max-size option for a description of how SIZE can be specified. The default suffix if none is given is bytes. Beginning in 3.2.3, a value of 0 specifies no limit. You can set a default value using the environment variable RSYNC_MAX_ALLOC using the same SIZE values as supported by this option. If the remote rsync doesn't understand the --max-alloc option, you can override an environmental value by specifying --max-alloc=1g, which will make rsync avoid sending the option to the remote side (because "1G" is the default). --block-size=SIZE, -B This forces the block size used in rsync's delta-transfer algorithm to a fixed value. It is normally selected based on the size of each file being updated. See the technical report for details. Beginning in 3.2.3 the SIZE can be specified with a suffix as detailed in the --max-size option. Older versions only accepted a byte count. --rsh=COMMAND, -e This option allows you to choose an alternative remote shell program to use for communication between the local and remote copies of rsync. Typically, rsync is configured to use ssh by default, but you may prefer to use rsh on a local network. If this option is used with [user@]host::module/path, then the remote shell COMMAND will be used to run an rsync daemon on the remote host, and all data will be transmitted through that remote shell connection, rather than through a direct socket connection to a running rsync daemon on the remote host. See the USING RSYNC-DAEMON FEATURES VIA A REMOTE-SHELL CONNECTION section above. Beginning with rsync 3.2.0, the RSYNC_PORT environment variable will be set when a daemon connection is being made via a remote-shell connection. It is set to 0 if the default daemon port is being assumed, or it is set to the value of the rsync port that was specified via either the --port option or a non-empty port value in an rsync:// URL. This allows the script to discern if a non-default port is being requested, allowing for things such as an SSL or stunnel helper script to connect to a default or alternate port. Command-line arguments are permitted in COMMAND provided that COMMAND is presented to rsync as a single argument. You must use spaces (not tabs or other whitespace) to separate the command and args from each other, and you can use single- and/or double-quotes to preserve spaces in an argument (but not backslashes). Note that doubling a single-quote inside a single-quoted string gives you a single-quote; likewise for double-quotes (though you need to pay attention to which quotes your shell is parsing and which quotes rsync is parsing). Some examples: -e 'ssh -p 2234' -e 'ssh -o "ProxyCommand nohup ssh firewall nc -w1 %h %p"' (Note that ssh users can alternately customize site- specific connect options in their .ssh/config file.) You can also choose the remote shell program using the RSYNC_RSH environment variable, which accepts the same range of values as -e. See also the --blocking-io option which is affected by this option. --rsync-path=PROGRAM Use this to specify what program is to be run on the remote machine to start-up rsync. Often used when rsync is not in the default remote-shell's path (e.g. --rsync- path=/usr/local/bin/rsync). Note that PROGRAM is run with the help of a shell, so it can be any program, script, or command sequence you'd care to run, so long as it does not corrupt the standard-in & standard-out that rsync is using to communicate. One tricky example is to set a different default directory on the remote machine for use with the --relative option. For instance: rsync -avR --rsync-path="cd /a/b && rsync" host:c/d /e/ --remote-option=OPTION, -M This option is used for more advanced situations where you want certain effects to be limited to one side of the transfer only. For instance, if you want to pass --log- file=FILE and --fake-super to the remote system, specify it like this: rsync -av -M --log-file=foo -M--fake-super src/ dest/ If you want to have an option affect only the local side of a transfer when it normally affects both sides, send its negation to the remote side. Like this: rsync -av -x -M--no-x src/ dest/ Be cautious using this, as it is possible to toggle an option that will cause rsync to have a different idea about what data to expect next over the socket, and that will make it fail in a cryptic fashion. Note that you should use a separate -M option for each remote option you want to pass. On older rsync versions, the presence of any spaces in the remote-option arg could cause it to be split into separate remote args, but this requires the use of --old-args in a modern rsync. When performing a local transfer, the "local" side is the sender and the "remote" side is the receiver. Note some versions of the popt option-parsing library have a bug in them that prevents you from using an adjacent arg with an equal in it next to a short option letter (e.g. -M--log-file=/tmp/foo). If this bug affects your version of popt, you can use the version of popt that is included with rsync. --cvs-exclude, -C This is a useful shorthand for excluding a broad range of files that you often don't want to transfer between systems. It uses a similar algorithm to CVS to determine if a file should be ignored. The exclude list is initialized to exclude the following items (these initial items are marked as perishable -- see the FILTER RULES section): RCS SCCS CVS CVS.adm RCSLOG cvslog.* tags TAGS .make.state .nse_depinfo *~ #* .#* ,* _$* *$ *.old *.bak *.BAK *.orig *.rej .del-* *.a *.olb *.o *.obj *.so *.exe *.Z *.elc *.ln core .svn/ .git/ .hg/ .bzr/ then, files listed in a $HOME/.cvsignore are added to the list and any files listed in the CVSIGNORE environment variable (all cvsignore names are delimited by whitespace). Finally, any file is ignored if it is in the same directory as a .cvsignore file and matches one of the patterns listed therein. Unlike rsync's filter/exclude files, these patterns are split on whitespace. See the cvs(1) manual for more information. If you're combining -C with your own --filter rules, you should note that these CVS excludes are appended at the end of your own rules, regardless of where the -C was placed on the command-line. This makes them a lower priority than any rules you specified explicitly. If you want to control where these CVS excludes get inserted into your filter rules, you should omit the -C as a command- line option and use a combination of --filter=:C and --filter=-C (either on your command-line or by putting the ":C" and "-C" rules into a filter file with your other rules). The first option turns on the per-directory scanning for the .cvsignore file. The second option does a one-time import of the CVS excludes mentioned above. --filter=RULE, -f This option allows you to add rules to selectively exclude certain files from the list of files to be transferred. This is most useful in combination with a recursive transfer. You may use as many --filter options on the command line as you like to build up the list of files to exclude. If the filter contains whitespace, be sure to quote it so that the shell gives the rule to rsync as a single argument. The text below also mentions that you can use an underscore to replace the space that separates a rule from its arg. See the FILTER RULES section for detailed information on this option. -F The -F option is a shorthand for adding two --filter rules to your command. The first time it is used is a shorthand for this rule: --filter='dir-merge /.rsync-filter' This tells rsync to look for per-directory .rsync-filter files that have been sprinkled through the hierarchy and use their rules to filter the files in the transfer. If -F is repeated, it is a shorthand for this rule: --filter='exclude .rsync-filter' This filters out the .rsync-filter files themselves from the transfer. See the FILTER RULES section for detailed information on how these options work. --exclude=PATTERN This option is a simplified form of the --filter option that specifies an exclude rule and does not allow the full rule-parsing syntax of normal filter rules. This is equivalent to specifying -f'- PATTERN'. See the FILTER RULES section for detailed information on this option. --exclude-from=FILE This option is related to the --exclude option, but it specifies a FILE that contains exclude patterns (one per line). Blank lines in the file are ignored, as are whole- line comments that start with ';' or '#' (filename rules that contain those characters are unaffected). If a line begins with "- " (dash, space) or "+ " (plus, space), then the type of rule is being explicitly specified as an exclude or an include (respectively). Any rules without such a prefix are taken to be an exclude. If a line consists of just "!", then the current filter rules are cleared before adding any further rules. If FILE is '-', the list will be read from standard input. --include=PATTERN This option is a simplified form of the --filter option that specifies an include rule and does not allow the full rule-parsing syntax of normal filter rules. This is equivalent to specifying -f'+ PATTERN'. See the FILTER RULES section for detailed information on this option. --include-from=FILE This option is related to the --include option, but it specifies a FILE that contains include patterns (one per line). Blank lines in the file are ignored, as are whole- line comments that start with ';' or '#' (filename rules that contain those characters are unaffected). If a line begins with "- " (dash, space) or "+ " (plus, space), then the type of rule is being explicitly specified as an exclude or an include (respectively). Any rules without such a prefix are taken to be an include. If a line consists of just "!", then the current filter rules are cleared before adding any further rules. If FILE is '-', the list will be read from standard input. --files-from=FILE Using this option allows you to specify the exact list of files to transfer (as read from the specified FILE or '-' for standard input). It also tweaks the default behavior of rsync to make transferring just the specified files and directories easier: o The --relative (-R) option is implied, which preserves the path information that is specified for each item in the file (use --no-relative or --no-R if you want to turn that off). o The --dirs (-d) option is implied, which will create directories specified in the list on the destination rather than noisily skipping them (use --no-dirs or --no-d if you want to turn that off). o The --archive (-a) option's behavior does not imply --recursive (-r), so specify it explicitly, if you want it. o These side-effects change the default state of rsync, so the position of the --files-from option on the command-line has no bearing on how other options are parsed (e.g. -a works the same before or after --files-from, as does --no-R and all other options). The filenames that are read from the FILE are all relative to the source dir -- any leading slashes are removed and no ".." references are allowed to go higher than the source dir. For example, take this command: rsync -a --files-from=/tmp/foo /usr remote:/backup If /tmp/foo contains the string "bin" (or even "/bin"), the /usr/bin directory will be created as /backup/bin on the remote host. If it contains "bin/" (note the trailing slash), the immediate contents of the directory would also be sent (without needing to be explicitly mentioned in the file -- this began in version 2.6.4). In both cases, if the -r option was enabled, that dir's entire hierarchy would also be transferred (keep in mind that -r needs to be specified explicitly with --files-from, since it is not implied by -a. Also note that the effect of the (enabled by default) -r option is to duplicate only the path info that is read from the file -- it does not force the duplication of the source-spec path (/usr in this case). In addition, the --files-from file can be read from the remote host instead of the local host if you specify a "host:" in front of the file (the host must match one end of the transfer). As a short-cut, you can specify just a prefix of ":" to mean "use the remote end of the transfer". For example: rsync -a --files-from=:/path/file-list src:/ /tmp/copy This would copy all the files specified in the /path/file- list file that was located on the remote "src" host. If the --iconv and --secluded-args options are specified and the --files-from filenames are being sent from one host to another, the filenames will be translated from the sending host's charset to the receiving host's charset. NOTE: sorting the list of files in the --files-from input helps rsync to be more efficient, as it will avoid re- visiting the path elements that are shared between adjacent entries. If the input is not sorted, some path elements (implied directories) may end up being scanned multiple times, and rsync will eventually unduplicate them after they get turned into file-list elements. --from0, -0 This tells rsync that the rules/filenames it reads from a file are terminated by a null ('\0') character, not a NL, CR, or CR+LF. This affects --exclude-from, --include- from, --files-from, and any merged files specified in a --filter rule. It does not affect --cvs-exclude (since all names read from a .cvsignore file are split on whitespace). --old-args This option tells rsync to stop trying to protect the arg values on the remote side from unintended word-splitting or other misinterpretation. It also allows the client to treat an empty arg as a "." instead of generating an error. The default in a modern rsync is for "shell-active" characters (including spaces) to be backslash-escaped in the args that are sent to the remote shell. The wildcard characters *, ?, [, & ] are not escaped in filename args (allowing them to expand into multiple filenames) while being protected in option args, such as --usermap. If you have a script that wants to use old-style arg splitting in its filenames, specify this option once. If the remote shell has a problem with any backslash escapes at all, specify this option twice. You may also control this setting via the RSYNC_OLD_ARGS environment variable. If it has the value "1", rsync will default to a single-option setting. If it has the value "2" (or more), rsync will default to a repeated-option setting. If it is "0", you'll get the default escaping behavior. The environment is always overridden by manually specified positive or negative options (the negative is --no-old-args). Note that this option also disables the extra safety check added in 3.2.5 that ensures that a remote sender isn't including extra top-level items in the file-list that you didn't request. This side-effect is necessary because we can't know for sure what names to expect when the remote shell is interpreting the args. This option conflicts with the --secluded-args option. --secluded-args, -s This option sends all filenames and most options to the remote rsync via the protocol (not the remote shell command line) which avoids letting the remote shell modify them. Wildcards are expanded on the remote host by rsync instead of a shell. This is similar to the default backslash-escaping of args that was added in 3.2.4 (see --old-args) in that it prevents things like space splitting and unwanted special- character side-effects. However, it has the drawbacks of being incompatible with older rsync versions (prior to 3.0.0) and of being refused by restricted shells that want to be able to inspect all the option values for safety. This option is useful for those times that you need the argument's character set to be converted for the remote host, if the remote shell is incompatible with the default backslash-escpaing method, or there is some other reason that you want the majority of the options and arguments to bypass the command-line of the remote shell. If you combine this option with --iconv, the args related to the remote side will be translated from the local to the remote character-set. The translation happens before wild-cards are expanded. See also the --files-from option. You may also control this setting via the RSYNC_PROTECT_ARGS environment variable. If it has a non- zero value, this setting will be enabled by default, otherwise it will be disabled by default. Either state is overridden by a manually specified positive or negative version of this option (note that --no-s and --no- secluded-args are the negative versions). This environment variable is also superseded by a non-zero RSYNC_OLD_ARGS export. This option conflicts with the --old-args option. This option used to be called --protect-args (before 3.2.6) and that older name can still be used (though specifying it as -s is always the easiest and most compatible choice). --trust-sender This option disables two extra validation checks that a local client performs on the file list generated by a remote sender. This option should only be used if you trust the sender to not put something malicious in the file list (something that could possibly be done via a modified rsync, a modified shell, or some other similar manipulation). Normally, the rsync client (as of version 3.2.5) runs two extra validation checks when pulling files from a remote rsync: o It verifies that additional arg items didn't get added at the top of the transfer. o It verifies that none of the items in the file list are names that should have been excluded (if filter rules were specified). Note that various options can turn off one or both of these checks if the option interferes with the validation. For instance: o Using a per-directory filter file reads filter rules that only the server knows about, so the filter checking is disabled. o Using the --old-args option allows the sender to manipulate the requested args, so the arg checking is disabled. o Reading the files-from list from the server side means that the client doesn't know the arg list, so the arg checking is disabled. o Using --read-batch disables both checks since the batch file's contents will have been verified when it was created. This option may help an under-powered client server if the extra pattern matching is slowing things down on a huge transfer. It can also be used to work around a currently- unknown bug in the verification logic for a transfer from a trusted sender. When using this option it is a good idea to specify a dedicated destination directory, as discussed in the MULTI-HOST SECURITY section. --copy-as=USER[:GROUP] This option instructs rsync to use the USER and (if specified after a colon) the GROUP for the copy operations. This only works if the user that is running rsync has the ability to change users. If the group is not specified then the user's default groups are used. This option can help to reduce the risk of an rsync being run as root into or out of a directory that might have live changes happening to it and you want to make sure that root-level read or write actions of system files are not possible. While you could alternatively run all of rsync as the specified user, sometimes you need the root- level host-access credentials to be used, so this allows rsync to drop root for the copying part of the operation after the remote-shell or daemon connection is established. The option only affects one side of the transfer unless the transfer is local, in which case it affects both sides. Use the --remote-option to affect the remote side, such as -M--copy-as=joe. For a local transfer, the lsh (or lsh.sh) support file provides a local-shell helper script that can be used to allow a "localhost:" or "lh:" host-spec to be specified without needing to setup any remote shells, allowing you to specify remote options that affect the side of the transfer that is using the host- spec (and using hostname "lh" avoids the overriding of the remote directory to the user's home dir). For example, the following rsync writes the local files as user "joe": sudo rsync -aiv --copy-as=joe host1:backups/joe/ /home/joe/ This makes all files owned by user "joe", limits the groups to those that are available to that user, and makes it impossible for the joe user to do a timed exploit of the path to induce a change to a file that the joe user has no permissions to change. The following command does a local copy into the "dest/" dir as user "joe" (assuming you've installed support/lsh into a dir on your $PATH): sudo rsync -aive lsh -M--copy-as=joe src/ lh:dest/ --temp-dir=DIR, -T This option instructs rsync to use DIR as a scratch directory when creating temporary copies of the files transferred on the receiving side. The default behavior is to create each temporary file in the same directory as the associated destination file. Beginning with rsync 3.1.1, the temp-file names inside the specified DIR will not be prefixed with an extra dot (though they will still have a random suffix added). This option is most often used when the receiving disk partition does not have enough free space to hold a copy of the largest file in the transfer. In this case (i.e. when the scratch directory is on a different disk partition), rsync will not be able to rename each received temporary file over the top of the associated destination file, but instead must copy it into place. Rsync does this by copying the file over the top of the destination file, which means that the destination file will contain truncated data during this copy. If this were not done this way (even if the destination file were first removed, the data locally copied to a temporary file in the destination directory, and then renamed into place) it would be possible for the old file to continue taking up disk space (if someone had it open), and thus there might not be enough room to fit the new version on the disk at the same time. If you are using this option for reasons other than a shortage of disk space, you may wish to combine it with the --delay-updates option, which will ensure that all copied files get put into subdirectories in the destination hierarchy, awaiting the end of the transfer. If you don't have enough room to duplicate all the arriving files on the destination partition, another way to tell rsync that you aren't overly concerned about disk space is to use the --partial-dir option with a relative path; because this tells rsync that it is OK to stash off a copy of a single file in a subdir in the destination hierarchy, rsync will use the partial-dir as a staging area to bring over the copied file, and then rename it into place from there. (Specifying a --partial-dir with an absolute path does not have this side-effect.) --fuzzy, -y This option tells rsync that it should look for a basis file for any destination file that is missing. The current algorithm looks in the same directory as the destination file for either a file that has an identical size and modified-time, or a similarly-named file. If found, rsync uses the fuzzy basis file to try to speed up the transfer. If the option is repeated, the fuzzy scan will also be done in any matching alternate destination directories that are specified via --compare-dest, --copy-dest, or --link-dest. Note that the use of the --delete option might get rid of any potential fuzzy-match files, so either use --delete- after or specify some filename exclusions if you need to prevent this. --compare-dest=DIR This option instructs rsync to use DIR on the destination machine as an additional hierarchy to compare destination files against doing transfers (if the files are missing in the destination directory). If a file is found in DIR that is identical to the sender's file, the file will NOT be transferred to the destination directory. This is useful for creating a sparse backup of just files that have changed from an earlier backup. This option is typically used to copy into an empty (or newly created) directory. Beginning in version 2.6.4, multiple --compare-dest directories may be provided, which will cause rsync to search the list in the order specified for an exact match. If a match is found that differs only in attributes, a local copy is made and the attributes updated. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. If DIR is a relative path, it is relative to the destination directory. See also --copy-dest and --link- dest. NOTE: beginning with version 3.1.0, rsync will remove a file from a non-empty destination hierarchy if an exact match is found in one of the compare-dest hierarchies (making the end result more closely match a fresh copy). --copy-dest=DIR This option behaves like --compare-dest, but rsync will also copy unchanged files found in DIR to the destination directory using a local copy. This is useful for doing transfers to a new destination while leaving existing files intact, and then doing a flash-cutover when all files have been successfully transferred. Multiple --copy-dest directories may be provided, which will cause rsync to search the list in the order specified for an unchanged file. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. If DIR is a relative path, it is relative to the destination directory. See also --compare-dest and --link-dest. --link-dest=DIR This option behaves like --copy-dest, but unchanged files are hard linked from DIR to the destination directory. The files must be identical in all preserved attributes (e.g. permissions, possibly ownership) in order for the files to be linked together. An example: rsync -av --link-dest=$PWD/prior_dir host:src_dir/ new_dir/ If files aren't linking, double-check their attributes. Also check if some attributes are getting forced outside of rsync's control, such a mount option that squishes root to a single user, or mounts a removable drive with generic ownership (such as OS X's "Ignore ownership on this volume" option). Beginning in version 2.6.4, multiple --link-dest directories may be provided, which will cause rsync to search the list in the order specified for an exact match (there is a limit of 20 such directories). If a match is found that differs only in attributes, a local copy is made and the attributes updated. If a match is not found, a basis file from one of the DIRs will be selected to try to speed up the transfer. This option works best when copying into an empty destination hierarchy, as existing files may get their attributes tweaked, and that can affect alternate destination files via hard-links. Also, itemizing of changes can get a bit muddled. Note that prior to version 3.1.0, an alternate-directory exact match would never be found (nor linked into the destination) when a destination file already exists. Note that if you combine this option with --ignore-times, rsync will not link any files together because it only links identical files together as a substitute for transferring the file, never as an additional check after the file is updated. If DIR is a relative path, it is relative to the destination directory. See also --compare-dest and --copy-dest. Note that rsync versions prior to 2.6.1 had a bug that could prevent --link-dest from working properly for a non- super-user when --owner (-o) was specified (or implied). You can work-around this bug by avoiding the -o option (or using --no-o) when sending to an old rsync. --compress, -z With this option, rsync compresses the file data as it is sent to the destination machine, which reduces the amount of data being transmitted -- something that is useful over a slow connection. Rsync supports multiple compression methods and will choose one for you unless you force the choice using the --compress-choice (--zc) option. Run rsync --version to see the default compress list compiled into your version. When both sides of the transfer are at least 3.2.0, rsync chooses the first algorithm in the client's list of choices that is also in the server's list of choices. If no common compress choice is found, rsync exits with an error. If the remote rsync is too old to support checksum negotiation, its list is assumed to be "zlib". The default order can be customized by setting the environment variable RSYNC_COMPRESS_LIST to a space- separated list of acceptable compression names. If the string contains a "&" character, it is separated into the "client string & server string", otherwise the same string applies to both. If the string (or string portion) contains no non-whitespace characters, the default compress list is used. Any unknown compression names are discarded from the list, but a list with only invalid names results in a failed negotiation. There are some older rsync versions that were configured to reject a -z option and require the use of -zz because their compression library was not compatible with the default zlib compression method. You can usually ignore this weirdness unless the rsync server complains and tells you to specify -zz. --compress-choice=STR, --zc=STR This option can be used to override the automatic negotiation of the compression algorithm that occurs when --compress is used. The option implies --compress unless "none" was specified, which instead implies --no-compress. The compression options that you may be able to use are: o zstd o lz4 o zlibx o zlib o none Run rsync --version to see the default compress list compiled into your version (which may differ from the list above). Note that if you see an error about an option named --old- compress or --new-compress, this is rsync trying to send the --compress-choice=zlib or --compress-choice=zlibx option in a backward-compatible manner that more rsync versions understand. This error indicates that the older rsync version on the server will not allow you to force the compression type. Note that the "zlibx" compression algorithm is just the "zlib" algorithm with matched data excluded from the compression stream (to try to make it more compatible with an external zlib implementation). --compress-level=NUM, --zl=NUM Explicitly set the compression level to use (see --compress, -z) instead of letting it default. The --compress option is implied as long as the level chosen is not a "don't compress" level for the compression algorithm that is in effect (e.g. zlib compression treats level 0 as "off"). The level values vary depending on the checksum in effect. Because rsync will negotiate a checksum choice by default (when the remote rsync is new enough), it can be good to combine this option with a --compress-choice (--zc) option unless you're sure of the choice in effect. For example: rsync -aiv --zc=zstd --zl=22 host:src/ dest/ For zlib & zlibx compression the valid values are from 1 to 9 with 6 being the default. Specifying --zl=0 turns compression off, and specifying --zl=-1 chooses the default level of 6. For zstd compression the valid values are from -131072 to 22 with 3 being the default. Specifying 0 chooses the default of 3. For lz4 compression there are no levels, so the value is always 0. If you specify a too-large or too-small value, the number is silently limited to a valid value. This allows you to specify something like --zl=999999999 and be assured that you'll end up with the maximum compression level no matter what algorithm was chosen. If you want to know the compression level that is in effect, specify --debug=nstr to see the "negotiated string" results. This will report something like "Client compress: zstd (level 3)" (along with the checksum choice in effect). --skip-compress=LIST NOTE: no compression method currently supports per-file compression changes, so this option has no effect. Override the list of file suffixes that will be compressed as little as possible. Rsync sets the compression level on a per-file basis based on the file's suffix. If the compression algorithm has an "off" level, then no compression occurs for those files. Other algorithms that support changing the streaming level on-the-fly will have the level minimized to reduces the CPU usage as much as possible for a matching file. The LIST should be one or more file suffixes (without the dot) separated by slashes (/). You may specify an empty string to indicate that no files should be skipped. Simple character-class matching is supported: each must consist of a list of letters inside the square brackets (e.g. no special classes, such as "[:alpha:]", are supported, and '-' has no special meaning). The characters asterisk (*) and question-mark (?) have no special meaning. Here's an example that specifies 6 suffixes to skip (since 1 of the 5 rules matches 2 suffixes): --skip-compress=gz/jpg/mp[34]/7z/bz2 The default file suffixes in the skip-compress list in this version of rsync are: 3g2 3gp 7z aac ace apk avi bz2 deb dmg ear f4v flac flv gpg gz iso jar jpeg jpg lrz lz lz4 lzma lzo m1a m1v m2a m2ts m2v m4a m4b m4p m4r m4v mka mkv mov mp1 mp2 mp3 mp4 mpa mpeg mpg mpv mts odb odf odg odi odm odp ods odt oga ogg ogm ogv ogx opus otg oth otp ots ott oxt png qt rar rpm rz rzip spx squashfs sxc sxd sxg sxm sxw sz tbz tbz2 tgz tlz ts txz tzo vob war webm webp xz z zip zst This list will be replaced by your --skip-compress list in all but one situation: a copy from a daemon rsync will add your skipped suffixes to its list of non-compressing files (and its list may be configured to a different default). --numeric-ids With this option rsync will transfer numeric group and user IDs rather than using user and group names and mapping them at both ends. By default rsync will use the username and groupname to determine what ownership to give files. The special uid 0 and the special group 0 are never mapped via user/group names even if the --numeric-ids option is not specified. If a user or group has no name on the source system or it has no match on the destination system, then the numeric ID from the source system is used instead. See also the use chroot setting in the rsyncd.conf manpage for some comments on how the chroot setting affects rsync's ability to look up the names of the users and groups and what you can do about it. --usermap=STRING, --groupmap=STRING These options allow you to specify users and groups that should be mapped to other values by the receiving side. The STRING is one or more FROM:TO pairs of values separated by commas. Any matching FROM value from the sender is replaced with a TO value from the receiver. You may specify usernames or user IDs for the FROM and TO values, and the FROM value may also be a wild-card string, which will be matched against the sender's names (wild- cards do NOT match against ID numbers, though see below for why a '*' matches everything). You may instead specify a range of ID numbers via an inclusive range: LOW- HIGH. For example: --usermap=0-99:nobody,wayne:admin,*:normal --groupmap=usr:1,1:usr The first match in the list is the one that is used. You should specify all your user mappings using a single --usermap option, and/or all your group mappings using a single --groupmap option. Note that the sender's name for the 0 user and group are not transmitted to the receiver, so you should either match these values using a 0, or use the names in effect on the receiving side (typically "root"). All other FROM names match those in use on the sending side. All TO names match those in use on the receiving side. Any IDs that do not have a name on the sending side are treated as having an empty name for the purpose of matching. This allows them to be matched via a "*" or using an empty name. For instance: --usermap=:nobody --groupmap=*:nobody When the --numeric-ids option is used, the sender does not send any names, so all the IDs are treated as having an empty name. This means that you will need to specify numeric FROM values if you want to map these nameless IDs to different values. For the --usermap option to work, the receiver will need to be running as a super-user (see also the --super and --fake-super options). For the --groupmap option to work, the receiver will need to have permissions to set that group. Starting with rsync 3.2.4, the --usermap option implies the --owner (-o) option while the --groupmap option implies the --group (-g) option (since rsync needs to have those options enabled for the mapping options to work). An older rsync client may need to use -s to avoid a complaint about wildcard characters, but a modern rsync handles this automatically. --chown=USER:GROUP This option forces all files to be owned by USER with group GROUP. This is a simpler interface than using --usermap & --groupmap directly, but it is implemented using those options internally so they cannot be mixed. If either the USER or GROUP is empty, no mapping for the omitted user/group will occur. If GROUP is empty, the trailing colon may be omitted, but if USER is empty, a leading colon must be supplied. If you specify "--chown=foo:bar", this is exactly the same as specifying "--usermap=*:foo --groupmap=*:bar", only easier (and with the same implied --owner and/or --group options). An older rsync client may need to use -s to avoid a complaint about wildcard characters, but a modern rsync handles this automatically. --timeout=SECONDS This option allows you to set a maximum I/O timeout in seconds. If no data is transferred for the specified time then rsync will exit. The default is 0, which means no timeout. --contimeout=SECONDS This option allows you to set the amount of time that rsync will wait for its connection to an rsync daemon to succeed. If the timeout is reached, rsync exits with an error. --address=ADDRESS By default rsync will bind to the wildcard address when connecting to an rsync daemon. The --address option allows you to specify a specific IP address (or hostname) to bind to. See also the daemon version of the --address option. --port=PORT This specifies an alternate TCP port number to use rather than the default of 873. This is only needed if you are using the double-colon (::) syntax to connect with an rsync daemon (since the URL syntax has a way to specify the port as a part of the URL). See also the daemon version of the --port option. --sockopts=OPTIONS This option can provide endless fun for people who like to tune their systems to the utmost degree. You can set all sorts of socket options which may make transfers faster (or slower!). Read the manpage for the setsockopt() system call for details on some of the options you may be able to set. By default no special socket options are set. This only affects direct socket connections to a remote rsync daemon. See also the daemon version of the --sockopts option. --blocking-io This tells rsync to use blocking I/O when launching a remote shell transport. If the remote shell is either rsh or remsh, rsync defaults to using blocking I/O, otherwise it defaults to using non-blocking I/O. (Note that ssh prefers non-blocking I/O.) --outbuf=MODE This sets the output buffering mode. The mode can be None (aka Unbuffered), Line, or Block (aka Full). You may specify as little as a single letter for the mode, and use upper or lower case. The main use of this option is to change Full buffering to Line buffering when rsync's output is going to a file or pipe. --itemize-changes, -i Requests a simple itemized list of the changes that are being made to each file, including attribute changes. This is exactly the same as specifying --out- format='%i %n%L'. If you repeat the option, unchanged files will also be output, but only if the receiving rsync is at least version 2.6.7 (you can use -vv with older versions of rsync, but that also turns on the output of other verbose messages). The "%i" escape has a cryptic output that is 11 letters long. The general format is like the string YXcstpoguax, where Y is replaced by the type of update being done, X is replaced by the file-type, and the other letters represent attributes that may be output if they are being modified. The update types that replace the Y are as follows: o A < means that a file is being transferred to the remote host (sent). o A > means that a file is being transferred to the local host (received). o A c means that a local change/creation is occurring for the item (such as the creation of a directory or the changing of a symlink, etc.). o A h means that the item is a hard link to another item (requires --hard-links). o A . means that the item is not being updated (though it might have attributes that are being modified). o A * means that the rest of the itemized-output area contains a message (e.g. "deleting"). The file-types that replace the X are: f for a file, a d for a directory, an L for a symlink, a D for a device, and a S for a special file (e.g. named sockets and fifos). The other letters in the string indicate if some attributes of the file have changed, as follows: o "." - the attribute is unchanged. o "+" - the file is newly created. o " " - all the attributes are unchanged (all dots turn to spaces). o "?" - the change is unknown (when the remote rsync is old). o A letter indicates an attribute is being updated. The attribute that is associated with each letter is as follows: o A c means either that a regular file has a different checksum (requires --checksum) or that a symlink, device, or special file has a changed value. Note that if you are sending files to an rsync prior to 3.0.1, this change flag will be present only for checksum-differing regular files. o A s means the size of a regular file is different and will be updated by the file transfer. o A t means the modification time is different and is being updated to the sender's value (requires --times). An alternate value of T means that the modification time will be set to the transfer time, which happens when a file/symlink/device is updated without --times and when a symlink is changed and the receiver can't set its time. (Note: when using an rsync 3.0.0 client, you might see the s flag combined with t instead of the proper T flag for this time-setting failure.) o A p means the permissions are different and are being updated to the sender's value (requires --perms). o An o means the owner is different and is being updated to the sender's value (requires --owner and super-user privileges). o A g means the group is different and is being updated to the sender's value (requires --group and the authority to set the group). o o A u|n|b indicates the following information: u means the access (use) time is different and is being updated to the sender's value (requires --atimes) o n means the create time (newness) is different and is being updated to the sender's value (requires --crtimes) o b means that both the access and create times are being updated o The a means that the ACL information is being changed. o The x means that the extended attribute information is being changed. One other output is possible: when deleting files, the "%i" will output the string "*deleting" for each item that is being removed (assuming that you are talking to a recent enough rsync that it logs deletions instead of outputting them as a verbose message). --out-format=FORMAT This allows you to specify exactly what the rsync client outputs to the user on a per-update basis. The format is a text string containing embedded single-character escape sequences prefixed with a percent (%) character. A default format of "%n%L" is assumed if either --info=name or -v is specified (this tells you just the name of the file and, if the item is a link, where it points). For a full list of the possible escape characters, see the log format setting in the rsyncd.conf manpage. Specifying the --out-format option implies the --info=name option, which will mention each file, dir, etc. that gets updated in a significant way (a transferred file, a recreated symlink/device, or a touched directory). In addition, if the itemize-changes escape (%i) is included in the string (e.g. if the --itemize-changes option was used), the logging of names increases to mention any item that is changed in any way (as long as the receiving side is at least 2.6.4). See the --itemize-changes option for a description of the output of "%i". Rsync will output the out-format string prior to a file's transfer unless one of the transfer-statistic escapes is requested, in which case the logging is done at the end of the file's transfer. When this late logging is in effect and --progress is also specified, rsync will also output the name of the file being transferred prior to its progress information (followed, of course, by the out- format output). --log-file=FILE This option causes rsync to log what it is doing to a file. This is similar to the logging that a daemon does, but can be requested for the client side and/or the server side of a non-daemon transfer. If specified as a client option, transfer logging will be enabled with a default format of "%i %n%L". See the --log-file-format option if you wish to override this. Here's an example command that requests the remote side to log what is happening: rsync -av --remote-option=--log-file=/tmp/rlog src/ dest/ This is very useful if you need to debug why a connection is closing unexpectedly. See also the daemon version of the --log-file option. --log-file-format=FORMAT This allows you to specify exactly what per-update logging is put into the file specified by the --log-file option (which must also be specified for this option to have any effect). If you specify an empty string, updated files will not be mentioned in the log file. For a list of the possible escape characters, see the log format setting in the rsyncd.conf manpage. The default FORMAT used if --log-file is specified and this option is not is '%i %n%L'. See also the daemon version of the --log-file-format option. --stats This tells rsync to print a verbose set of statistics on the file transfer, allowing you to tell how effective rsync's delta-transfer algorithm is for your data. This option is equivalent to --info=stats2 if combined with 0 or 1 -v options, or --info=stats3 if combined with 2 or more -v options. The current statistics are as follows: o Number of files is the count of all "files" (in the generic sense), which includes directories, symlinks, etc. The total count will be followed by a list of counts by filetype (if the total is non- zero). For example: "(reg: 5, dir: 3, link: 2, dev: 1, special: 1)" lists the totals for regular files, directories, symlinks, devices, and special files. If any of value is 0, it is completely omitted from the list. o Number of created files is the count of how many "files" (generic sense) were created (as opposed to updated). The total count will be followed by a list of counts by filetype (if the total is non- zero). o Number of deleted files is the count of how many "files" (generic sense) were deleted. The total count will be followed by a list of counts by filetype (if the total is non-zero). Note that this line is only output if deletions are in effect, and only if protocol 31 is being used (the default for rsync 3.1.x). o Number of regular files transferred is the count of normal files that were updated via rsync's delta- transfer algorithm, which does not include dirs, symlinks, etc. Note that rsync 3.1.0 added the word "regular" into this heading. o Total file size is the total sum of all file sizes in the transfer. This does not count any size for directories or special files, but does include the size of symlinks. o Total transferred file size is the total sum of all files sizes for just the transferred files. o Literal data is how much unmatched file-update data we had to send to the receiver for it to recreate the updated files. o Matched data is how much data the receiver got locally when recreating the updated files. o File list size is how big the file-list data was when the sender sent it to the receiver. This is smaller than the in-memory size for the file list due to some compressing of duplicated data when rsync sends the list. o File list generation time is the number of seconds that the sender spent creating the file list. This requires a modern rsync on the sending side for this to be present. o File list transfer time is the number of seconds that the sender spent sending the file list to the receiver. o Total bytes sent is the count of all the bytes that rsync sent from the client side to the server side. o Total bytes received is the count of all non- message bytes that rsync received by the client side from the server side. "Non-message" bytes means that we don't count the bytes for a verbose message that the server sent to us, which makes the stats more consistent. --8-bit-output, -8 This tells rsync to leave all high-bit characters unescaped in the output instead of trying to test them to see if they're valid in the current locale and escaping the invalid ones. All control characters (but never tabs) are always escaped, regardless of this option's setting. The escape idiom that started in 2.6.7 is to output a literal backslash (\) and a hash (#), followed by exactly 3 octal digits. For example, a newline would output as "\#012". A literal backslash that is in a filename is not escaped unless it is followed by a hash and 3 digits (0-9). --human-readable, -h Output numbers in a more human-readable format. There are 3 possible levels: 1. output numbers with a separator between each set of 3 digits (either a comma or a period, depending on if the decimal point is represented by a period or a comma). 2. output numbers in units of 1000 (with a character suffix for larger units -- see below). 3. output numbers in units of 1024. The default is human-readable level 1. Each -h option increases the level by one. You can take the level down to 0 (to output numbers as pure digits) by specifying the --no-human-readable (--no-h) option. The unit letters that are appended in levels 2 and 3 are: K (kilo), M (mega), G (giga), T (tera), or P (peta). For example, a 1234567-byte file would output as 1.23M in level-2 (assuming that a period is your local decimal point). Backward compatibility note: versions of rsync prior to 3.1.0 do not support human-readable level 1, and they default to level 0. Thus, specifying one or two -h options will behave in a comparable manner in old and new versions as long as you didn't specify a --no-h option prior to one or more -h options. See the --list-only option for one difference. --partial By default, rsync will delete any partially transferred file if the transfer is interrupted. In some circumstances it is more desirable to keep partially transferred files. Using the --partial option tells rsync to keep the partial file which should make a subsequent transfer of the rest of the file much faster. --partial-dir=DIR This option modifies the behavior of the --partial option while also implying that it be enabled. This enhanced partial-file method puts any partially transferred files into the specified DIR instead of writing the partial file out to the destination file. On the next transfer, rsync will use a file found in this dir as data to speed up the resumption of the transfer and then delete it after it has served its purpose. Note that if --whole-file is specified (or implied), any partial-dir files that are found for a file that is being updated will simply be removed (since rsync is sending files without using rsync's delta-transfer algorithm). Rsync will create the DIR if it is missing, but just the last dir -- not the whole path. This makes it easy to use a relative path (such as "--partial-dir=.rsync-partial") to have rsync create the partial-directory in the destination file's directory when it is needed, and then remove it again when the partial file is deleted. Note that this directory removal is only done for a relative pathname, as it is expected that an absolute path is to a directory that is reserved for partial-dir work. If the partial-dir value is not an absolute path, rsync will add an exclude rule at the end of all your existing excludes. This will prevent the sending of any partial- dir files that may exist on the sending side, and will also prevent the untimely deletion of partial-dir items on the receiving side. An example: the above --partial-dir option would add the equivalent of this "perishable" exclude at the end of any other filter rules: -f '-p .rsync-partial/' If you are supplying your own exclude rules, you may need to add your own exclude/hide/protect rule for the partial- dir because: 1. the auto-added rule may be ineffective at the end of your other rules, or 2. you may wish to override rsync's exclude choice. For instance, if you want to make rsync clean-up any left- over partial-dirs that may be lying around, you should specify --delete-after and add a "risk" filter rule, e.g. -f 'R .rsync-partial/'. Avoid using --delete-before or --delete-during unless you don't need rsync to use any of the left-over partial-dir data during the current run. IMPORTANT: the --partial-dir should not be writable by other users or it is a security risk! E.g. AVOID "/tmp"! You can also set the partial-dir value the RSYNC_PARTIAL_DIR environment variable. Setting this in the environment does not force --partial to be enabled, but rather it affects where partial files go when --partial is specified. For instance, instead of using --partial-dir=.rsync-tmp along with --progress, you could set RSYNC_PARTIAL_DIR=.rsync-tmp in your environment and then use the -P option to turn on the use of the .rsync- tmp dir for partial transfers. The only times that the --partial option does not look for this environment value are: 1. when --inplace was specified (since --inplace conflicts with --partial-dir), and 2. when --delay-updates was specified (see below). When a modern rsync resumes the transfer of a file in the partial-dir, that partial file is now updated in-place instead of creating yet another tmp-file copy (so it maxes out at dest + tmp instead of dest + partial + tmp). This requires both ends of the transfer to be at least version 3.2.0. For the purposes of the daemon-config's "refuse options" setting, --partial-dir does not imply --partial. This is so that a refusal of the --partial option can be used to disallow the overwriting of destination files with a partial transfer, while still allowing the safer idiom provided by --partial-dir. --delay-updates This option puts the temporary file from each updated file into a holding directory until the end of the transfer, at which time all the files are renamed into place in rapid succession. This attempts to make the updating of the files a little more atomic. By default the files are placed into a directory named .~tmp~ in each file's destination directory, but if you've specified the --partial-dir option, that directory will be used instead. See the comments in the --partial-dir section for a discussion of how this .~tmp~ dir will be excluded from the transfer, and what you can do if you want rsync to cleanup old .~tmp~ dirs that might be lying around. Conflicts with --inplace and --append. This option implies --no-inc-recursive since it needs the full file list in memory in order to be able to iterate over it at the end. This option uses more memory on the receiving side (one bit per file transferred) and also requires enough free disk space on the receiving side to hold an additional copy of all the updated files. Note also that you should not use an absolute path to --partial-dir unless: 1. there is no chance of any of the files in the transfer having the same name (since all the updated files will be put into a single directory if the path is absolute), and 2. there are no mount points in the hierarchy (since the delayed updates will fail if they can't be renamed into place). See also the "atomic-rsync" python script in the "support" subdir for an update algorithm that is even more atomic (it uses --link-dest and a parallel hierarchy of files). --prune-empty-dirs, -m This option tells the receiving rsync to get rid of empty directories from the file-list, including nested directories that have no non-directory children. This is useful for avoiding the creation of a bunch of useless directories when the sending rsync is recursively scanning a hierarchy of files using include/exclude/filter rules. This option can still leave empty directories on the receiving side if you make use of TRANSFER_RULES. Because the file-list is actually being pruned, this option also affects what directories get deleted when a delete is active. However, keep in mind that excluded files and directories can prevent existing items from being deleted due to an exclude both hiding source files and protecting destination files. See the perishable filter-rule option for how to avoid this. You can prevent the pruning of certain empty directories from the file-list by using a global "protect" filter. For instance, this option would ensure that the directory "emptydir" was kept in the file-list: --filter 'protect emptydir/' Here's an example that copies all .pdf files in a hierarchy, only creating the necessary destination directories to hold the .pdf files, and ensures that any superfluous files and directories in the destination are removed (note the hide filter of non-directories being used instead of an exclude): rsync -avm --del --include='*.pdf' -f 'hide,! */' src/ dest If you didn't want to remove superfluous destination files, the more time-honored options of --include='*/' --exclude='*' would work fine in place of the hide-filter (if that is more natural to you). --progress This option tells rsync to print information showing the progress of the transfer. This gives a bored user something to watch. With a modern rsync this is the same as specifying --info=flist2,name,progress, but any user- supplied settings for those info flags takes precedence (e.g. --info=flist0 --progress). While rsync is transferring a regular file, it updates a progress line that looks like this: 782448 63% 110.64kB/s 0:00:04 In this example, the receiver has reconstructed 782448 bytes or 63% of the sender's file, which is being reconstructed at a rate of 110.64 kilobytes per second, and the transfer will finish in 4 seconds if the current rate is maintained until the end. These statistics can be misleading if rsync's delta- transfer algorithm is in use. For example, if the sender's file consists of the basis file followed by additional data, the reported rate will probably drop dramatically when the receiver gets to the literal data, and the transfer will probably take much longer to finish than the receiver estimated as it was finishing the matched part of the file. When the file transfer finishes, rsync replaces the progress line with a summary line that looks like this: 1,238,099 100% 146.38kB/s 0:00:08 (xfr#5, to-chk=169/396) In this example, the file was 1,238,099 bytes long in total, the average rate of transfer for the whole file was 146.38 kilobytes per second over the 8 seconds that it took to complete, it was the 5th transfer of a regular file during the current rsync session, and there are 169 more files for the receiver to check (to see if they are up-to-date or not) remaining out of the 396 total files in the file-list. In an incremental recursion scan, rsync won't know the total number of files in the file-list until it reaches the ends of the scan, but since it starts to transfer files during the scan, it will display a line with the text "ir-chk" (for incremental recursion check) instead of "to-chk" until the point that it knows the full size of the list, at which point it will switch to using "to-chk". Thus, seeing "ir-chk" lets you know that the total count of files in the file list is still going to increase (and each time it does, the count of files left to check will increase by the number of the files added to the list). -P The -P option is equivalent to "--partial --progress". Its purpose is to make it much easier to specify these two options for a long transfer that may be interrupted. There is also a --info=progress2 option that outputs statistics based on the whole transfer, rather than individual files. Use this flag without outputting a filename (e.g. avoid -v or specify --info=name0) if you want to see how the transfer is doing without scrolling the screen with a lot of names. (You don't need to specify the --progress option in order to use --info=progress2.) Finally, you can get an instant progress report by sending rsync a signal of either SIGINFO or SIGVTALRM. On BSD systems, a SIGINFO is generated by typing a Ctrl+T (Linux doesn't currently support a SIGINFO signal). When the client-side process receives one of those signals, it sets a flag to output a single progress report which is output when the current file transfer finishes (so it may take a little time if a big file is being handled when the signal arrives). A filename is output (if needed) followed by the --info=progress2 format of progress info. If you don't know which of the 3 rsync processes is the client process, it's OK to signal all of them (since the non- client processes ignore the signal). CAUTION: sending SIGVTALRM to an older rsync (pre-3.2.0) will kill it. --password-file=FILE This option allows you to provide a password for accessing an rsync daemon via a file or via standard input if FILE is -. The file should contain just the password on the first line (all other lines are ignored). Rsync will exit with an error if FILE is world readable or if a root-run rsync command finds a non-root-owned file. This option does not supply a password to a remote shell transport such as ssh; to learn how to do that, consult the remote shell's documentation. When accessing an rsync daemon using a remote shell as the transport, this option only comes into effect after the remote shell finishes its authentication (i.e. if you have also specified a password in the daemon's config file). --early-input=FILE This option allows rsync to send up to 5K of data to the "early exec" script on its stdin. One possible use of this data is to give the script a secret that can be used to mount an encrypted filesystem (which you should unmount in the the "post-xfer exec" script). The daemon must be at least version 3.2.1. --list-only This option will cause the source files to be listed instead of transferred. This option is inferred if there is a single source arg and no destination specified, so its main uses are: 1. to turn a copy command that includes a destination arg into a file-listing command, or 2. to be able to specify more than one source arg. Note: be sure to include the destination. CAUTION: keep in mind that a source arg with a wild-card is expanded by the shell into multiple args, so it is never safe to try to specify a single wild-card arg to try to infer this option. A safe example is: rsync -av --list-only foo* dest/ This option always uses an output format that looks similar to this: drwxrwxr-x 4,096 2022/09/30 12:53:11 support -rw-rw-r-- 80 2005/01/11 10:37:37 support/Makefile The only option that affects this output style is (as of 3.1.0) the --human-readable (-h) option. The default is to output sizes as byte counts with digit separators (in a 14-character-width column). Specifying at least one -h option makes the sizes output with unit suffixes. If you want old-style bytecount sizes without digit separators (and an 11-character-width column) use --no-h. Compatibility note: when requesting a remote listing of files from an rsync that is version 2.6.3 or older, you may encounter an error if you ask for a non-recursive listing. This is because a file listing implies the --dirs option w/o --recursive, and older rsyncs don't have that option. To avoid this problem, either specify the --no-dirs option (if you don't need to expand a directory's content), or turn on recursion and exclude the content of subdirectories: -r --exclude='/*/*'. --bwlimit=RATE This option allows you to specify the maximum transfer rate for the data sent over the socket, specified in units per second. The RATE value can be suffixed with a string to indicate a size multiplier, and may be a fractional value (e.g. --bwlimit=1.5m). If no suffix is specified, the value will be assumed to be in units of 1024 bytes (as if "K" or "KiB" had been appended). See the --max-size option for a description of all the available suffixes. A value of 0 specifies no limit. For backward-compatibility reasons, the rate limit will be rounded to the nearest KiB unit, so no rate smaller than 1024 bytes per second is possible. Rsync writes data over the socket in blocks, and this option both limits the size of the blocks that rsync writes, and tries to keep the average transfer rate at the requested limit. Some burstiness may be seen where rsync writes out a block of data and then sleeps to bring the average rate into compliance. Due to the internal buffering of data, the --progress option may not be an accurate reflection on how fast the data is being sent. This is because some files can show up as being rapidly sent when the data is quickly buffered, while other can show up as very slow when the flushing of the output buffer occurs. This may be fixed in a future version. See also the daemon version of the --bwlimit option. --stop-after=MINS, (--time-limit=MINS) This option tells rsync to stop copying when the specified number of minutes has elapsed. For maximal flexibility, rsync does not communicate this option to the remote rsync since it is usually enough that one side of the connection quits as specified. This allows the option's use even when only one side of the connection supports it. You can tell the remote side about the time limit using --remote-option (-M), should the need arise. The --time-limit version of this option is deprecated. --stop-at=y-m-dTh:m This option tells rsync to stop copying when the specified point in time has been reached. The date & time can be fully specified in a numeric format of year-month- dayThour:minute (e.g. 2000-12-31T23:59) in the local timezone. You may choose to separate the date numbers using slashes instead of dashes. The value can also be abbreviated in a variety of ways, such as specifying a 2-digit year and/or leaving off various values. In all cases, the value will be taken to be the next possible point in time where the supplied information matches. If the value specifies the current time or a past time, rsync exits with an error. For example, "1-30" specifies the next January 30th (at midnight local time), "14:00" specifies the next 2 P.M., "1" specifies the next 1st of the month at midnight, "31" specifies the next month where we can stop on its 31st day, and ":59" specifies the next 59th minute after the hour. For maximal flexibility, rsync does not communicate this option to the remote rsync since it is usually enough that one side of the connection quits as specified. This allows the option's use even when only one side of the connection supports it. You can tell the remote side about the time limit using --remote-option (-M), should the need arise. Do keep in mind that the remote host may have a different default timezone than your local host. --fsync Cause the receiving side to fsync each finished file. This may slow down the transfer, but can help to provide peace of mind when updating critical files. --write-batch=FILE Record a file that can later be applied to another identical destination with --read-batch. See the "BATCH MODE" section for details, and also the --only-write-batch option. This option overrides the negotiated checksum & compress lists and always negotiates a choice based on old-school md5/md4/zlib choices. If you want a more modern choice, use the --checksum-choice (--cc) and/or --compress-choice (--zc) options. --only-write-batch=FILE Works like --write-batch, except that no updates are made on the destination system when creating the batch. This lets you transport the changes to the destination system via some other means and then apply the changes via --read-batch. Note that you can feel free to write the batch directly to some portable media: if this media fills to capacity before the end of the transfer, you can just apply that partial transfer to the destination and repeat the whole process to get the rest of the changes (as long as you don't mind a partially updated destination system while the multi-update cycle is happening). Also note that you only save bandwidth when pushing changes to a remote system because this allows the batched data to be diverted from the sender into the batch file without having to flow over the wire to the receiver (when pulling, the sender is remote, and thus can't write the batch). --read-batch=FILE Apply all of the changes stored in FILE, a file previously generated by --write-batch. If FILE is -, the batch data will be read from standard input. See the "BATCH MODE" section for details. --protocol=NUM Force an older protocol version to be used. This is useful for creating a batch file that is compatible with an older version of rsync. For instance, if rsync 2.6.4 is being used with the --write-batch option, but rsync 2.6.3 is what will be used to run the --read-batch option, you should use "--protocol=28" when creating the batch file to force the older protocol version to be used in the batch file (assuming you can't upgrade the rsync on the reading system). --iconv=CONVERT_SPEC Rsync can convert filenames between character sets using this option. Using a CONVERT_SPEC of "." tells rsync to look up the default character-set via the locale setting. Alternately, you can fully specify what conversion to do by giving a local and a remote charset separated by a comma in the order --iconv=LOCAL,REMOTE, e.g. --iconv=utf8,iso88591. This order ensures that the option will stay the same whether you're pushing or pulling files. Finally, you can specify either --no-iconv or a CONVERT_SPEC of "-" to turn off any conversion. The default setting of this option is site-specific, and can also be affected via the RSYNC_ICONV environment variable. For a list of what charset names your local iconv library supports, you can run "iconv --list". If you specify the --secluded-args (-s) option, rsync will translate the filenames you specify on the command-line that are being sent to the remote host. See also the --files-from option. Note that rsync does not do any conversion of names in filter files (including include/exclude files). It is up to you to ensure that you're specifying matching rules that can match on both sides of the transfer. For instance, you can specify extra include/exclude rules if there are filename differences on the two sides that need to be accounted for. When you pass an --iconv option to an rsync daemon that allows it, the daemon uses the charset specified in its "charset" configuration parameter regardless of the remote charset you actually pass. Thus, you may feel free to specify just the local charset for a daemon transfer (e.g. --iconv=utf8). --ipv4, -4 or --ipv6, -6 Tells rsync to prefer IPv4/IPv6 when creating sockets or running ssh. This affects sockets that rsync has direct control over, such as the outgoing socket when directly contacting an rsync daemon, as well as the forwarding of the -4 or -6 option to ssh when rsync can deduce that ssh is being used as the remote shell. For other remote shells you'll need to specify the "--rsh SHELL -4" option directly (or whatever IPv4/IPv6 hint options it uses). See also the daemon version of these options. If rsync was compiled without support for IPv6, the --ipv6 option will have no effect. The rsync --version output will contain "no IPv6" if is the case. --checksum-seed=NUM Set the checksum seed to the integer NUM. This 4 byte checksum seed is included in each block and MD4 file checksum calculation (the more modern MD5 file checksums don't use a seed). By default the checksum seed is generated by the server and defaults to the current time(). This option is used to set a specific checksum seed, which is useful for applications that want repeatable block checksums, or in the case where the user wants a more random checksum seed. Setting NUM to 0 causes rsync to use the default of time() for checksum seed. DAEMON OPTIONS top The options allowed when starting an rsync daemon are as follows: --daemon This tells rsync that it is to run as a daemon. The daemon you start running may be accessed using an rsync client using the host::module or rsync://host/module/ syntax. If standard input is a socket then rsync will assume that it is being run via inetd, otherwise it will detach from the current terminal and become a background daemon. The daemon will read the config file (rsyncd.conf) on each connect made by a client and respond to requests accordingly. See the rsyncd.conf(5) manpage for more details. --address=ADDRESS By default rsync will bind to the wildcard address when run as a daemon with the --daemon option. The --address option allows you to specify a specific IP address (or hostname) to bind to. This makes virtual hosting possible in conjunction with the --config option. See also the address global option in the rsyncd.conf manpage and the client version of the --address option. --bwlimit=RATE This option allows you to specify the maximum transfer rate for the data the daemon sends over the socket. The client can still specify a smaller --bwlimit value, but no larger value will be allowed. See the client version of the --bwlimit option for some extra details. --config=FILE This specifies an alternate config file than the default. This is only relevant when --daemon is specified. The default is /etc/rsyncd.conf unless the daemon is running over a remote shell program and the remote user is not the super-user; in that case the default is rsyncd.conf in the current directory (typically $HOME). --dparam=OVERRIDE, -M This option can be used to set a daemon-config parameter when starting up rsync in daemon mode. It is equivalent to adding the parameter at the end of the global settings prior to the first module's definition. The parameter names can be specified without spaces, if you so desire. For instance: rsync --daemon -M pidfile=/path/rsync.pid --no-detach When running as a daemon, this option instructs rsync to not detach itself and become a background process. This option is required when running as a service on Cygwin, and may also be useful when rsync is supervised by a program such as daemontools or AIX's System Resource Controller. --no-detach is also recommended when rsync is run under a debugger. This option has no effect if rsync is run from inetd or sshd. --port=PORT This specifies an alternate TCP port number for the daemon to listen on rather than the default of 873. See also the client version of the --port option and the port global setting in the rsyncd.conf manpage. --log-file=FILE This option tells the rsync daemon to use the given log- file name instead of using the "log file" setting in the config file. See also the client version of the --log-file option. --log-file-format=FORMAT This option tells the rsync daemon to use the given FORMAT string instead of using the "log format" setting in the config file. It also enables "transfer logging" unless the string is empty, in which case transfer logging is turned off. See also the client version of the --log-file-format option. --sockopts This overrides the socket options setting in the rsyncd.conf file and has the same syntax. See also the client version of the --sockopts option. --verbose, -v This option increases the amount of information the daemon logs during its startup phase. After the client connects, the daemon's verbosity level will be controlled by the options that the client used and the "max verbosity" setting in the module's config section. See also the client version of the --verbose option. --ipv4, -4 or --ipv6, -6 Tells rsync to prefer IPv4/IPv6 when creating the incoming sockets that the rsync daemon will use to listen for connections. One of these options may be required in older versions of Linux to work around an IPv6 bug in the kernel (if you see an "address already in use" error when nothing else is using the port, try specifying --ipv6 or --ipv4 when starting the daemon). See also the client version of these options. If rsync was compiled without support for IPv6, the --ipv6 option will have no effect. The rsync --version output will contain "no IPv6" if is the case. --help, -h When specified after --daemon, print a short help page describing the options available for starting an rsync daemon. FILTER RULES top The filter rules allow for custom control of several aspects of how files are handled: o Control which files the sending side puts into the file list that describes the transfer hierarchy o Control which files the receiving side protects from deletion when the file is not in the sender's file list o Control which extended attribute names are skipped when copying xattrs The rules are either directly specified via option arguments or they can be read in from one or more files. The filter-rule files can even be a part of the hierarchy of files being copied, affecting different parts of the tree in different ways. SIMPLE INCLUDE/EXCLUDE RULES We will first cover the basics of how include & exclude rules affect what files are transferred, ignoring any deletion side- effects. Filter rules mainly affect the contents of directories that rsync is "recursing" into, but they can also affect a top- level item in the transfer that was specified as a argument. The default for any unmatched file/dir is for it to be included in the transfer, which puts the file/dir into the sender's file list. The use of an exclude rule causes one or more matching files/dirs to be left out of the sender's file list. An include rule can be used to limit the effect of an exclude rule that is matching too many files. The order of the rules is important because the first rule that matches is the one that takes effect. Thus, if an early rule excludes a file, no include rule that comes after it can have any effect. This means that you must place any include overrides somewhere prior to the exclude that it is intended to limit. When a directory is excluded, all its contents and sub-contents are also excluded. The sender doesn't scan through any of it at all, which can save a lot of time when skipping large unneeded sub-trees. It is also important to understand that the include/exclude rules are applied to every file and directory that the sender is recursing into. Thus, if you want a particular deep file to be included, you have to make sure that none of the directories that must be traversed on the way down to that file are excluded or else the file will never be discovered to be included. As an example, if the directory "a/path" was given as a transfer argument and you want to ensure that the file "a/path/down/deep/wanted.txt" is a part of the transfer, then the sender must not exclude the directories "a/path", "a/path/down", or "a/path/down/deep" as it makes it way scanning through the file tree. When you are working on the rules, it can be helpful to ask rsync to tell you what is being excluded/included and why. Specifying --debug=FILTER or (when pulling files) -M--debug=FILTER turns on level 1 of the FILTER debug information that will output a message any time that a file or directory is included or excluded and which rule it matched. Beginning in 3.2.4 it will also warn if a filter rule has trailing whitespace, since an exclude of "foo " (with a trailing space) will not exclude a file named "foo". Exclude and include rules can specify wildcard PATTERN MATCHING RULES (similar to shell wildcards) that allow you to match things like a file suffix or a portion of a filename. A rule can be limited to only affecting a directory by putting a trailing slash onto the filename. SIMPLE INCLUDE/EXCLUDE EXAMPLE With the following file tree created on the sending side: mkdir x/ touch x/file.txt mkdir x/y/ touch x/y/file.txt touch x/y/zzz.txt mkdir x/z/ touch x/z/file.txt Then the following rsync command will transfer the file "x/y/file.txt" and the directories needed to hold it, resulting in the path "/tmp/x/y/file.txt" existing on the remote host: rsync -ai -f'+ x/' -f'+ x/y/' -f'+ x/y/file.txt' -f'- *' x host:/tmp/ Aside: this copy could also have been accomplished using the -R option (though the 2 commands behave differently if deletions are enabled): rsync -aiR x/y/file.txt host:/tmp/ The following command does not need an include of the "x" directory because it is not a part of the transfer (note the traililng slash). Running this command would copy just "/tmp/x/file.txt" because the "y" and "z" dirs get excluded: rsync -ai -f'+ file.txt' -f'- *' x/ host:/tmp/x/ This command would omit the zzz.txt file while copying "x" and everything else it contains: rsync -ai -f'- zzz.txt' x host:/tmp/ FILTER RULES WHEN DELETING By default the include & exclude filter rules affect both the sender (as it creates its file list) and the receiver (as it creates its file lists for calculating deletions). If no delete option is in effect, the receiver skips creating the delete- related file lists. This two-sided default can be manually overridden so that you are only specifying sender rules or receiver rules, as described in the FILTER RULES IN DEPTH section. When deleting, an exclude protects a file from being removed on the receiving side while an include overrides that protection (putting the file at risk of deletion). The default is for a file to be at risk -- its safety depends on it matching a corresponding file from the sender. An example of the two-sided exclude effect can be illustrated by the copying of a C development directory between 2 systems. When doing a touch-up copy, you might want to skip copying the built executable and the .o files (sender hide) so that the receiving side can build their own and not lose any object files that are already correct (receiver protect). For instance: rsync -ai --del -f'- *.o' -f'- cmd' src host:/dest/ Note that using -f'-p *.o' is even better than -f'- *.o' if there is a chance that the directory structure may have changed. The "p" modifier is discussed in FILTER RULE MODIFIERS. One final note, if your shell doesn't mind unexpanded wildcards, you could simplify the typing of the filter options by using an underscore in place of the space and leaving off the quotes. For instance, -f -_*.o -f -_cmd (and similar) could be used instead of the filter options above. FILTER RULES IN DEPTH Rsync supports old-style include/exclude rules and new-style filter rules. The older rules are specified using --include and --exclude as well as the --include-from and --exclude-from. These are limited in behavior but they don't require a "-" or "+" prefix. An old-style exclude rule is turned into a "- name" filter rule (with no modifiers) and an old-style include rule is turned into a "+ name" filter rule (with no modifiers). Rsync builds an ordered list of filter rules as specified on the command-line and/or read-in from files. New style filter rules have the following syntax: RULE [PATTERN_OR_FILENAME] RULE,MODIFIERS [PATTERN_OR_FILENAME] You have your choice of using either short or long RULE names, as described below. If you use a short-named rule, the ',' separating the RULE from the MODIFIERS is optional. The PATTERN or FILENAME that follows (when present) must come after either a single space or an underscore (_). Any additional spaces and/or underscores are considered to be a part of the pattern name. Here are the available rule prefixes: exclude, '-' specifies an exclude pattern that (by default) is both a hide and a protect. include, '+' specifies an include pattern that (by default) is both a show and a risk. merge, '.' specifies a merge-file on the client side to read for more rules. dir-merge, ':' specifies a per-directory merge-file. Using this kind of filter rule requires that you trust the sending side's filter checking, so it has the side-effect mentioned under the --trust-sender option. hide, 'H' specifies a pattern for hiding files from the transfer. Equivalent to a sender-only exclude, so -f'H foo' could also be specified as -f'-s foo'. show, 'S' files that match the pattern are not hidden. Equivalent to a sender-only include, so -f'S foo' could also be specified as -f'+s foo'. protect, 'P' specifies a pattern for protecting files from deletion. Equivalent to a receiver-only exclude, so -f'P foo' could also be specified as -f'-r foo'. risk, 'R' files that match the pattern are not protected. Equivalent to a receiver-only include, so -f'R foo' could also be specified as -f'+r foo'. clear, '!' clears the current include/exclude list (takes no arg) When rules are being read from a file (using merge or dir-merge), empty lines are ignored, as are whole-line comments that start with a '#' (filename rules that contain a hash character are unaffected). Note also that the --filter, --include, and --exclude options take one rule/pattern each. To add multiple ones, you can repeat the options on the command-line, use the merge-file syntax of the --filter option, or the --include-from / --exclude-from options. PATTERN MATCHING RULES Most of the rules mentioned above take an argument that specifies what the rule should match. If rsync is recursing through a directory hierarchy, keep in mind that each pattern is matched against the name of every directory in the descent path as rsync finds the filenames to send. The matching rules for the pattern argument take several forms: o If a pattern contains a / (not counting a trailing slash) or a "**" (which can match a slash), then the pattern is matched against the full pathname, including any leading directories within the transfer. If the pattern doesn't contain a (non-trailing) / or a "**", then it is matched only against the final component of the filename or pathname. For example, foo means that the final path component must be "foo" while foo/bar would match the last 2 elements of the path (as long as both elements are within the transfer). o A pattern that ends with a / only matches a directory, not a regular file, symlink, or device. o A pattern that starts with a / is anchored to the start of the transfer path instead of the end. For example, /foo/** or /foo/bar/** match only leading elements in the path. If the rule is read from a per-directory filter file, the transfer path being matched will begin at the level of the filter file instead of the top of the transfer. See the section on ANCHORING INCLUDE/EXCLUDE PATTERNS for a full discussion of how to specify a pattern that matches at the root of the transfer. Rsync chooses between doing a simple string match and wildcard matching by checking if the pattern contains one of these three wildcard characters: '*', '?', and '[' : o a '?' matches any single character except a slash (/). o a '*' matches zero or more non-slash characters. o a '**' matches zero or more characters, including slashes. o a '[' introduces a character class, such as [a-z] or [[:alpha:]], that must match one character. o a trailing *** in the pattern is a shorthand that allows you to match a directory and all its contents using a single rule. For example, specifying "dir_name/***" will match both the "dir_name" directory (as if "dir_name/" had been specified) and everything in the directory (as if "dir_name/**" had been specified). o a backslash can be used to escape a wildcard character, but it is only interpreted as an escape character if at least one wildcard character is present in the match pattern. For instance, the pattern "foo\bar" matches that single backslash literally, while the pattern "foo\bar*" would need to be changed to "foo\\bar*" to avoid the "\b" becoming just "b". Here are some examples of exclude/include matching: o Option -f'- *.o' would exclude all filenames ending with .o o Option -f'- /foo' would exclude a file (or directory) named foo in the transfer-root directory o Option -f'- foo/' would exclude any directory named foo o Option -f'- foo/*/bar' would exclude any file/dir named bar which is at two levels below a directory named foo (if foo is in the transfer) o Option -f'- /foo/**/bar' would exclude any file/dir named bar that was two or more levels below a top-level directory named foo (note that /foo/bar is not excluded by this) o Options -f'+ */' -f'+ *.c' -f'- *' would include all directories and .c source files but nothing else o Options -f'+ foo/' -f'+ foo/bar.c' -f'- *' would include only the foo directory and foo/bar.c (the foo directory must be explicitly included or it would be excluded by the "- *") FILTER RULE MODIFIERS The following modifiers are accepted after an include (+) or exclude (-) rule: o A / specifies that the include/exclude rule should be matched against the absolute pathname of the current item. For example, -f'-/ /etc/passwd' would exclude the passwd file any time the transfer was sending files from the "/etc" directory, and "-/ subdir/foo" would always exclude "foo" when it is in a dir named "subdir", even if "foo" is at the root of the current transfer. o A ! specifies that the include/exclude should take effect if the pattern fails to match. For instance, -f'-! */' would exclude all non-directories. o A C is used to indicate that all the global CVS-exclude rules should be inserted as excludes in place of the "-C". No arg should follow. o An s is used to indicate that the rule applies to the sending side. When a rule affects the sending side, it affects what files are put into the sender's file list. The default is for a rule to affect both sides unless --delete-excluded was specified, in which case default rules become sender-side only. See also the hide (H) and show (S) rules, which are an alternate way to specify sending-side includes/excludes. o An r is used to indicate that the rule applies to the receiving side. When a rule affects the receiving side, it prevents files from being deleted. See the s modifier for more info. See also the protect (P) and risk (R) rules, which are an alternate way to specify receiver-side includes/excludes. o A p indicates that a rule is perishable, meaning that it is ignored in directories that are being deleted. For instance, the --cvs-exclude (-C) option's default rules that exclude things like "CVS" and "*.o" are marked as perishable, and will not prevent a directory that was removed on the source from being deleted on the destination. o An x indicates that a rule affects xattr names in xattr copy/delete operations (and is thus ignored when matching file/dir names). If no xattr-matching rules are specified, a default xattr filtering rule is used (see the --xattrs option). MERGE-FILE FILTER RULES You can merge whole files into your filter rules by specifying either a merge (.) or a dir-merge (:) filter rule (as introduced in the FILTER RULES section above). There are two kinds of merged files -- single-instance ('.') and per-directory (':'). A single-instance merge file is read one time, and its rules are incorporated into the filter list in the place of the "." rule. For per-directory merge files, rsync will scan every directory that it traverses for the named file, merging its contents when the file exists into the current list of inherited rules. These per-directory rule files must be created on the sending side because it is the sending side that is being scanned for the available files to transfer. These rule files may also need to be transferred to the receiving side if you want them to affect what files don't get deleted (see PER- DIRECTORY RULES AND DELETE below). Some examples: merge /etc/rsync/default.rules . /etc/rsync/default.rules dir-merge .per-dir-filter dir-merge,n- .non-inherited-per-dir-excludes :n- .non-inherited-per-dir-excludes The following modifiers are accepted after a merge or dir-merge rule: o A - specifies that the file should consist of only exclude patterns, with no other rule-parsing except for in-file comments. o A + specifies that the file should consist of only include patterns, with no other rule-parsing except for in-file comments. o A C is a way to specify that the file should be read in a CVS-compatible manner. This turns on 'n', 'w', and '-', but also allows the list-clearing token (!) to be specified. If no filename is provided, ".cvsignore" is assumed. o A e will exclude the merge-file name from the transfer; e.g. "dir-merge,e .rules" is like "dir-merge .rules" and "- .rules". o An n specifies that the rules are not inherited by subdirectories. o A w specifies that the rules are word-split on whitespace instead of the normal line-splitting. This also turns off comments. Note: the space that separates the prefix from the rule is treated specially, so "- foo + bar" is parsed as two rules (assuming that prefix-parsing wasn't also disabled). o You may also specify any of the modifiers for the "+" or "-" rules (above) in order to have the rules that are read in from the file default to having that modifier set (except for the ! modifier, which would not be useful). For instance, "merge,-/ .excl" would treat the contents of .excl as absolute-path excludes, while "dir-merge,s .filt" and ":sC" would each make all their per-directory rules apply only on the sending side. If the merge rule specifies sides to affect (via the s or r modifier or both), then the rules in the file must not specify sides (via a modifier or a rule prefix such as hide). Per-directory rules are inherited in all subdirectories of the directory where the merge-file was found unless the 'n' modifier was used. Each subdirectory's rules are prefixed to the inherited per-directory rules from its parents, which gives the newest rules a higher priority than the inherited rules. The entire set of dir-merge rules are grouped together in the spot where the merge-file was specified, so it is possible to override dir-merge rules via a rule that got specified earlier in the list of global rules. When the list-clearing rule ("!") is read from a per-directory file, it only clears the inherited rules for the current merge file. Another way to prevent a single rule from a dir-merge file from being inherited is to anchor it with a leading slash. Anchored rules in a per-directory merge-file are relative to the merge- file's directory, so a pattern "/foo" would only match the file "foo" in the directory where the dir-merge filter file was found. Here's an example filter file which you'd specify via --filter=". file": merge /home/user/.global-filter - *.gz dir-merge .rules + *.[ch] - *.o - foo* This will merge the contents of the /home/user/.global-filter file at the start of the list and also turns the ".rules" filename into a per-directory filter file. All rules read in prior to the start of the directory scan follow the global anchoring rules (i.e. a leading slash matches at the root of the transfer). If a per-directory merge-file is specified with a path that is a parent directory of the first transfer directory, rsync will scan all the parent dirs from that starting point to the transfer directory for the indicated per-directory file. For instance, here is a common filter (see -F): --filter=': /.rsync-filter' That rule tells rsync to scan for the file .rsync-filter in all directories from the root down through the parent directory of the transfer prior to the start of the normal directory scan of the file in the directories that are sent as a part of the transfer. (Note: for an rsync daemon, the root is always the same as the module's "path".) Some examples of this pre-scanning for per-directory files: rsync -avF /src/path/ /dest/dir rsync -av --filter=': ../../.rsync-filter' /src/path/ /dest/dir rsync -av --filter=': .rsync-filter' /src/path/ /dest/dir The first two commands above will look for ".rsync-filter" in "/" and "/src" before the normal scan begins looking for the file in "/src/path" and its subdirectories. The last command avoids the parent-dir scan and only looks for the ".rsync-filter" files in each directory that is a part of the transfer. If you want to include the contents of a ".cvsignore" in your patterns, you should use the rule ":C", which creates a dir-merge of the .cvsignore file, but parsed in a CVS-compatible manner. You can use this to affect where the --cvs-exclude (-C) option's inclusion of the per-directory .cvsignore file gets placed into your rules by putting the ":C" wherever you like in your filter rules. Without this, rsync would add the dir-merge rule for the .cvsignore file at the end of all your other rules (giving it a lower priority than your command-line rules). For example: cat <<EOT | rsync -avC --filter='. -' a/ b + foo.o :C - *.old EOT rsync -avC --include=foo.o -f :C --exclude='*.old' a/ b Both of the above rsync commands are identical. Each one will merge all the per-directory .cvsignore rules in the middle of the list rather than at the end. This allows their dir-specific rules to supersede the rules that follow the :C instead of being subservient to all your rules. To affect the other CVS exclude rules (i.e. the default list of exclusions, the contents of $HOME/.cvsignore, and the value of $CVSIGNORE) you should omit the -C command-line option and instead insert a "-C" rule into your filter rules; e.g. "--filter=-C". LIST-CLEARING FILTER RULE You can clear the current include/exclude list by using the "!" filter rule (as introduced in the FILTER RULES section above). The "current" list is either the global list of rules (if the rule is encountered while parsing the filter options) or a set of per-directory rules (which are inherited in their own sub-list, so a subdirectory can use this to clear out the parent's rules). ANCHORING INCLUDE/EXCLUDE PATTERNS As mentioned earlier, global include/exclude patterns are anchored at the "root of the transfer" (as opposed to per- directory patterns, which are anchored at the merge-file's directory). If you think of the transfer as a subtree of names that are being sent from sender to receiver, the transfer-root is where the tree starts to be duplicated in the destination directory. This root governs where patterns that start with a / match. Because the matching is relative to the transfer-root, changing the trailing slash on a source path or changing your use of the --relative option affects the path you need to use in your matching (in addition to changing how much of the file tree is duplicated on the destination host). The following examples demonstrate this. Let's say that we want to match two source files, one with an absolute path of "/home/me/foo/bar", and one with a path of "/home/you/bar/baz". Here is how the various command choices differ for a 2-source transfer: Example cmd: rsync -a /home/me /home/you /dest +/- pattern: /me/foo/bar +/- pattern: /you/bar/baz Target file: /dest/me/foo/bar Target file: /dest/you/bar/baz Example cmd: rsync -a /home/me/ /home/you/ /dest +/- pattern: /foo/bar (note missing "me") +/- pattern: /bar/baz (note missing "you") Target file: /dest/foo/bar Target file: /dest/bar/baz Example cmd: rsync -a --relative /home/me/ /home/you /dest +/- pattern: /home/me/foo/bar (note full path) +/- pattern: /home/you/bar/baz (ditto) Target file: /dest/home/me/foo/bar Target file: /dest/home/you/bar/baz Example cmd: cd /home; rsync -a --relative me/foo you/ /dest +/- pattern: /me/foo/bar (starts at specified path) +/- pattern: /you/bar/baz (ditto) Target file: /dest/me/foo/bar Target file: /dest/you/bar/baz The easiest way to see what name you should filter is to just look at the output when using --verbose and put a / in front of the name (use the --dry-run option if you're not yet ready to copy any files). PER-DIRECTORY RULES AND DELETE Without a delete option, per-directory rules are only relevant on the sending side, so you can feel free to exclude the merge files themselves without affecting the transfer. To make this easy, the 'e' modifier adds this exclude for you, as seen in these two equivalent commands: rsync -av --filter=': .excl' --exclude=.excl host:src/dir /dest rsync -av --filter=':e .excl' host:src/dir /dest However, if you want to do a delete on the receiving side AND you want some files to be excluded from being deleted, you'll need to be sure that the receiving side knows what files to exclude. The easiest way is to include the per-directory merge files in the transfer and use --delete-after, because this ensures that the receiving side gets all the same exclude rules as the sending side before it tries to delete anything: rsync -avF --delete-after host:src/dir /dest However, if the merge files are not a part of the transfer, you'll need to either specify some global exclude rules (i.e. specified on the command line), or you'll need to maintain your own per-directory merge files on the receiving side. An example of the first is this (assume that the remote .rules files exclude themselves): rsync -av --filter=': .rules' --filter='. /my/extra.rules' --delete host:src/dir /dest In the above example the extra.rules file can affect both sides of the transfer, but (on the sending side) the rules are subservient to the rules merged from the .rules files because they were specified after the per-directory merge rule. In one final example, the remote side is excluding the .rsync- filter files from the transfer, but we want to use our own .rsync-filter files to control what gets deleted on the receiving side. To do this we must specifically exclude the per-directory merge files (so that they don't get deleted) and then put rules into the local files to control what else should not get deleted. Like one of these commands: rsync -av --filter=':e /.rsync-filter' --delete \ host:src/dir /dest rsync -avFF --delete host:src/dir /dest TRANSFER RULES top In addition to the FILTER RULES that affect the recursive file scans that generate the file list on the sending and (when deleting) receiving sides, there are transfer rules. These rules affect which files the generator decides need to be transferred without the side effects of an exclude filter rule. Transfer rules affect only files and never directories. Because a transfer rule does not affect what goes into the sender's (and receiver's) file list, it cannot have any effect on which files get deleted on the receiving side. For example, if the file "foo" is present in the sender's list but its size is such that it is omitted due to a transfer rule, the receiving side does not request the file. However, its presence in the file list means that a delete pass will not remove a matching file named "foo" on the receiving side. On the other hand, a server-side exclude (hide) of the file "foo" leaves the file out of the server's file list, and absent a receiver-side exclude (protect) the receiver will remove a matching file named "foo" if deletions are requested. Given that the files are still in the sender's file list, the --prune-empty-dirs option will not judge a directory as being empty even if it contains only files that the transfer rules omitted. Similarly, a transfer rule does not have any extra effect on which files are deleted on the receiving side, so setting a maximum file size for the transfer does not prevent big files from being deleted. Examples of transfer rules include the default "quick check" algorithm (which compares size & modify time), the --update option, the --max-size option, the --ignore-non-existing option, and a few others. BATCH MODE top Batch mode can be used to apply the same set of updates to many identical systems. Suppose one has a tree which is replicated on a number of hosts. Now suppose some changes have been made to this source tree and those changes need to be propagated to the other hosts. In order to do this using batch mode, rsync is run with the write-batch option to apply the changes made to the source tree to one of the destination trees. The write-batch option causes the rsync client to store in a "batch file" all the information needed to repeat this operation against other, identical destination trees. Generating the batch file once saves having to perform the file status, checksum, and data block generation more than once when updating multiple destination trees. Multicast transport protocols can be used to transfer the batch update files in parallel to many hosts at once, instead of sending the same data to every host individually. To apply the recorded changes to another destination tree, run rsync with the read-batch option, specifying the name of the same batch file, and the destination tree. Rsync updates the destination tree using the information stored in the batch file. For your convenience, a script file is also created when the write-batch option is used: it will be named the same as the batch file with ".sh" appended. This script file contains a command-line suitable for updating a destination tree using the associated batch file. It can be executed using a Bourne (or Bourne-like) shell, optionally passing in an alternate destination tree pathname which is then used instead of the original destination path. This is useful when the destination tree path on the current host differs from the one used to create the batch file. Examples: $ rsync --write-batch=foo -a host:/source/dir/ /adest/dir/ $ scp foo* remote: $ ssh remote ./foo.sh /bdest/dir/ $ rsync --write-batch=foo -a /source/dir/ /adest/dir/ $ ssh remote rsync --read-batch=- -a /bdest/dir/ <foo In these examples, rsync is used to update /adest/dir/ from /source/dir/ and the information to repeat this operation is stored in "foo" and "foo.sh". The host "remote" is then updated with the batched data going into the directory /bdest/dir. The differences between the two examples reveals some of the flexibility you have in how you deal with batches: o The first example shows that the initial copy doesn't have to be local -- you can push or pull data to/from a remote host using either the remote-shell syntax or rsync daemon syntax, as desired. o The first example uses the created "foo.sh" file to get the right rsync options when running the read-batch command on the remote host. o The second example reads the batch data via standard input so that the batch file doesn't need to be copied to the remote machine first. This example avoids the foo.sh script because it needed to use a modified --read-batch option, but you could edit the script file if you wished to make use of it (just be sure that no other option is trying to use standard input, such as the --exclude-from=- option). Caveats: The read-batch option expects the destination tree that it is updating to be identical to the destination tree that was used to create the batch update fileset. When a difference between the destination trees is encountered the update might be discarded with a warning (if the file appears to be up-to-date already) or the file-update may be attempted and then, if the file fails to verify, the update discarded with an error. This means that it should be safe to re-run a read-batch operation if the command got interrupted. If you wish to force the batched-update to always be attempted regardless of the file's size and date, use the -I option (when reading the batch). If an error occurs, the destination tree will probably be in a partially updated state. In that case, rsync can be used in its regular (non-batch) mode of operation to fix up the destination tree. The rsync version used on all destinations must be at least as new as the one used to generate the batch file. Rsync will die with an error if the protocol version in the batch file is too new for the batch-reading rsync to handle. See also the --protocol option for a way to have the creating rsync generate a batch file that an older rsync can understand. (Note that batch files changed format in version 2.6.3, so mixing versions older than that with newer versions will not work.) When reading a batch file, rsync will force the value of certain options to match the data in the batch file if you didn't set them to the same as the batch-writing command. Other options can (and should) be changed. For instance --write-batch changes to --read-batch, --files-from is dropped, and the --filter / --include / --exclude options are not needed unless one of the --delete options is specified. The code that creates the BATCH.sh file transforms any filter/include/exclude options into a single list that is appended as a "here" document to the shell script file. An advanced user can use this to modify the exclude list if a change in what gets deleted by --delete is desired. A normal user can ignore this detail and just use the shell script as an easy way to run the appropriate --read-batch command for the batched data. The original batch mode in rsync was based on "rsync+", but the latest version uses a new implementation. SYMBOLIC LINKS top Three basic behaviors are possible when rsync encounters a symbolic link in the source directory. By default, symbolic links are not transferred at all. A message "skipping non-regular" file is emitted for any symlinks that exist. If --links is specified, then symlinks are added to the transfer (instead of being noisily ignored), and the default handling is to recreate them with the same target on the destination. Note that --archive implies --links. If --copy-links is specified, then symlinks are "collapsed" by copying their referent, rather than the symlink. Rsync can also distinguish "safe" and "unsafe" symbolic links. An example where this might be used is a web site mirror that wishes to ensure that the rsync module that is copied does not include symbolic links to /etc/passwd in the public section of the site. Using --copy-unsafe-links will cause any links to be copied as the file they point to on the destination. Using --safe-links will cause unsafe links to be omitted by the receiver. (Note that you must specify or imply --links for --safe-links to have any effect.) Symbolic links are considered unsafe if they are absolute symlinks (start with /), empty, or if they contain enough ".." components to ascend from the top of the transfer. Here's a summary of how the symlink options are interpreted. The list is in order of precedence, so if your combination of options isn't mentioned, use the first line that is a complete subset of your options: --copy-links Turn all symlinks into normal files and directories (leaving no symlinks in the transfer for any other options to affect). --copy-dirlinks Turn just symlinks to directories into real directories, leaving all other symlinks to be handled as described below. --links --copy-unsafe-links Turn all unsafe symlinks into files and create all safe symlinks. --copy-unsafe-links Turn all unsafe symlinks into files, noisily skip all safe symlinks. --links --safe-links The receiver skips creating unsafe symlinks found in the transfer and creates the safe ones. --links Create all symlinks. For the effect of --munge-links, see the discussion in that option's section. Note that the --keep-dirlinks option does not effect symlinks in the transfer but instead affects how rsync treats a symlink to a directory that already exists on the receiving side. See that option's section for a warning. DIAGNOSTICS top Rsync occasionally produces error messages that may seem a little cryptic. The one that seems to cause the most confusion is "protocol version mismatch -- is your shell clean?". This message is usually caused by your startup scripts or remote shell facility producing unwanted garbage on the stream that rsync is using for its transport. The way to diagnose this problem is to run your remote shell like this: ssh remotehost /bin/true > out.dat then look at out.dat. If everything is working correctly then out.dat should be a zero length file. If you are getting the above error from rsync then you will probably find that out.dat contains some text or data. Look at the contents and try to work out what is producing it. The most common cause is incorrectly configured shell startup scripts (such as .cshrc or .profile) that contain output statements for non-interactive logins. If you are having trouble debugging filter patterns, then try specifying the -vv option. At this level of verbosity rsync will show why each individual file is included or excluded. EXIT VALUES top o 0 - Success o 1 - Syntax or usage error o 2 - Protocol incompatibility o 3 - Errors selecting input/output files, dirs o o 4 - Requested action not supported. Either: an attempt was made to manipulate 64-bit files on a platform that cannot support them o an option was specified that is supported by the client and not by the server o 5 - Error starting client-server protocol o 6 - Daemon unable to append to log-file o 10 - Error in socket I/O o 11 - Error in file I/O o 12 - Error in rsync protocol data stream o 13 - Errors with program diagnostics o 14 - Error in IPC code o 20 - Received SIGUSR1 or SIGINT o 21 - Some error returned by waitpid() o 22 - Error allocating core memory buffers o 23 - Partial transfer due to error o 24 - Partial transfer due to vanished source files o 25 - The --max-delete limit stopped deletions o 30 - Timeout in data send/receive o 35 - Timeout waiting for daemon connection ENVIRONMENT VARIABLES top CVSIGNORE The CVSIGNORE environment variable supplements any ignore patterns in .cvsignore files. See the --cvs-exclude option for more details. RSYNC_ICONV Specify a default --iconv setting using this environment variable. First supported in 3.0.0. RSYNC_OLD_ARGS Specify a "1" if you want the --old-args option to be enabled by default, a "2" (or more) if you want it to be enabled in the repeated-option state, or a "0" to make sure that it is disabled by default. When this environment variable is set to a non-zero value, it supersedes the RSYNC_PROTECT_ARGS variable. This variable is ignored if --old-args, --no-old-args, or --secluded-args is specified on the command line. First supported in 3.2.4. RSYNC_PROTECT_ARGS Specify a non-zero numeric value if you want the --secluded-args option to be enabled by default, or a zero value to make sure that it is disabled by default. This variable is ignored if --secluded-args, --no- secluded-args, or --old-args is specified on the command line. First supported in 3.1.0. Starting in 3.2.4, this variable is ignored if RSYNC_OLD_ARGS is set to a non-zero value. RSYNC_RSH This environment variable allows you to override the default shell used as the transport for rsync. Command line options are permitted after the command name, just as in the --rsh (-e) option. RSYNC_PROXY This environment variable allows you to redirect your rsync client to use a web proxy when connecting to an rsync daemon. You should set RSYNC_PROXY to a hostname:port pair. RSYNC_PASSWORD This environment variable allows you to set the password for an rsync daemon connection, which avoids the password prompt. Note that this does not supply a password to a remote shell transport such as ssh (consult its documentation for how to do that). USER or LOGNAME The USER or LOGNAME environment variables are used to determine the default username sent to an rsync daemon. If neither is set, the username defaults to "nobody". If both are set, USER takes precedence. RSYNC_PARTIAL_DIR This environment variable specifies the directory to use for a --partial transfer without implying that partial transfers be enabled. See the --partial-dir option for full details. RSYNC_COMPRESS_LIST This environment variable allows you to customize the negotiation of the compression algorithm by specifying an alternate order or a reduced list of names. Use the command rsync --version to see the available compression names. See the --compress option for full details. RSYNC_CHECKSUM_LIST This environment variable allows you to customize the negotiation of the checksum algorithm by specifying an alternate order or a reduced list of names. Use the command rsync --version to see the available checksum names. See the --checksum-choice option for full details. RSYNC_MAX_ALLOC This environment variable sets an allocation maximum as if you had used the --max-alloc option. RSYNC_PORT This environment variable is not read by rsync, but is instead set in its sub-environment when rsync is running the remote shell in combination with a daemon connection. This allows a script such as rsync-ssl to be able to know the port number that the user specified on the command line. HOME This environment variable is used to find the user's default .cvsignore file. RSYNC_CONNECT_PROG This environment variable is mainly used in debug setups to set the program to use when making a daemon connection. See CONNECTING TO AN RSYNC DAEMON for full details. RSYNC_SHELL This environment variable is mainly used in debug setups to set the program to use to run the program specified by RSYNC_CONNECT_PROG. See CONNECTING TO AN RSYNC DAEMON for full details. FILES top /etc/rsyncd.conf or rsyncd.conf SEE ALSO top rsync-ssl(1), rsyncd.conf(5), rrsync(1) BUGS top o Times are transferred as *nix time_t values. o When transferring to FAT filesystems rsync may re-sync unmodified files. See the comments on the --modify-window option. o File permissions, devices, etc. are transferred as native numerical values. o See also the comments on the --delete option. Please report bugs! See the web site at https://rsync.samba.org/. VERSION top This manpage is current for version 3.2.7 of rsync. INTERNAL OPTIONS top The options --server and --sender are used internally by rsync, and should never be typed by a user under normal circumstances. Some awareness of these options may be needed in certain scenarios, such as when setting up a login that can only run an rsync command. For instance, the support directory of the rsync distribution has an example script named rrsync (for restricted rsync) that can be used with a restricted ssh login. CREDITS top Rsync is distributed under the GNU General Public License. See the file COPYING for details. An rsync web site is available at https://rsync.samba.org/. The site includes an FAQ-O-Matic which may cover questions unanswered by this manual page. The rsync github project is https://github.com/WayneD/rsync. We would be delighted to hear from you if you like this program. Please contact the mailing-list at rsync@lists.samba.org. This program uses the excellent zlib compression library written by Jean-loup Gailly and Mark Adler. THANKS top Special thanks go out to: John Van Essen, Matt McCutchen, Wesley W. Terpstra, David Dykstra, Jos Backus, Sebastian Krahmer, Martin Pool, and our gone-but-not-forgotten compadre, J.W. Schultz. Thanks also to Richard Brent, Brendan Mackay, Bill Waite, Stephen Rothwell and David Bell. I've probably missed some people, my apologies if I have. AUTHOR top Rsync was originally written by Andrew Tridgell and Paul Mackerras. Many people have later contributed to it. It is currently maintained by Wayne Davison. Mailing lists for support and development are available at https://lists.samba.org/. COLOPHON top This page is part of the rsync (a fast, versatile, remote (and local) file-copying tool) project. Information about the project can be found at https://rsync.samba.org/. If you have a bug report for this manual page, see https://rsync.samba.org/bugzilla.html. This page was obtained from the tarball fetched from https://download.samba.org/pub/rsync/ 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 rsync 3.2.7 20 Oct 2022 rsync(1) Pages that refer to this page: pmlogger_daily(1), rrsync(1), rsync-ssl(1), rsyncd.conf(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: Copy "/Users/username/path/on/machine/" to "username@server.ip.address.here:/home/username/path/on/server/" and convert encoding from UTF-8-MAC to UTF-8 Bash Command:<START>rsync --iconv=UTF-8-MAC,UTF-8 /Users/username/path/on/machine/ 'username@server.ip.address.here:/home/username/path/on/server/'<END>