This is coreutils.info, produced by makeinfo version 4.12 fromcoreutils.texi.INFO-DIR-SECTION BasicsSTART-INFO-DIR-ENTRY* Coreutils: (coreutils). Core GNU (file, text, shell) utilities.* Common options: (coreutils)Common options. Common options.* File permissions: (coreutils)File permissions. Access modes.* Date input formats: (coreutils)Date input formats.END-INFO-DIR-ENTRYINFO-DIR-SECTION Individual utilitiesSTART-INFO-DIR-ENTRY* arch: (coreutils)arch invocation. Print machine hardware name.* base64: (coreutils)base64 invocation. Base64 encode/decode data.* basename: (coreutils)basename invocation. Strip directory and suffix.* cat: (coreutils)cat invocation. Concatenate and write files.* chcon: (coreutils)chcon invocation. Change SELinux CTX of files.* chgrp: (coreutils)chgrp invocation. Change file groups.* chmod: (coreutils)chmod invocation. Change file permissions.* chown: (coreutils)chown invocation. Change file owners/groups.* chroot: (coreutils)chroot invocation. Specify the root directory.* cksum: (coreutils)cksum invocation. Print POSIX CRC checksum.* comm: (coreutils)comm invocation. Compare sorted files by line.* cp: (coreutils)cp invocation. Copy files.* csplit: (coreutils)csplit invocation. Split by context.* cut: (coreutils)cut invocation. Print selected parts of lines.* date: (coreutils)date invocation. Print/set system date and time.* dd: (coreutils)dd invocation. Copy and convert a file.* df: (coreutils)df invocation. Report file system disk usage.* dir: (coreutils)dir invocation. List directories briefly.* dircolors: (coreutils)dircolors invocation. Color setup for ls.* dirname: (coreutils)dirname invocation. Strip non-directory suffix.* du: (coreutils)du invocation. Report on disk usage.* echo: (coreutils)echo invocation. Print a line of text.* env: (coreutils)env invocation. Modify the environment.* expand: (coreutils)expand invocation. Convert tabs to spaces.* expr: (coreutils)expr invocation. Evaluate expressions.* factor: (coreutils)factor invocation. Print prime factors* false: (coreutils)false invocation. Do nothing, unsuccessfully.* fmt: (coreutils)fmt invocation. Reformat paragraph text.* fold: (coreutils)fold invocation. Wrap long input lines.* groups: (coreutils)groups invocation. Print group names a user is in.* head: (coreutils)head invocation. Output the first part of files.* hostid: (coreutils)hostid invocation. Print numeric host identifier.* hostname: (coreutils)hostname invocation. Print or set system name.* id: (coreutils)id invocation. Print user identity.* install: (coreutils)install invocation. Copy and change attributes.* join: (coreutils)join invocation. Join lines on a common field.* kill: (coreutils)kill invocation. Send a signal to processes.* link: (coreutils)link invocation. Make hard links between files.* ln: (coreutils)ln invocation. Make links between files.* logname: (coreutils)logname invocation. Print current login name.* ls: (coreutils)ls invocation. List directory contents.* md5sum: (coreutils)md5sum invocation. Print or check MD5 digests.* mkdir: (coreutils)mkdir invocation. Create directories.* mkfifo: (coreutils)mkfifo invocation. Create FIFOs (named pipes).* mknod: (coreutils)mknod invocation. Create special files.* mv: (coreutils)mv invocation. Rename files.* nice: (coreutils)nice invocation. Modify niceness.* nl: (coreutils)nl invocation. Number lines and write files.* nohup: (coreutils)nohup invocation. Immunize to hangups.* od: (coreutils)od invocation. Dump files in octal, etc.* paste: (coreutils)paste invocation. Merge lines of files.* pathchk: (coreutils)pathchk invocation. Check file name portability.* pr: (coreutils)pr invocation. Paginate or columnate files.* printenv: (coreutils)printenv invocation. Print environment variables.* printf: (coreutils)printf invocation. Format and print data.* ptx: (coreutils)ptx invocation. Produce permuted indexes.* pwd: (coreutils)pwd invocation. Print working directory.* readlink: (coreutils)readlink invocation. Print referent of a symlink.* rm: (coreutils)rm invocation. Remove files.* rmdir: (coreutils)rmdir invocation. Remove empty directories.* runcon: (coreutils)runcon invocation. Run in specified SELinux CTX.* seq: (coreutils)seq invocation. Print numeric sequences* sha1sum: (coreutils)sha1sum invocation. Print or check SHA-1 digests.* sha2: (coreutils)sha2 utilities. Print or check SHA-2 digests.* shred: (coreutils)shred invocation. Remove files more securely.* shuf: (coreutils)shuf invocation. Shuffling text files.* sleep: (coreutils)sleep invocation. Delay for a specified time.* sort: (coreutils)sort invocation. Sort text files.* split: (coreutils)split invocation. Split into fixed-size pieces.* stat: (coreutils)stat invocation. Report file(system) status.* stty: (coreutils)stty invocation. Print/change terminal settings.* su: (coreutils)su invocation. Modify user and group ID.* sum: (coreutils)sum invocation. Print traditional checksum.* sync: (coreutils)sync invocation. Synchronize memory and disk.* tac: (coreutils)tac invocation. Reverse files.* tail: (coreutils)tail invocation. Output the last part of files.* tee: (coreutils)tee invocation. Redirect to multiple files.* test: (coreutils)test invocation. File/string tests.* timeout: (coreutils)timeout invocation. Run with time limit.* touch: (coreutils)touch invocation. Change file timestamps.* tr: (coreutils)tr invocation. Translate characters.* true: (coreutils)true invocation. Do nothing, successfully.* truncate: (coreutils)truncate invocation. Shrink/extend size of a file.* tsort: (coreutils)tsort invocation. Topological sort.* tty: (coreutils)tty invocation. Print terminal name.* uname: (coreutils)uname invocation. Print system information.* unexpand: (coreutils)unexpand invocation. Convert spaces to tabs.* uniq: (coreutils)uniq invocation. Uniquify files.* unlink: (coreutils)unlink invocation. Removal via unlink(2).* uptime: (coreutils)uptime invocation. Print uptime and load.* users: (coreutils)users invocation. Print current user names.* vdir: (coreutils)vdir invocation. List directories verbosely.* wc: (coreutils)wc invocation. Line, word, and byte counts.* who: (coreutils)who invocation. Print who is logged in.* whoami: (coreutils)whoami invocation. Print effective user ID.* yes: (coreutils)yes invocation. Print a string indefinitely.END-INFO-DIR-ENTRYThis manual documents version 7.4 of the GNU core utilities,including the standard programs for text and file manipulation.Copyright (C) 1994-1996, 2000-2009 Free Software Foundation, Inc.Permission is granted to copy, distribute and/or modify thisdocument under the terms of the GNU Free Documentation License,Version 1.3 or any later version published by the Free SoftwareFoundation; with no Invariant Sections, with no Front-Cover Texts,and with no Back-Cover Texts. A copy of the license is includedin the section entitled "GNU Free Documentation License".File: coreutils.info, Node: Top, Next: Introduction, Up: (dir)GNU Coreutils*************This manual documents version 7.4 of the GNU core utilities, includingthe standard programs for text and file manipulation.Copyright (C) 1994-1996, 2000-2009 Free Software Foundation, Inc.Permission is granted to copy, distribute and/or modify thisdocument under the terms of the GNU Free Documentation License,Version 1.3 or any later version published by the Free SoftwareFoundation; with no Invariant Sections, with no Front-Cover Texts,and with no Back-Cover Texts. A copy of the license is includedin the section entitled "GNU Free Documentation License".* Menu:* Introduction:: Caveats, overview, and authors.* Common options:: Common options.* Output of entire files:: cat tac nl od* Formatting file contents:: fmt pr fold* Output of parts of files:: head tail split csplit* Summarizing files:: wc sum cksum md5sum sha1sum sha2* Operating on sorted files:: sort shuf uniq comm ptx tsort* Operating on fields within a line:: cut paste join* Operating on characters:: tr expand unexpand* Directory listing:: ls dir vdir dircolors* Basic operations:: cp dd install mv rm shred* Special file types:: ln mkdir rmdir mkfifo mknod* Changing file attributes:: chgrp chmod chown touch* Disk usage:: df du stat sync truncate* Printing text:: echo printf yes* Conditions:: false true test expr* Redirection:: tee* File name manipulation:: dirname basename pathchk* Working context:: pwd stty printenv tty* User information:: id logname whoami groups users who* System context:: date uname hostname hostid uptime* SELinux context:: chcon runcon* Modified command invocation:: chroot env nice nohup su timeout* Process control:: kill* Delaying:: sleep* Numeric operations:: factor seq* File permissions:: Access modes.* Date input formats:: Specifying date strings.* Opening the software toolbox:: The software tools philosophy.* GNU Free Documentation License:: Copying and sharing this manual.* Concept index:: General index.--- The Detailed Node Listing ---Common Options* Exit status:: Indicating program success or failure.* Backup options:: Backup options* Block size:: Block size* Signal specifications:: Specifying signals* Disambiguating names and IDs:: chgrp and chown owner and group syntax* Random sources:: Sources of random data* Target directory:: Target directory* Trailing slashes:: Trailing slashes* Traversing symlinks:: Traversing symlinks to directories* Treating / specially:: Treating / specially* Standards conformance:: Standards conformanceOutput of entire files* cat invocation:: Concatenate and write files.* tac invocation:: Concatenate and write files in reverse.* nl invocation:: Number lines and write files.* od invocation:: Write files in octal or other formats.* base64 invocation:: Transform data into printable data.Formatting file contents* fmt invocation:: Reformat paragraph text.* pr invocation:: Paginate or columnate files for printing.* fold invocation:: Wrap input lines to fit in specified width.Output of parts of files* head invocation:: Output the first part of files.* tail invocation:: Output the last part of files.* split invocation:: Split a file into fixed-size pieces.* csplit invocation:: Split a file into context-determined pieces.Summarizing files* wc invocation:: Print newline, word, and byte counts.* sum invocation:: Print checksum and block counts.* cksum invocation:: Print CRC checksum and byte counts.* md5sum invocation:: Print or check MD5 digests.* sha1sum invocation:: Print or check SHA-1 digests.* sha2 utilities:: Print or check SHA-2 digests.Operating on sorted files* sort invocation:: Sort text files.* shuf invocation:: Shuffle text files.* uniq invocation:: Uniquify files.* comm invocation:: Compare two sorted files line by line.* ptx invocation:: Produce a permuted index of file contents.* tsort invocation:: Topological sort.`ptx': Produce permuted indexes* General options in ptx:: Options which affect general program behavior.* Charset selection in ptx:: Underlying character set considerations.* Input processing in ptx:: Input fields, contexts, and keyword selection.* Output formatting in ptx:: Types of output format, and sizing the fields.* Compatibility in ptx:: The GNU extensions to `ptx'Operating on fields within a line* cut invocation:: Print selected parts of lines.* paste invocation:: Merge lines of files.* join invocation:: Join lines on a common field.Operating on characters* tr invocation:: Translate, squeeze, and/or delete characters.* expand invocation:: Convert tabs to spaces.* unexpand invocation:: Convert spaces to tabs.`tr': Translate, squeeze, and/or delete characters* Character sets:: Specifying sets of characters.* Translating:: Changing one set of characters to another.* Squeezing:: Squeezing repeats and deleting.Directory listing* ls invocation:: List directory contents* dir invocation:: Briefly list directory contents* vdir invocation:: Verbosely list directory contents* dircolors invocation:: Color setup for `ls'`ls': List directory contents* Which files are listed:: Which files are listed* What information is listed:: What information is listed* Sorting the output:: Sorting the output* More details about version sort:: More details about version sort* General output formatting:: General output formatting* Formatting the file names:: Formatting the file namesBasic operations* cp invocation:: Copy files and directories* dd invocation:: Convert and copy a file* install invocation:: Copy files and set attributes* mv invocation:: Move (rename) files* rm invocation:: Remove files or directories* shred invocation:: Remove files more securelySpecial file types* link invocation:: Make a hard link via the link syscall* ln invocation:: Make links between files* mkdir invocation:: Make directories* mkfifo invocation:: Make FIFOs (named pipes)* mknod invocation:: Make block or character special files* readlink invocation:: Print the referent of a symbolic link* rmdir invocation:: Remove empty directories* unlink invocation:: Remove files via unlink syscallChanging file attributes* chown invocation:: Change file owner and group* chgrp invocation:: Change group ownership* chmod invocation:: Change access permissions* touch invocation:: Change file timestampsDisk usage* df invocation:: Report file system disk space usage* du invocation:: Estimate file space usage* stat invocation:: Report file or file system status* sync invocation:: Synchronize data on disk with memory* truncate invocation:: Shrink or extend the size of a filePrinting text* echo invocation:: Print a line of text* printf invocation:: Format and print data* yes invocation:: Print a string until interruptedConditions* false invocation:: Do nothing, unsuccessfully* true invocation:: Do nothing, successfully* test invocation:: Check file types and compare values* expr invocation:: Evaluate expressions`test': Check file types and compare values* File type tests:: File type tests* Access permission tests:: Access permission tests* File characteristic tests:: File characteristic tests* String tests:: String tests* Numeric tests:: Numeric tests`expr': Evaluate expression* String expressions:: + : match substr index length* Numeric expressions:: + - * / %* Relations for expr:: | & < <= = == != >= >* Examples of expr:: Examples of using `expr'Redirection* tee invocation:: Redirect output to multiple files or processesFile name manipulation* basename invocation:: Strip directory and suffix from a file name* dirname invocation:: Strip non-directory suffix from a file name* pathchk invocation:: Check file name validity and portabilityWorking context* pwd invocation:: Print working directory* stty invocation:: Print or change terminal characteristics* printenv invocation:: Print all or some environment variables* tty invocation:: Print file name of terminal on standard input`stty': Print or change terminal characteristics* Control:: Control settings* Input:: Input settings* Output:: Output settings* Local:: Local settings* Combination:: Combination settings* Characters:: Special characters* Special:: Special settingsUser information* id invocation:: Print user identity* logname invocation:: Print current login name* whoami invocation:: Print effective user ID* groups invocation:: Print group names a user is in* users invocation:: Print login names of users currently logged in* who invocation:: Print who is currently logged inSystem context* arch invocation:: Print machine hardware name* date invocation:: Print or set system date and time* uname invocation:: Print system information* hostname invocation:: Print or set system name* hostid invocation:: Print numeric host identifier* uptime invocation:: Print system uptime and load`date': Print or set system date and time* Time conversion specifiers:: %[HIklMNpPrRsSTXzZ]* Date conversion specifiers:: %[aAbBcCdDeFgGhjmuUVwWxyY]* Literal conversion specifiers:: %[%nt]* Padding and other flags:: Pad with zeros, spaces, etc.* Setting the time:: Changing the system clock.* Options for date:: Instead of the current time.* Date input formats:: Specifying date strings.* Examples of date:: Examples.SELinux context* chcon invocation:: Change SELinux context of file* runcon invocation:: Run a command in specified SELinux contextModified command invocation* chroot invocation:: Run a command with a different root directory* env invocation:: Run a command in a modified environment* nice invocation:: Run a command with modified niceness* nohup invocation:: Run a command immune to hangups* su invocation:: Run a command with substitute user and group ID* timeout invocation:: Run a command with a time limitProcess control* kill invocation:: Sending a signal to processes.Delaying* sleep invocation:: Delay for a specified timeNumeric operations* factor invocation:: Print prime factors* seq invocation:: Print numeric sequencesFile permissions* Mode Structure:: Structure of file mode bits.* Symbolic Modes:: Mnemonic representation of file mode bits.* Numeric Modes:: File mode bits as octal numbers.* Directory Setuid and Setgid:: Set-user-ID and set-group-ID on directories.Date input formats* General date syntax:: Common rules.* Calendar date items:: 19 Dec 1994.* Time of day items:: 9:20pm.* Time zone items:: EST, PDT, GMT.* Day of week items:: Monday and others.* Relative items in date strings:: next tuesday, 2 years ago.* Pure numbers in date strings:: 19931219, 1440.* Seconds since the Epoch:: @1078100502.* Specifying time zone rules:: TZ="America/New_York", TZ="UTC0".* Authors of get_date:: Bellovin, Eggert, Salz, Berets, et al.Opening the software toolbox* Toolbox introduction:: Toolbox introduction* I/O redirection:: I/O redirection* The who command:: The `who' command* The cut command:: The `cut' command* The sort command:: The `sort' command* The uniq command:: The `uniq' command* Putting the tools together:: Putting the tools togetherCopying This Manual* GNU Free Documentation License:: Copying and sharing this manual.File: coreutils.info, Node: Introduction, Next: Common options, Prev: Top, Up: Top1 Introduction**************This manual is a work in progress: many sections make no attempt toexplain basic concepts in a way suitable for novices. Thus, if you areinterested, please get involved in improving this manual. The entireGNU community will benefit.The GNU utilities documented here are mostly compatible with thePOSIX standard. Please report bugs to <bug-coreutils@gnu.org>.Remember to include the version number, machine architecture, inputfiles, and any other information needed to reproduce the bug: yourinput, what you expected, what you got, and why it is wrong. Diffs arewelcome, but please include a description of the problem as well, sincethis is sometimes difficult to infer. *Note Bugs: (gcc)Bugs.This manual was originally derived from the Unix man pages in thedistributions, which were written by David MacKenzie and updated by JimMeyering. What you are reading now is the authoritative documentationfor these utilities; the man pages are no longer being maintained. Theoriginal `fmt' man page was written by Ross Paterson. Franc,ois Pinarddid the initial conversion to Texinfo format. Karl Berry did theindexing, some reorganization, and editing of the results. BrianYoumans of the Free Software Foundation office staff combined themanuals for textutils, fileutils, and sh-utils to produce the presentomnibus manual. Richard Stallman contributed his usual invaluableinsights to the overall process.File: coreutils.info, Node: Common options, Next: Output of entire files, Prev: Introduction, Up: Top2 Common options****************Certain options are available in all of these programs. Rather thanwriting identical descriptions for each of the programs, they aredescribed here. (In fact, every GNU program accepts (or should accept)these options.)Normally options and operands can appear in any order, and programsact as if all the options appear before any operands. For example,`sort -r passwd -t :' acts like `sort -r -t : passwd', since `:' is anoption-argument of `-t'. However, if the `POSIXLY_CORRECT' environmentvariable is set, options must appear before operands, unless otherwisespecified for a particular command.A few programs can usefully have trailing operands with leading `-'.With such a program, options must precede operands even if`POSIXLY_CORRECT' is not set, and this fact is noted in the programdescription. For example, the `env' command's options must appearbefore its operands, since in some cases the operands specify a commandthat itself contains options.Most programs that accept long options recognize unambiguousabbreviations of those options. For example, `rmdir--ignore-fail-on-non-empty' can be invoked as `rmdir --ignore-fail' oreven `rmdir --i'. Ambiguous options, such as `ls --h', are identifiedas such.Some of these programs recognize the `--help' and `--version'options only when one of them is the sole command line argument. Forthese programs, abbreviations of the long options are not alwaysrecognized.`--help'Print a usage message listing all available options, then exitsuccessfully.`--version'Print the version number, then exit successfully.`--'Delimit the option list. Later arguments, if any, are treated asoperands even if they begin with `-'. For example, `sort -- -r'reads from the file named `-r'.A single `-' operand is not really an option, though it looks likeone. It stands for standard input, or for standard output if that isclear from the context. For example, `sort -' reads from standardinput, and is equivalent to plain `sort', and `tee -' writes an extracopy of its input to standard output. Unless otherwise specified, `-'can appear as any operand that requires a file name.* Menu:* Exit status:: Indicating program success or failure.* Backup options:: -b -S, in some programs.* Block size:: BLOCK_SIZE and --block-size, in some programs.* Signal specifications:: Specifying signals using the --signal option.* Disambiguating names and IDs:: chgrp and chown owner and group syntax* Random sources:: --random-source, in some programs.* Target directory:: Specifying a target directory, in some programs.* Trailing slashes:: --strip-trailing-slashes, in some programs.* Traversing symlinks:: -H, -L, or -P, in some programs.* Treating / specially:: --preserve-root and --no-preserve-root.* Special built-in utilities:: `break', `:', `eval', ...* Standards conformance:: Conformance to the POSIX standard.File: coreutils.info, Node: Exit status, Next: Backup options, Up: Common options2.1 Exit status===============Nearly every command invocation yields an integral "exit status" thatcan be used to change how other commands work. For the vast majorityof commands, an exit status of zero indicates success. Failure isindicated by a nonzero value--typically `1', though it may differ onunusual platforms as POSIX requires only that it be nonzero.However, some of the programs documented here do produce other exitstatus values and a few associate different meanings with the values`0' and `1'. Here are some of the exceptions: `chroot', `env', `expr',`nice', `nohup', `printenv', `sort', `su', `test', `timeout', `tty'.File: coreutils.info, Node: Backup options, Next: Block size, Prev: Exit status, Up: Common options2.2 Backup options==================Some GNU programs (at least `cp', `install', `ln', and `mv') optionallymake backups of files before writing new versions. These optionscontrol the details of these backups. The options are also brieflymentioned in the descriptions of the particular programs.`-b'`--backup[=METHOD]'Make a backup of each file that would otherwise be overwritten orremoved. Without this option, the original versions are destroyed.Use METHOD to determine the type of backups to make. When thisoption is used but METHOD is not specified, then the value of the`VERSION_CONTROL' environment variable is used. And if`VERSION_CONTROL' is not set, the default backup type is`existing'.Note that the short form of this option, `-b' does not accept anyargument. Using `-b' is equivalent to using `--backup=existing'.This option corresponds to the Emacs variable `version-control';the values for METHOD are the same as those used in Emacs. Thisoption also accepts more descriptive names. The valid METHODs are(unique abbreviations are accepted):`none'`off'Never make backups.`numbered'`t'Always make numbered backups.`existing'`nil'Make numbered backups of files that already have them, simplebackups of the others.`simple'`never'Always make simple backups. Please note `never' is not to beconfused with `none'.`-S SUFFIX'`--suffix=SUFFIX'Append SUFFIX to each backup file made with `-b'. If this optionis not specified, the value of the `SIMPLE_BACKUP_SUFFIX'environment variable is used. And if `SIMPLE_BACKUP_SUFFIX' is notset, the default is `~', just as in Emacs.File: coreutils.info, Node: Block size, Next: Signal specifications, Prev: Backup options, Up: Common options2.3 Block size==============Some GNU programs (at least `df', `du', and `ls') display sizes in"blocks". You can adjust the block size and method of display to makesizes easier to read. The block size used for display is independentof any file system block size. Fractional block counts are rounded upto the nearest integer.The default block size is chosen by examining the followingenvironment variables in turn; the first one that is set determines theblock size.`DF_BLOCK_SIZE'This specifies the default block size for the `df' command.Similarly, `DU_BLOCK_SIZE' specifies the default for `du' and`LS_BLOCK_SIZE' for `ls'.`BLOCK_SIZE'This specifies the default block size for all three commands, ifthe above command-specific environment variables are not set.`BLOCKSIZE'This specifies the default block size for all values that arenormally printed as blocks, if neither `BLOCK_SIZE' nor the abovecommand-specific environment variables are set. Unlike the otherenvironment variables, `BLOCKSIZE' does not affect values that arenormally printed as byte counts, e.g., the file sizes contained in`ls -l' output.`POSIXLY_CORRECT'If neither `COMMAND_BLOCK_SIZE', nor `BLOCK_SIZE', nor `BLOCKSIZE'is set, but this variable is set, the block size defaults to 512.If none of the above environment variables are set, the block sizecurrently defaults to 1024 bytes in most contexts, but this number maychange in the future. For `ls' file sizes, the block size defaults to1 byte.A block size specification can be a positive integer specifying thenumber of bytes per block, or it can be `human-readable' or `si' toselect a human-readable format. Integers may be followed by suffixesthat are upward compatible with the SI prefixes(http://www.bipm.fr/enus/3_SI/si-prefixes.html) for decimal multiplesand with the IEC 60027-2 prefixes for binary multiples(http://physics.nist.gov/cuu/Units/binary.html).With human-readable formats, output sizes are followed by a sizeletter such as `M' for megabytes. `BLOCK_SIZE=human-readable' usespowers of 1024; `M' stands for 1,048,576 bytes. `BLOCK_SIZE=si' issimilar, but uses powers of 1000 and appends `B'; `MB' stands for1,000,000 bytes.A block size specification preceded by `'' causes output sizes to bedisplayed with thousands separators. The `LC_NUMERIC' locale specifiesthe thousands separator and grouping. For example, in an AmericanEnglish locale, `--block-size="'1kB"' would cause a size of 1234000bytes to be displayed as `1,234'. In the default C locale, there is nothousands separator so a leading `'' has no effect.An integer block size can be followed by a suffix to specify amultiple of that size. A bare size letter, or one followed by `iB',specifies a multiple using powers of 1024. A size letter followed by`B' specifies powers of 1000 instead. For example, `1M' and `1MiB' areequivalent to `1048576', whereas `1MB' is equivalent to `1000000'.A plain suffix without a preceding integer acts as if `1' wereprepended, except that it causes a size indication to be appended tothe output. For example, `--block-size="kB"' displays 3000 as `3kB'.The following suffixes are defined. Large sizes like `1Y' may berejected by your computer due to limitations of its arithmetic.`kB'kilobyte: 10^3 = 1000.`k'`K'`KiB'kibibyte: 2^10 = 1024. `K' is special: the SI prefix is `k' andthe IEC 60027-2 prefix is `Ki', but tradition and POSIX use `k' tomean `KiB'.`MB'megabyte: 10^6 = 1,000,000.`M'`MiB'mebibyte: 2^20 = 1,048,576.`GB'gigabyte: 10^9 = 1,000,000,000.`G'`GiB'gibibyte: 2^30 = 1,073,741,824.`TB'terabyte: 10^12 = 1,000,000,000,000.`T'`TiB'tebibyte: 2^40 = 1,099,511,627,776.`PB'petabyte: 10^15 = 1,000,000,000,000,000.`P'`PiB'pebibyte: 2^50 = 1,125,899,906,842,624.`EB'exabyte: 10^18 = 1,000,000,000,000,000,000.`E'`EiB'exbibyte: 2^60 = 1,152,921,504,606,846,976.`ZB'zettabyte: 10^21 = 1,000,000,000,000,000,000,000`Z'`ZiB'2^70 = 1,180,591,620,717,411,303,424. (`Zi' is a GNU extension toIEC 60027-2.)`YB'yottabyte: 10^24 = 1,000,000,000,000,000,000,000,000.`Y'`YiB'2^80 = 1,208,925,819,614,629,174,706,176. (`Yi' is a GNUextension to IEC 60027-2.)Block size defaults can be overridden by an explicit`--block-size=SIZE' option. The `-k' option is equivalent to`--block-size=1K', which is the default unless the `POSIXLY_CORRECT'environment variable is set. The `-h' or `--human-readable' option isequivalent to `--block-size=human-readable'. The `--si' option isequivalent to `--block-size=si'.File: coreutils.info, Node: Signal specifications, Next: Disambiguating names and IDs, Prev: Block size, Up: Common options2.4 Signal specifications=========================A SIGNAL may be a signal name like `HUP', or a signal number like `1',or an exit status of a process terminated by the signal. A signal namecan be given in canonical form or prefixed by `SIG'. The case of theletters is ignored. The following signal names and numbers aresupported on all POSIX compliant systems:`HUP'1. Hangup.`INT'2. Terminal interrupt.`QUIT'3. Terminal quit.`ABRT'6. Process abort.`KILL'9. Kill (cannot be caught or ignored).`ALRM'14. Alarm Clock.`TERM'15. Termination.Other supported signal names have system-dependent correspondingnumbers. All systems conforming to POSIX 1003.1-2001 also support thefollowing signals:`BUS'Access to an undefined portion of a memory object.`CHLD'Child process terminated, stopped, or continued.`CONT'Continue executing, if stopped.`FPE'Erroneous arithmetic operation.`ILL'Illegal Instruction.`PIPE'Write on a pipe with no one to read it.`SEGV'Invalid memory reference.`STOP'Stop executing (cannot be caught or ignored).`TSTP'Terminal stop.`TTIN'Background process attempting read.`TTOU'Background process attempting write.`URG'High bandwidth data is available at a socket.`USR1'User-defined signal 1.`USR2'User-defined signal 2.POSIX 1003.1-2001 systems that support the XSI extension also supportthe following signals:`POLL'Pollable event.`PROF'Profiling timer expired.`SYS'Bad system call.`TRAP'Trace/breakpoint trap.`VTALRM'Virtual timer expired.`XCPU'CPU time limit exceeded.`XFSZ'File size limit exceeded.POSIX 1003.1-2001 systems that support the XRT extension also supportat least eight real-time signals called `RTMIN', `RTMIN+1', ...,`RTMAX-1', `RTMAX'.File: coreutils.info, Node: Disambiguating names and IDs, Next: Random sources, Prev: Signal specifications, Up: Common options2.5 chown and chgrp: Disambiguating user names and IDs======================================================Since the OWNER and GROUP arguments to `chown' and `chgrp' may bespecified as names or numeric IDs, there is an apparent ambiguity.What if a user or group _name_ is a string of digits? (1) Should thecommand interpret it as a user name or as an ID? POSIX requires that`chown' and `chgrp' first attempt to resolve the specified string as aname, and only once that fails, then try to interpret it as an ID.This is troublesome when you want to specify a numeric ID, say 42, andit must work even in a pathological situation where `42' is a user namethat maps to some other user ID, say 1000. Simply invoking `chown 42F', will set `F's owner ID to 1000--not what you intended.GNU `chown' and `chgrp' provide a way to work around this, that atthe same time may result in a significant performance improvement byeliminating a database look-up. Simply precede each numeric user IDand/or group ID with a `+', in order to force its interpretation as aninteger:chown +42 Fchgrp +$numeric_group_id another-filechown +0:+0 /GNU `chown' and `chgrp' skip the name look-up process for each`+'-prefixed string, because a string containing `+' is never a validuser or group name. This syntax is accepted on most common Unixsystems, but not on Solaris 10.---------- Footnotes ----------(1) Using a number as a user name is common in some environments.File: coreutils.info, Node: Random sources, Next: Target directory, Prev: Disambiguating names and IDs, Up: Common options2.6 Sources of random data==========================The `shuf', `shred', and `sort' commands sometimes need random data todo their work. For example, `sort -R' must choose a hash function atrandom, and it needs random data to make this selection.By default these commands use an internal pseudorandom generatorinitialized by a small amount of entropy, but can be directed to use anexternal source with the `--random-source=FILE' option. An error isreported if FILE does not contain enough bytes.For example, the device file `/dev/urandom' could be used as thesource of random data. Typically, this device gathers environmentalnoise from device drivers and other sources into an entropy pool, anduses the pool to generate random bits. If the pool is short of data,the device reuses the internal pool to produce more bits, using acryptographically secure pseudorandom number generator. But be awarethat this device is not designed for bulk random data generation and isrelatively slow.`/dev/urandom' suffices for most practical uses, but applicationsrequiring high-value or long-term protection of private data mayrequire an alternate data source like `/dev/random' or `/dev/arandom'.The set of available sources depends on your operating system.To reproduce the results of an earlier invocation of a command, youcan save some random data into a file and then use that file as therandom source in earlier and later invocations of the command.File: coreutils.info, Node: Target directory, Next: Trailing slashes, Prev: Random sources, Up: Common options2.7 Target directory====================The `cp', `install', `ln', and `mv' commands normally treat the lastoperand specially when it is a directory or a symbolic link to adirectory. For example, `cp source dest' is equivalent to `cp sourcedest/source' if `dest' is a directory. Sometimes this behavior is notexactly what is wanted, so these commands support the following optionsto allow more fine-grained control:`-T'`--no-target-directory'Do not treat the last operand specially when it is a directory or asymbolic link to a directory. This can help avoid race conditionsin programs that operate in a shared area. For example, when thecommand `mv /tmp/source /tmp/dest' succeeds, there is no guaranteethat `/tmp/source' was renamed to `/tmp/dest': it could have beenrenamed to `/tmp/dest/source' instead, if some other processcreated `/tmp/dest' as a directory. However, if `mv -T/tmp/source /tmp/dest' succeeds, there is no question that`/tmp/source' was renamed to `/tmp/dest'.In the opposite situation, where you want the last operand to betreated as a directory and want a diagnostic otherwise, you can usethe `--target-directory' (`-t') option.`-t DIRECTORY'`--target-directory=DIRECTORY'Use DIRECTORY as the directory component of each destination filename.The interface for most programs is that after processing optionsand a finite (possibly zero) number of fixed-position arguments,the remaining argument list is either expected to be empty, or isa list of items (usually files) that will all be handledidentically. The `xargs' program is designed to work well withthis convention.The commands in the `mv'-family are unusual in that they take avariable number of arguments with a special case at the _end_(namely, the target directory). This makes it nontrivial toperform some operations, e.g., "move all files from here to../d/", because `mv * ../d/' might exhaust the argument space, and`ls | xargs ...' doesn't have a clean way to specify an extrafinal argument for each invocation of the subject command. (Itcan be done by going through a shell command, but that requiresmore human labor and brain power than it should.)The `--target-directory' (`-t') option allows the `cp', `install',`ln', and `mv' programs to be used conveniently with `xargs'. Forexample, you can move the files from the current directory to asibling directory, `d' like this:ls | xargs mv -t ../d --However, this doesn't move files whose names begin with `.'. Ifyou use the GNU `find' program, you can move those files too, withthis command:find . -mindepth 1 -maxdepth 1 \| xargs mv -t ../dBut both of the above approaches fail if there are no files in thecurrent directory, or if any file has a name containing a blank orsome other special characters. The following example removesthose limitations and requires both GNU `find' and GNU `xargs':find . -mindepth 1 -maxdepth 1 -print0 \| xargs --null --no-run-if-empty \mv -t ../dThe `--target-directory' (`-t') and `--no-target-directory' (`-T')options cannot be combined.File: coreutils.info, Node: Trailing slashes, Next: Traversing symlinks, Prev: Target directory, Up: Common options2.8 Trailing slashes====================Some GNU programs (at least `cp' and `mv') allow you to remove anytrailing slashes from each SOURCE argument before operating on it. The`--strip-trailing-slashes' option enables this behavior.This is useful when a SOURCE argument may have a trailing slash andspecify a symbolic link to a directory. This scenario is in fact rathercommon because some shells can automatically append a trailing slashwhen performing file name completion on such symbolic links. Withoutthis option, `mv', for example, (via the system's rename function) mustinterpret a trailing slash as a request to dereference the symbolic linkand so must rename the indirectly referenced _directory_ and not thesymbolic link. Although it may seem surprising that such behavior bethe default, it is required by POSIX and is consistent with other partsof that standard.File: coreutils.info, Node: Traversing symlinks, Next: Treating / specially, Prev: Trailing slashes, Up: Common options2.9 Traversing symlinks=======================The following options modify how `chown' and `chgrp' traverse ahierarchy when the `--recursive' (`-R') option is also specified. Ifmore than one of the following options is specified, only the final onetakes effect. These options specify whether processing a symbolic linkto a directory entails operating on just the symbolic link or on allfiles in the hierarchy rooted at that directory.These options are independent of `--dereference' and`--no-dereference' (`-h'), which control whether to modify a symlink orits referent.`-H'If `--recursive' (`-R') is specified and a command line argumentis a symbolic link to a directory, traverse it.`-L'In a recursive traversal, traverse every symbolic link to adirectory that is encountered.`-P'Do not traverse any symbolic links. This is the default if noneof `-H', `-L', or `-P' is specified.File: coreutils.info, Node: Treating / specially, Next: Special built-in utilities, Prev: Traversing symlinks, Up: Common options2.10 Treating `/' specially===========================Certain commands can operate destructively on entire hierarchies. Forexample, if a user with appropriate privileges mistakenly runs `rm -rf/ tmp/junk', that may remove all files on the entire system. Sincethere are so few legitimate uses for such a command, GNU `rm' normallydeclines to operate on any directory that resolves to `/'. If youreally want to try to remove all the files on your system, you can usethe `--no-preserve-root' option, but the default behavior, specified bythe `--preserve-option', is safer for most purposes.The commands `chgrp', `chmod' and `chown' can also operatedestructively on entire hierarchies, so they too support these options.Although, unlike `rm', they don't actually unlink files, these commandsare arguably more dangerous when operating recursively on `/', sincethey often work much more quickly, and hence damage more files beforean alert user can interrupt them. Tradition and POSIX require thesecommands to operate recursively on `/', so they default to`--no-preserve-root', but using the `--preserve-root' option makes themsafer for most purposes. For convenience you can specify`--preserve-root' in an alias or in a shell function.Note that the `--preserve-root' option also ensures that `chgrp' and`chown' do not modify `/' even when dereferencing a symlink pointing to`/'.File: coreutils.info, Node: Special built-in utilities, Next: Standards conformance, Prev: Treating / specially, Up: Common options2.11 Special built-in utilities===============================Some programs like `nice' can invoke other programs; for example, thecommand `nice cat file' invokes the program `cat' by executing thecommand `cat file'. However, "special built-in utilities" like `exit'cannot be invoked this way. For example, the command `nice exit' doesnot have a well-defined behavior: it may generate an error messageinstead of exiting.Here is a list of the special built-in utilities that arestandardized by POSIX 1003.1-2004.. : break continue eval exec exit export readonly return set shifttimes trap unsetFor example, because `.', `:', and `exec' are special, the commands`nice . foo.sh', `nice :', and `nice exec pwd' do not work as you mightexpect.Many shells extend this list. For example, Bash has several extraspecial built-in utilities like `history', and `suspend', and with Bashthe command `nice suspend' generates an error message instead ofsuspending.File: coreutils.info, Node: Standards conformance, Prev: Special built-in utilities, Up: Common options2.12 Standards conformance==========================In a few cases, the GNU utilities' default behavior is incompatiblewith the POSIX standard. To suppress these incompatibilities, definethe `POSIXLY_CORRECT' environment variable. Unless you are checkingfor POSIX conformance, you probably do not need to define`POSIXLY_CORRECT'.Newer versions of POSIX are occasionally incompatible with olderversions. For example, older versions of POSIX required the command`sort +1' to sort based on the second and succeeding fields in eachinput line, but starting with POSIX 1003.1-2001 the same command isrequired to sort the file named `+1', and you must instead use thecommand `sort -k 2' to get the field-based sort.The GNU utilities normally conform to the version of POSIX that isstandard for your system. To cause them to conform to a differentversion of POSIX, define the `_POSIX2_VERSION' environment variable toa value of the form YYYYMM specifying the year and month the standardwas adopted. Two values are currently supported for `_POSIX2_VERSION':`199209' stands for POSIX 1003.2-1992, and `200112' stands for POSIX1003.1-2001. For example, if you have a newer system but are runningsoftware that assumes an older version of POSIX and uses `sort +1' or`tail +10', you can work around any compatibility problems by setting`_POSIX2_VERSION=199209' in your environment.File: coreutils.info, Node: Output of entire files, Next: Formatting file contents, Prev: Common options, Up: Top3 Output of entire files************************These commands read and write entire files, possibly transforming themin some way.* Menu:* cat invocation:: Concatenate and write files.* tac invocation:: Concatenate and write files in reverse.* nl invocation:: Number lines and write files.* od invocation:: Write files in octal or other formats.* base64 invocation:: Transform data into printable data.File: coreutils.info, Node: cat invocation, Next: tac invocation, Up: Output of entire files3.1 `cat': Concatenate and write files======================================`cat' copies each FILE (`-' means standard input), or standard input ifnone are given, to standard output. Synopsis:cat [OPTION] [FILE]...The program accepts the following options. Also see *note Commonoptions::.`-A'`--show-all'Equivalent to `-vET'.`-b'`--number-nonblank'Number all nonempty output lines, starting with 1.`-e'Equivalent to `-vE'.`-E'`--show-ends'Display a `$' after the end of each line.`-n'`--number'Number all output lines, starting with 1.`-s'`--squeeze-blank'Suppress repeated adjacent empty lines; output just one empty lineinstead of several.`-t'Equivalent to `-vT'.`-T'`--show-tabs'Display TAB characters as `^I'.`-u'Ignored; for POSIX compatibility.`-v'`--show-nonprinting'Display control characters except for LFD and TAB using `^'notation and precede characters that have the high bit set with`M-'.On systems like MS-DOS that distinguish between text and binaryfiles, `cat' normally reads and writes in binary mode. However, `cat'reads in text mode if one of the options `-bensAE' is used or if `cat'is reading from standard input and standard input is a terminal.Similarly, `cat' writes in text mode if one of the options `-bensAE' isused or if standard output is a terminal.An exit status of zero indicates success, and a nonzero valueindicates failure.Examples:# Output f's contents, then standard input, then g's contents.cat f - g# Copy standard input to standard output.catFile: coreutils.info, Node: tac invocation, Next: nl invocation, Prev: cat invocation, Up: Output of entire files3.2 `tac': Concatenate and write files in reverse=================================================`tac' copies each FILE (`-' means standard input), or standard input ifnone are given, to standard output, reversing the records (lines bydefault) in each separately. Synopsis:tac [OPTION]... [FILE]..."Records" are separated by instances of a string (newline bydefault). By default, this separator string is attached to the end ofthe record that it follows in the file.The program accepts the following options. Also see *note Commonoptions::.`-b'`--before'The separator is attached to the beginning of the record that itprecedes in the file.`-r'`--regex'Treat the separator string as a regular expression. Users of `tac'on MS-DOS/MS-Windows should note that, since `tac' reads files inbinary mode, each line of a text file might end with a CR/LF pairinstead of the Unix-style LF.`-s SEPARATOR'`--separator=SEPARATOR'Use SEPARATOR as the record separator, instead of newline.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: nl invocation, Next: od invocation, Prev: tac invocation, Up: Output of entire files3.3 `nl': Number lines and write files======================================`nl' writes each FILE (`-' means standard input), or standard input ifnone are given, to standard output, with line numbers added to some orall of the lines. Synopsis:nl [OPTION]... [FILE]...`nl' decomposes its input into (logical) pages; by default, the linenumber is reset to 1 at the top of each logical page. `nl' treats allof the input files as a single document; it does not reset line numbersor logical pages between files.A logical page consists of three sections: header, body, and footer.Any of the sections can be empty. Each can be numbered in a differentstyle from the others.The beginnings of the sections of logical pages are indicated in theinput file by a line containing exactly one of these delimiter strings:`\:\:\:'start of header;`\:\:'start of body;`\:'start of footer.The two characters from which these strings are made can be changedfrom `\' and `:' via options (see below), but the pattern and length ofeach string cannot be changed.A section delimiter is replaced by an empty line on output. Any textthat comes before the first section delimiter string in the input fileis considered to be part of a body section, so `nl' treats a file thatcontains no section delimiters as a single body section.The program accepts the following options. Also see *note Commonoptions::.`-b STYLE'`--body-numbering=STYLE'Select the numbering style for lines in the body section of eachlogical page. When a line is not numbered, the current line numberis not incremented, but the line number separator character isstill prepended to the line. The styles are:`a'number all lines,`t'number only nonempty lines (default for body),`n'do not number lines (default for header and footer),`pBRE'number only lines that contain a match for the basic regularexpression BRE. *Note Regular Expressions: (grep)RegularExpressions.`-d CD'`--section-delimiter=CD'Set the section delimiter characters to CD; default is `\:'. Ifonly C is given, the second remains `:'. (Remember to protect `\'or other metacharacters from shell expansion with quotes or extrabackslashes.)`-f STYLE'`--footer-numbering=STYLE'Analogous to `--body-numbering'.`-h STYLE'`--header-numbering=STYLE'Analogous to `--body-numbering'.`-i NUMBER'`--page-increment=NUMBER'Increment line numbers by NUMBER (default 1).`-l NUMBER'`--join-blank-lines=NUMBER'Consider NUMBER (default 1) consecutive empty lines to be onelogical line for numbering, and only number the last one. Wherefewer than NUMBER consecutive empty lines occur, do not numberthem. An empty line is one that contains no characters, not evenspaces or tabs.`-n FORMAT'`--number-format=FORMAT'Select the line numbering format (default is `rn'):`ln'left justified, no leading zeros;`rn'right justified, no leading zeros;`rz'right justified, leading zeros.`-p'`--no-renumber'Do not reset the line number at the start of a logical page.`-s STRING'`--number-separator=STRING'Separate the line number from the text line in the output withSTRING (default is the TAB character).`-v NUMBER'`--starting-line-number=NUMBER'Set the initial line number on each logical page to NUMBER(default 1).`-w NUMBER'`--number-width=NUMBER'Use NUMBER characters for line numbers (default 6).An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: od invocation, Next: base64 invocation, Prev: nl invocation, Up: Output of entire files3.4 `od': Write files in octal or other formats===============================================`od' writes an unambiguous representation of each FILE (`-' meansstandard input), or standard input if none are given. Synopses:od [OPTION]... [FILE]...od [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]]od [OPTION]... --traditional [FILE] [[+]OFFSET[.][b] [[+]LABEL[.][b]]]Each line of output consists of the offset in the input, followed bygroups of data from the file. By default, `od' prints the offset inoctal, and each group of file data is a C `short int''s worth of inputprinted as a single octal number.If OFFSET is given, it specifies how many input bytes to skip beforeformatting and writing. By default, it is interpreted as an octalnumber, but the optional trailing decimal point causes it to beinterpreted as decimal. If no decimal is specified and the offsetbegins with `0x' or `0X' it is interpreted as a hexadecimal number. Ifthere is a trailing `b', the number of bytes skipped will be OFFSETmultiplied by 512.If a command is of both the first and second forms, the second formis assumed if the last operand begins with `+' or (if there are twooperands) a digit. For example, in `od foo 10' and `od +10' the `10'is an offset, whereas in `od 10' the `10' is a file name.The program accepts the following options. Also see *note Commonoptions::.`-A RADIX'`--address-radix=RADIX'Select the base in which file offsets are printed. RADIX can beone of the following:`d'decimal;`o'octal;`x'hexadecimal;`n'none (do not print offsets).The default is octal.`-j BYTES'`--skip-bytes=BYTES'Skip BYTES input bytes before formatting and writing. If BYTESbegins with `0x' or `0X', it is interpreted in hexadecimal;otherwise, if it begins with `0', in octal; otherwise, in decimal.BYTES is a number which may have one of the followingmultiplicative suffixes:`b' => 512 ("blocks")`KB' => 1000 (KiloBytes)`K' => 1024 (KibiBytes)`MB' => 1000*1000 (MegaBytes)`M' => 1024*1024 (MebiBytes)`GB' => 1000*1000*1000 (GigaBytes)`G' => 1024*1024*1024 (GibiBytes)and so on for `T', `P', `E', `Z', and `Y'.`-N BYTES'`--read-bytes=BYTES'Output at most BYTES bytes of the input. Prefixes and suffixes on`bytes' are interpreted as for the `-j' option.`-S BYTES'`--strings[=BYTES]'Instead of the normal output, output only "string constants": atleast BYTES consecutive ASCII graphic characters, followed by azero byte (ASCII NUL). Prefixes and suffixes on `bytes' areinterpreted as for the `-j' option.If N is omitted with `--strings', the default is 3.`-t TYPE'`--format=TYPE'Select the format in which to output the file data. TYPE is astring of one or more of the below type indicator characters. Ifyou include more than one type indicator character in a single TYPEstring, or use this option more than once, `od' writes one copy ofeach output line using each of the data types that you specified,in the order that you specified.Adding a trailing "z" to any type specification appends a displayof the ASCII character representation of the printable charactersto the output line generated by the type specification.`a'named character, ignoring high-order bit`c'ASCII character or backslash escape,`d'signed decimal`f'floating point`o'octal`u'unsigned decimal`x'hexadecimalThe type `a' outputs things like `sp' for space, `nl' for newline,and `nul' for a zero byte. Only the least significant seven bitsof each byte is used; the high-order bit is ignored. Type `c'outputs ` ', `\n', and `\0', respectively.Except for types `a' and `c', you can specify the number of bytesto use in interpreting each number in the given data type byfollowing the type indicator character with a decimal integer.Alternately, you can specify the size of one of the C compiler'sbuilt-in data types by following the type indicator character withone of the following characters. For integers (`d', `o', `u',`x'):`C'char`S'short`I'int`L'longFor floating point (`f'):FfloatDdoubleLlong double`-v'`--output-duplicates'Output consecutive lines that are identical. By default, when twoor more consecutive output lines would be identical, `od' outputsonly the first line, and puts just an asterisk on the followingline to indicate the elision.`-w[N]'`--width[=N]'Dump `n' input bytes per output line. This must be a multiple ofthe least common multiple of the sizes associated with thespecified output types.If this option is not given at all, the default is 16. If N isomitted, the default is 32.The next several options are shorthands for format specifications.GNU `od' accepts any combination of shorthands and format specificationoptions. These options accumulate.`-a'Output as named characters. Equivalent to `-t a'.`-b'Output as octal bytes. Equivalent to `-t o1'.`-c'Output as ASCII characters or backslash escapes. Equivalent to`-t c'.`-d'Output as unsigned decimal two-byte units. Equivalent to `-t u2'.`-f'Output as floats. Equivalent to `-t fF'.`-i'Output as decimal ints. Equivalent to `-t dI'.`-l'Output as decimal long ints. Equivalent to `-t dL'.`-o'Output as octal two-byte units. Equivalent to `-t o2'.`-s'Output as decimal two-byte units. Equivalent to `-t d2'.`-x'Output as hexadecimal two-byte units. Equivalent to `-t x2'.`--traditional'Recognize the non-option label argument that traditional `od'accepted. The following syntax:od --traditional [FILE] [[+]OFFSET[.][b] [[+]LABEL[.][b]]]can be used to specify at most one file and optional argumentsspecifying an offset and a pseudo-start address, LABEL. The LABELargument is interpreted just like OFFSET, but it specifies aninitial pseudo-address. The pseudo-addresses are displayed inparentheses following any normal address.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: base64 invocation, Prev: od invocation, Up: Output of entire files3.5 `base64': Transform data into printable data.=================================================`base64' transforms data read from a file, or standard input, into (orfrom) base64 encoded form. The base64 encoded form uses printableASCII characters to represent binary data. Synopses:base64 [OPTION]... [FILE]base64 --decode [OPTION]... [FILE]The base64 encoding expands data to roughly 133% of the original.The format conforms to RFC 4648(ftp://ftp.rfc-editor.org/in-notes/rfc4648.txt).The program accepts the following options. Also see *note Commonoptions::.`-w COLS'`--wrap=COLS'During encoding, wrap lines after COLS characters. This must be apositive number.The default is to wrap after 76 characters. Use the value 0 todisable line wrapping altogether.`-d'`--decode'Change the mode of operation, from the default of encoding data, todecoding data. Input is expected to be base64 encoded data, andthe output will be the original data.`-i'`--ignore-garbage'When decoding, newlines are always accepted. During decoding,ignore unrecognized bytes, to permit distorted data to be decoded.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Formatting file contents, Next: Output of parts of files, Prev: Output of entire files, Up: Top4 Formatting file contents**************************These commands reformat the contents of files.* Menu:* fmt invocation:: Reformat paragraph text.* pr invocation:: Paginate or columnate files for printing.* fold invocation:: Wrap input lines to fit in specified width.File: coreutils.info, Node: fmt invocation, Next: pr invocation, Up: Formatting file contents4.1 `fmt': Reformat paragraph text==================================`fmt' fills and joins lines to produce output lines of (at most) agiven number of characters (75 by default). Synopsis:fmt [OPTION]... [FILE]...`fmt' reads from the specified FILE arguments (or standard input ifnone are given), and writes to standard output.By default, blank lines, spaces between words, and indentation arepreserved in the output; successive input lines with differentindentation are not joined; tabs are expanded on input and introduced onoutput.`fmt' prefers breaking lines at the end of a sentence, and tries toavoid line breaks after the first word of a sentence or before the lastword of a sentence. A "sentence break" is defined as either the end ofa paragraph or a word ending in any of `.?!', followed by two spaces orend of line, ignoring any intervening parentheses or quotes. Like TeX,`fmt' reads entire "paragraphs" before choosing line breaks; thealgorithm is a variant of that given by Donald E. Knuth and Michael F.Plass in "Breaking Paragraphs Into Lines", `Software--Practice &Experience' 11, 11 (November 1981), 1119-1184.The program accepts the following options. Also see *note Commonoptions::.`-C'`--compare'Compare each pair of source and destination files, and if thedestination has identical content and any specified owner, group,permissions, and possibly SELinux context, then do not modify thedestination at all.`-c'`--crown-margin'"Crown margin" mode: preserve the indentation of the first twolines within a paragraph, and align the left margin of eachsubsequent line with that of the second line.`-t'`--tagged-paragraph'"Tagged paragraph" mode: like crown margin mode, except that ifindentation of the first line of a paragraph is the same as theindentation of the second, the first line is treated as a one-lineparagraph.`-s'`--split-only'Split lines only. Do not join short lines to form longer ones.This prevents sample lines of code, and other such "formatted"text from being unduly combined.`-u'`--uniform-spacing'Uniform spacing. Reduce spacing between words to one space, andspacing between sentences to two spaces.`-WIDTH'`-w WIDTH'`--width=WIDTH'Fill output lines up to WIDTH characters (default 75). `fmt'initially tries to make lines about 7% shorter than this, to giveit room to balance line lengths.`-p PREFIX'`--prefix=PREFIX'Only lines beginning with PREFIX (possibly preceded by whitespace)are subject to formatting. The prefix and any precedingwhitespace are stripped for the formatting and then re-attached toeach formatted output line. One use is to format certain kinds ofprogram comments, while leaving the code unchanged.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: pr invocation, Next: fold invocation, Prev: fmt invocation, Up: Formatting file contents4.2 `pr': Paginate or columnate files for printing==================================================`pr' writes each FILE (`-' means standard input), or standard input ifnone are given, to standard output, paginating and optionallyoutputting in multicolumn format; optionally merges all FILEs, printingall in parallel, one per column. Synopsis:pr [OPTION]... [FILE]...By default, a 5-line header is printed at each page: two blank lines;a line with the date, the file name, and the page count; and two moreblank lines. A footer of five blank lines is also printed. Thedefault PAGE_LENGTH is 66 lines. The default number of text lines istherefore 56. The text line of the header takes the form `DATE STRINGPAGE', with spaces inserted around STRING so that the line takes up thefull PAGE_WIDTH. Here, DATE is the date (see the `-D' or`--date-format' option for details), STRING is the centered headerstring, and PAGE identifies the page number. The `LC_MESSAGES' localecategory affects the spelling of PAGE; in the default C locale, it is`Page NUMBER' where NUMBER is the decimal page number.Form feeds in the input cause page breaks in the output. Multipleform feeds produce empty pages.Columns are of equal width, separated by an optional string (defaultis `space'). For multicolumn output, lines will always be truncated toPAGE_WIDTH (default 72), unless you use the `-J' option. For singlecolumn output no line truncation occurs by default. Use `-W' option totruncate lines in that case.The following changes were made in version 1.22i and apply to laterversions of `pr': - Brian* Some small LETTER OPTIONS (`-s', `-w') have been redefined forbetter POSIX compliance. The output of some further cases hasbeen adapted to other Unix systems. These changes are notcompatible with earlier versions of the program.* Some NEW CAPITAL LETTER options (`-J', `-S', `-W') have beenintroduced to turn off unexpected interferences of small letteroptions. The `-N' option and the second argument LAST_PAGE of`+FIRST_PAGE' offer more flexibility. The detailed handling ofform feeds set in the input files requires the `-T' option.* Capital letter options override small letter ones.* Some of the option-arguments (compare `-s', `-e', `-i', `-n')cannot be specified as separate arguments from the precedingoption letter (already stated in the POSIX specification).The program accepts the following options. Also see *note Commonoptions::.`+FIRST_PAGE[:LAST_PAGE]'`--pages=FIRST_PAGE[:LAST_PAGE]'Begin printing with page FIRST_PAGE and stop with LAST_PAGE.Missing `:LAST_PAGE' implies end of file. While estimating thenumber of skipped pages each form feed in the input file resultsin a new page. Page counting with and without `+FIRST_PAGE' isidentical. By default, counting starts with the first page ofinput file (not first page printed). Line numbering may bealtered by `-N' option.`-COLUMN'`--columns=COLUMN'With each single FILE, produce COLUMN columns of output (defaultis 1) and print columns down, unless `-a' is used. The columnwidth is automatically decreased as COLUMN increases; unless youuse the `-W/-w' option to increase PAGE_WIDTH as well. Thisoption might well cause some lines to be truncated. The number oflines in the columns on each page are balanced. The options `-e'and `-i' are on for multiple text-column output. Together with`-J' option column alignment and line truncation is turned off.Lines of full length are joined in a free field format and `-S'option may set field separators. `-COLUMN' may not be used with`-m' option.`-a'`--across'With each single FILE, print columns across rather than down. The`-COLUMN' option must be given with COLUMN greater than one. If aline is too long to fit in a column, it is truncated.`-c'`--show-control-chars'Print control characters using hat notation (e.g., `^G'); printother nonprinting characters in octal backslash notation. Bydefault, nonprinting characters are not changed.`-d'`--double-space'Double space the output.`-D FORMAT'`--date-format=FORMAT'Format header dates using FORMAT, using the same conventions asfor the command `date +FORMAT'; *Note date invocation::. Exceptfor directives, which start with `%', characters in FORMAT areprinted unchanged. You can use this option to specify anarbitrary string in place of the header date, e.g.,`--date-format="Monday morning"'.The default date format is `%Y-%m-%d %H:%M' (for example,`2001-12-04 23:59'); but if the `POSIXLY_CORRECT' environmentvariable is set and the `LC_TIME' locale category specifies thePOSIX locale, the default is `%b %e %H:%M %Y' (for example, `Dec4 23:59 2001'.Time stamps are listed according to the time zone rules specifiedby the `TZ' environment variable, or by the system default rules if`TZ' is not set. *Note Specifying the Time Zone with `TZ':(libc)TZ Variable.`-e[IN-TABCHAR[IN-TABWIDTH]]'`--expand-tabs[=IN-TABCHAR[IN-TABWIDTH]]'Expand TABs to spaces on input. Optional argument IN-TABCHAR isthe input tab character (default is the TAB character). Secondoptional argument IN-TABWIDTH is the input tab character's width(default is 8).`-f'`-F'`--form-feed'Use a form feed instead of newlines to separate output pages.This does not alter the default page length of 66 lines.`-h HEADER'`--header=HEADER'Replace the file name in the header with the centered stringHEADER. When using the shell, HEADER should be quoted and shouldbe separated from `-h' by a space.`-i[OUT-TABCHAR[OUT-TABWIDTH]]'`--output-tabs[=OUT-TABCHAR[OUT-TABWIDTH]]'Replace spaces with TABs on output. Optional argument OUT-TABCHARis the output tab character (default is the TAB character).Second optional argument OUT-TABWIDTH is the output tabcharacter's width (default is 8).`-J'`--join-lines'Merge lines of full length. Used together with the column options`-COLUMN', `-a -COLUMN' or `-m'. Turns off `-W/-w' linetruncation; no column alignment used; may be used with`--sep-string[=STRING]'. `-J' has been introduced (together with`-W' and `--sep-string') to disentangle the old (POSIX-compliant)options `-w' and `-s' along with the three column options.`-l PAGE_LENGTH'`--length=PAGE_LENGTH'Set the page length to PAGE_LENGTH (default 66) lines, includingthe lines of the header [and the footer]. If PAGE_LENGTH is lessthan or equal to 10, the header and footer are omitted, as if the`-t' option had been given.`-m'`--merge'Merge and print all FILEs in parallel, one in each column. If aline is too long to fit in a column, it is truncated, unless the`-J' option is used. `--sep-string[=STRING]' may be used. Emptypages in some FILEs (form feeds set) produce empty columns, stillmarked by STRING. The result is a continuous line numbering andcolumn marking throughout the whole merged file. Completely emptymerged pages show no separators or line numbers. The defaultheader becomes `DATE PAGE' with spaces inserted in the middle; thismay be used with the `-h' or `--header' option to fill up themiddle blank part.`-n[NUMBER-SEPARATOR[DIGITS]]'`--number-lines[=NUMBER-SEPARATOR[DIGITS]]'Provide DIGITS digit line numbering (default for DIGITS is 5).With multicolumn output the number occupies the first DIGITScolumn positions of each text column or only each line of `-m'output. With single column output the number precedes each linejust as `-m' does. Default counting of the line numbers startswith the first line of the input file (not the first line printed,compare the `--page' option and `-N' option). Optional argumentNUMBER-SEPARATOR is the character appended to the line number toseparate it from the text followed. The default separator is theTAB character. In a strict sense a TAB is always printed withsingle column output only. The TAB width varies with the TABposition, e.g., with the left MARGIN specified by `-o' option.With multicolumn output priority is given to `equal width ofoutput columns' (a POSIX specification). The TAB width is fixedto the value of the first column and does not change withdifferent values of left MARGIN. That means a fixed number ofspaces is always printed in the place of the NUMBER-SEPARATOR TAB.The tabification depends upon the output position.`-N LINE_NUMBER'`--first-line-number=LINE_NUMBER'Start line counting with the number LINE_NUMBER at first line offirst page printed (in most cases not the first line of the inputfile).`-o MARGIN'`--indent=MARGIN'Indent each line with a margin MARGIN spaces wide (default iszero). The total page width is the size of the margin plus thePAGE_WIDTH set with the `-W/-w' option. A limited overflow mayoccur with numbered single column output (compare `-n' option).`-r'`--no-file-warnings'Do not print a warning message when an argument FILE cannot beopened. (The exit status will still be nonzero, however.)`-s[CHAR]'`--separator[=CHAR]'Separate columns by a single character CHAR. The default for CHARis the TAB character without `-w' and `no character' with `-w'.Without `-s' the default separator `space' is set. `-s[char]'turns off line truncation of all three column options(`-COLUMN'|`-a -COLUMN'|`-m') unless `-w' is set. This is aPOSIX-compliant formulation.`-SSTRING'`--sep-string[=STRING]'Use STRING to separate output columns. The `-S' option doesn'taffect the `-W/-w' option, unlike the `-s' option which does. Itdoes not affect line truncation or column alignment. Without`-S', and with `-J', `pr' uses the default output separator, TAB.Without `-S' or `-J', `pr' uses a `space' (same as `-S" "').`--sep-string' with no `=STRING' is equivalent to`--sep-string=""'.`-t'`--omit-header'Do not print the usual header [and footer] on each page, and donot fill out the bottom of pages (with blank lines or a formfeed). No page structure is produced, but form feeds set in theinput files are retained. The predefined pagination is notchanged. `-t' or `-T' may be useful together with other options;e.g.: `-t -e4', expand TAB characters in the input file to 4spaces but don't make any other changes. Use of `-t' overrides`-h'.`-T'`--omit-pagination'Do not print header [and footer]. In addition eliminate all formfeeds set in the input files.`-v'`--show-nonprinting'Print nonprinting characters in octal backslash notation.`-w PAGE_WIDTH'`--width=PAGE_WIDTH'Set page width to PAGE_WIDTH characters for multiple text-columnoutput only (default for PAGE_WIDTH is 72). `-s[CHAR]' turns offthe default page width and any line truncation and columnalignment. Lines of full length are merged, regardless of thecolumn options set. No PAGE_WIDTH setting is possible with singlecolumn output. A POSIX-compliant formulation.`-W PAGE_WIDTH'`--page_width=PAGE_WIDTH'Set the page width to PAGE_WIDTH characters. That's valid with andwithout a column option. Text lines are truncated, unless `-J' isused. Together with one of the three column options (`-COLUMN',`-a -COLUMN' or `-m') column alignment is always used. Theseparator options `-S' or `-s' don't affect the `-W' option.Default is 72 characters. Without `-W PAGE_WIDTH' and without anyof the column options NO line truncation is used (defined to keepdownward compatibility and to meet most frequent tasks). That'sequivalent to `-W 72 -J'. The header line is never truncated.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: fold invocation, Prev: pr invocation, Up: Formatting file contents4.3 `fold': Wrap input lines to fit in specified width======================================================`fold' writes each FILE (`-' means standard input), or standard inputif none are given, to standard output, breaking long lines. Synopsis:fold [OPTION]... [FILE]...By default, `fold' breaks lines wider than 80 columns. The outputis split into as many lines as necessary.`fold' counts screen columns by default; thus, a tab may count morethan one column, backspace decreases the column count, and carriagereturn sets the column to zero.The program accepts the following options. Also see *note Commonoptions::.`-b'`--bytes'Count bytes rather than columns, so that tabs, backspaces, andcarriage returns are each counted as taking up one column, justlike other characters.`-s'`--spaces'Break at word boundaries: the line is broken after the last blankbefore the maximum line length. If the line contains no suchblanks, the line is broken at the maximum line length as usual.`-w WIDTH'`--width=WIDTH'Use a maximum line length of WIDTH columns instead of 80.For compatibility `fold' supports an obsolete option syntax`-WIDTH'. New scripts should use `-w WIDTH' instead.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Output of parts of files, Next: Summarizing files, Prev: Formatting file contents, Up: Top5 Output of parts of files**************************These commands output pieces of the input.* Menu:* head invocation:: Output the first part of files.* tail invocation:: Output the last part of files.* split invocation:: Split a file into fixed-size pieces.* csplit invocation:: Split a file into context-determined pieces.File: coreutils.info, Node: head invocation, Next: tail invocation, Up: Output of parts of files5.1 `head': Output the first part of files==========================================`head' prints the first part (10 lines by default) of each FILE; itreads from standard input if no files are given or when given a FILE of`-'. Synopsis:head [OPTION]... [FILE]...If more than one FILE is specified, `head' prints a one-line headerconsisting of:==> FILE NAME <==before the output for each FILE.The program accepts the following options. Also see *note Commonoptions::.`-c N'`--bytes=N'Print the first N bytes, instead of initial lines. However, if Nstarts with a `-', print all but the last N bytes of each file. Nis a number which may have one of the following multiplicativesuffixes:`b' => 512 ("blocks")`KB' => 1000 (KiloBytes)`K' => 1024 (KibiBytes)`MB' => 1000*1000 (MegaBytes)`M' => 1024*1024 (MebiBytes)`GB' => 1000*1000*1000 (GigaBytes)`G' => 1024*1024*1024 (GibiBytes)and so on for `T', `P', `E', `Z', and `Y'.`-n N'`--lines=N'Output the first N lines. However, if N starts with a `-', printall but the last N lines of each file. Size multiplier suffixesare the same as with the `-c' option.`-q'`--quiet'`--silent'Never print file name headers.`-v'`--verbose'Always print file name headers.For compatibility `head' also supports an obsolete option syntax`-COUNTOPTIONS', which is recognized only if it is specified first.COUNT is a decimal number optionally followed by a size letter (`b',`k', `m') as in `-c', or `l' to mean count by lines, or other optionletters (`cqv'). Scripts intended for standard hosts should use `-cCOUNT' or `-n COUNT' instead. If your script must also run on hoststhat support only the obsolete syntax, it is usually simpler to avoid`head', e.g., by using `sed 5q' instead of `head -5'.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: tail invocation, Next: split invocation, Prev: head invocation, Up: Output of parts of files5.2 `tail': Output the last part of files=========================================`tail' prints the last part (10 lines by default) of each FILE; itreads from standard input if no files are given or when given a FILE of`-'. Synopsis:tail [OPTION]... [FILE]...If more than one FILE is specified, `tail' prints a one-line headerconsisting of:==> FILE NAME <==before the output for each FILE.GNU `tail' can output any amount of data (some other versions of`tail' cannot). It also has no `-r' option (print in reverse), sincereversing a file is really a different job from printing the end of afile; BSD `tail' (which is the one with `-r') can only reverse filesthat are at most as large as its buffer, which is typically 32 KiB. Amore reliable and versatile way to reverse files is the GNU `tac'command.The program accepts the following options. Also see *note Commonoptions::.`-c N'`--bytes=N'Output the last N bytes, instead of final lines. However, if Nstarts with a `+', start printing with the Nth byte from the startof each file, instead of from the end. N is a number which mayhave one of the following multiplicative suffixes:`b' => 512 ("blocks")`KB' => 1000 (KiloBytes)`K' => 1024 (KibiBytes)`MB' => 1000*1000 (MegaBytes)`M' => 1024*1024 (MebiBytes)`GB' => 1000*1000*1000 (GigaBytes)`G' => 1024*1024*1024 (GibiBytes)and so on for `T', `P', `E', `Z', and `Y'.`-f'`--follow[=HOW]'Loop forever trying to read more characters at the end of the file,presumably because the file is growing. If more than one file isgiven, `tail' prints a header whenever it gets output from adifferent file, to indicate which file that output is from.There are two ways to specify how you'd like to track files withthis option, but that difference is noticeable only when afollowed file is removed or renamed. If you'd like to continue totrack the end of a growing file even after it has been unlinked,use `--follow=descriptor'. This is the default behavior, but itis not useful if you're tracking a log file that may be rotated(removed or renamed, then reopened). In that case, use`--follow=name' to track the named file by reopening itperiodically to see if it has been removed and recreated by someother program.No matter which method you use, if the tracked file is determinedto have shrunk, `tail' prints a message saying the file has beentruncated and resumes tracking the end of the file from thenewly-determined endpoint.When a file is removed, `tail''s behavior depends on whether it isfollowing the name or the descriptor. When following by name,tail can detect that a file has been removed and gives a messageto that effect, and if `--retry' has been specified it willcontinue checking periodically to see if the file reappears. Whenfollowing a descriptor, tail does not detect that the file hasbeen unlinked or renamed and issues no message; even though thefile may no longer be accessible via its original name, it maystill be growing.The option values `descriptor' and `name' may be specified onlywith the long form of the option, not with `-f'.If `POSIXLY_CORRECT' is set, the `-f' option is ignored if no FILEoperand is specified and standard input is a FIFO or a pipe.`-F'This option is the same as `--follow=name --retry'. That is, tailwill attempt to reopen a file when it is removed. Should thisfail, tail will keep trying until it becomes accessible again.`--retry'This option is useful mainly when following by name (i.e., with`--follow=name'). Without this option, when tail encounters afile that doesn't exist or is otherwise inaccessible, it reportsthat fact and never checks it again.`--sleep-interval=NUMBER'Change the number of seconds to wait between iterations (thedefault is 1.0). During one iteration, every specified file ischecked to see if it has changed size. Historical implementationsof `tail' have required that NUMBER be an integer. However, GNU`tail' accepts an arbitrary floating point number (using a periodbefore any fractional digits).`--pid=PID'When following by name or by descriptor, you may specify theprocess ID, PID, of the sole writer of all FILE arguments. Then,shortly after that process terminates, tail will also terminate.This will work properly only if the writer and the tailing processare running on the same machine. For example, to save the outputof a build in a file and to watch the file grow, if you invoke`make' and `tail' like this then the tail process will stop whenyour build completes. Without this option, you would have had tokill the `tail -f' process yourself.$ make >& makerr & tail --pid=$! -f makerrIf you specify a PID that is not in use or that does not correspondto the process that is writing to the tailed files, then `tail'may terminate long before any FILEs stop growing or it may notterminate until long after the real writer has terminated. Notethat `--pid' cannot be supported on some systems; `tail' willprint a warning if this is the case.`--max-unchanged-stats=N'When tailing a file by name, if there have been N (defaultn=5) consecutive iterations for which the file has not changed,then `open'/`fstat' the file to determine if that file name isstill associated with the same device/inode-number pair as before.When following a log file that is rotated, this is approximatelythe number of seconds between when tail prints the lastpre-rotation lines and when it prints the lines that haveaccumulated in the new log file. This option is meaningful onlywhen following by name.`-n N'`--lines=N'Output the last N lines. However, if N starts with a `+', startprinting with the Nth line from the start of each file, instead offrom the end. Size multiplier suffixes are the same as with the`-c' option.`-q'`--quiet'`--silent'Never print file name headers.`-v'`--verbose'Always print file name headers.For compatibility `tail' also supports an obsolete usage `tail-[COUNT][bcl][f] [FILE]', which is recognized only if it does notconflict with the usage described above. This obsolete form usesexactly one option and at most one file. In the option, COUNT is anoptional decimal number optionally followed by a size letter (`b', `c',`l') to mean count by 512-byte blocks, bytes, or lines, optionallyfollowed by `f' which has the same meaning as `-f'.On older systems, the leading `-' can be replaced by `+' in theobsolete option syntax with the same meaning as in counts, and obsoleteusage overrides normal usage when the two conflict. This obsoletebehavior can be enabled or disabled with the `_POSIX2_VERSION'environment variable (*note Standards conformance::).Scripts intended for use on standard hosts should avoid obsoletesyntax and should use `-c COUNT[b]', `-n COUNT', and/or `-f' instead.If your script must also run on hosts that support only the obsoletesyntax, you can often rewrite it to avoid problematic usages, e.g., byusing `sed -n '$p'' rather than `tail -1'. If that's not possible, thescript can use a test like `if tail -c +1 </dev/null >/dev/null 2>&1;then ...' to decide which syntax to use.Even if your script assumes the standard behavior, you should stillbeware usages whose behaviors differ depending on the POSIX version.For example, avoid `tail - main.c', since it might be interpreted aseither `tail main.c' or as `tail -- - main.c'; avoid `tail -c 4', sinceit might mean either `tail -c4' or `tail -c 10 4'; and avoid `tail +4',since it might mean either `tail ./+4' or `tail -n +4'.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: split invocation, Next: csplit invocation, Prev: tail invocation, Up: Output of parts of files5.3 `split': Split a file into fixed-size pieces================================================`split' creates output files containing consecutive sections of INPUT(standard input if none is given or INPUT is `-'). Synopsis:split [OPTION] [INPUT [PREFIX]]By default, `split' puts 1000 lines of INPUT (or whatever is leftover for the last section), into each output file.The output files' names consist of PREFIX (`x' by default) followedby a group of characters (`aa', `ab', ... by default), such thatconcatenating the output files in traditional sorted order by file nameproduces the original input file. If the output file names areexhausted, `split' reports an error without deleting the output filesthat it did create.The program accepts the following options. Also see *note Commonoptions::.`-l LINES'`--lines=LINES'Put LINES lines of INPUT into each output file.For compatibility `split' also supports an obsolete option syntax`-LINES'. New scripts should use `-l LINES' instead.`-b SIZE'`--bytes=SIZE'Put SIZE bytes of INPUT into each output file. SIZE is a numberwhich may have one of the following multiplicative suffixes:`b' => 512 ("blocks")`KB' => 1000 (KiloBytes)`K' => 1024 (KibiBytes)`MB' => 1000*1000 (MegaBytes)`M' => 1024*1024 (MebiBytes)`GB' => 1000*1000*1000 (GigaBytes)`G' => 1024*1024*1024 (GibiBytes)and so on for `T', `P', `E', `Z', and `Y'.`-C SIZE'`--line-bytes=SIZE'Put into each output file as many complete lines of INPUT aspossible without exceeding SIZE bytes. Individual lines longerthan SIZE bytes are broken into multiple files. SIZE has the sameformat as for the `--bytes' option.`-a LENGTH'`--suffix-length=LENGTH'Use suffixes of length LENGTH. The default LENGTH is 2.`-d'`--numeric-suffixes'Use digits in suffixes rather than lower-case letters.`--verbose'Write a diagnostic just before each output file is opened.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: csplit invocation, Prev: split invocation, Up: Output of parts of files5.4 `csplit': Split a file into context-determined pieces=========================================================`csplit' creates zero or more output files containing sections of INPUT(standard input if INPUT is `-'). Synopsis:csplit [OPTION]... INPUT PATTERN...The contents of the output files are determined by the PATTERNarguments, as detailed below. An error occurs if a PATTERN argumentrefers to a nonexistent line of the input file (e.g., if no remainingline matches a given regular expression). After every PATTERN has beenmatched, any remaining input is copied into one last output file.By default, `csplit' prints the number of bytes written to eachoutput file after it has been created.The types of pattern arguments are:`N'Create an output file containing the input up to but not includingline N (a positive integer). If followed by a repeat count, alsocreate an output file containing the next N lines of the inputfile once for each repeat.`/REGEXP/[OFFSET]'Create an output file containing the current line up to (but notincluding) the next line of the input file that contains a matchfor REGEXP. The optional OFFSET is an integer. If it is given,the input up to (but not including) the matching line plus orminus OFFSET is put into the output file, and the line after thatbegins the next section of input.`%REGEXP%[OFFSET]'Like the previous type, except that it does not create an outputfile, so that section of the input file is effectively ignored.`{REPEAT-COUNT}'Repeat the previous pattern REPEAT-COUNT additional times. TheREPEAT-COUNT can either be a positive integer or an asterisk,meaning repeat as many times as necessary until the input isexhausted.The output files' names consist of a prefix (`xx' by default)followed by a suffix. By default, the suffix is an ascending sequenceof two-digit decimal numbers from `00' to `99'. In any case,concatenating the output files in sorted order by file name produces theoriginal input file.By default, if `csplit' encounters an error or receives a hangup,interrupt, quit, or terminate signal, it removes any output files thatit has created so far before it exits.The program accepts the following options. Also see *note Commonoptions::.`-f PREFIX'`--prefix=PREFIX'Use PREFIX as the output file name prefix.`-b SUFFIX'`--suffix=SUFFIX'Use SUFFIX as the output file name suffix. When this option isspecified, the suffix string must include exactly one`printf(3)'-style conversion specification, possibly includingformat specification flags, a field width, a precisionspecifications, or all of these kinds of modifiers. The formatletter must convert a binary integer argument to readable form;thus, only `d', `i', `u', `o', `x', and `X' conversions areallowed. The entire SUFFIX is given (with the current output filenumber) to `sprintf(3)' to form the file name suffixes for each ofthe individual output files in turn. If this option is used, the`--digits' option is ignored.`-n DIGITS'`--digits=DIGITS'Use output file names containing numbers that are DIGITS digitslong instead of the default 2.`-k'`--keep-files'Do not remove output files when errors are encountered.`-z'`--elide-empty-files'Suppress the generation of zero-length output files. (In caseswhere the section delimiters of the input file are supposed tomark the first lines of each of the sections, the first outputfile will generally be a zero-length file unless you use thisoption.) The output file sequence numbers always runconsecutively starting from 0, even when this option is specified.`-s'`-q'`--silent'`--quiet'Do not print counts of output file sizes.An exit status of zero indicates success, and a nonzero valueindicates failure.Here is an example of its usage. First, create an empty directoryfor the exercise, and cd into it:$ mkdir d && cd dNow, split the sequence of 1..14 on lines that end with 0 or 5:$ seq 14 | csplit - '/[05]$/' '{*}'81015Each number printed above is the size of an output file that csplithas just created. List the names of those output files:$ lsxx00 xx01 xx02Use `head' to show their contents:$ head xx*==> xx00 <==1234==> xx01 <==56789==> xx02 <==1011121314File: coreutils.info, Node: Summarizing files, Next: Operating on sorted files, Prev: Output of parts of files, Up: Top6 Summarizing files*******************These commands generate just a few numbers representing entire contentsof files.* Menu:* wc invocation:: Print newline, word, and byte counts.* sum invocation:: Print checksum and block counts.* cksum invocation:: Print CRC checksum and byte counts.* md5sum invocation:: Print or check MD5 digests.* sha1sum invocation:: Print or check SHA-1 digests.* sha2 utilities:: Print or check SHA-2 digests.File: coreutils.info, Node: wc invocation, Next: sum invocation, Up: Summarizing files6.1 `wc': Print newline, word, and byte counts==============================================`wc' counts the number of bytes, characters, whitespace-separatedwords, and newlines in each given FILE, or standard input if none aregiven or for a FILE of `-'. Synopsis:wc [OPTION]... [FILE]...`wc' prints one line of counts for each file, and if the file wasgiven as an argument, it prints the file name following the counts. Ifmore than one FILE is given, `wc' prints a final line containing thecumulative counts, with the file name `total'. The counts are printedin this order: newlines, words, characters, bytes, maximum line length.Each count is printed right-justified in a field with at least onespace between fields so that the numbers and file names normally lineup nicely in columns. The width of the count fields varies dependingon the inputs, so you should not depend on a particular field width.However, as a GNU extension, if only one count is printed, it isguaranteed to be printed without leading spaces.By default, `wc' prints three counts: the newline, words, and bytecounts. Options can specify that only certain counts be printed.Options do not undo others previously given, sowc --bytes --wordsprints both the byte counts and the word counts.With the `--max-line-length' option, `wc' prints the length of thelongest line per file, and if there is more than one file it prints themaximum (not the sum) of those lengths. The line lengths here aremeasured in screen columns, according to the current locale andassuming tab positions in every 8th column.The program accepts the following options. Also see *note Commonoptions::.`-c'`--bytes'Print only the byte counts.`-m'`--chars'Print only the character counts.`-w'`--words'Print only the word counts.`-l'`--lines'Print only the newline counts.`-L'`--max-line-length'Print only the maximum line lengths.`--files0-from=FILE'Disallow processing files named on the command line, and insteadprocess those named in file FILE; each name being terminated by azero byte (ASCII NUL). This is useful when the list of file namesis so long that it may exceed a command line length limitation.In such cases, running `wc' via `xargs' is undesirable because itsplits the list into pieces and makes `wc' print a total for eachsublist rather than for the entire list. One way to produce alist of ASCII NUL terminated file names is with GNU `find', usingits `-print0' predicate. If FILE is `-' then the ASCII NULterminated file names are read from standard input.For example, to find the length of the longest line in any `.c' or`.h' file in the current hierarchy, do this:find . -name '*.[ch]' -print0 |wc -L --files0-from=- | tail -n1An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: sum invocation, Next: cksum invocation, Prev: wc invocation, Up: Summarizing files6.2 `sum': Print checksum and block counts==========================================`sum' computes a 16-bit checksum for each given FILE, or standard inputif none are given or for a FILE of `-'. Synopsis:sum [OPTION]... [FILE]...`sum' prints the checksum for each FILE followed by the number ofblocks in the file (rounded up). If more than one FILE is given, filenames are also printed (by default). (With the `--sysv' option,corresponding file names are printed when there is at least one fileargument.)By default, GNU `sum' computes checksums using an algorithmcompatible with BSD `sum' and prints file sizes in units of 1024-byteblocks.The program accepts the following options. Also see *note Commonoptions::.`-r'Use the default (BSD compatible) algorithm. This option isincluded for compatibility with the System V `sum'. Unless `-s'was also given, it has no effect.`-s'`--sysv'Compute checksums using an algorithm compatible with System V`sum''s default, and print file sizes in units of 512-byte blocks.`sum' is provided for compatibility; the `cksum' program (see nextsection) is preferable in new applications.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: cksum invocation, Next: md5sum invocation, Prev: sum invocation, Up: Summarizing files6.3 `cksum': Print CRC checksum and byte counts===============================================`cksum' computes a cyclic redundancy check (CRC) checksum for eachgiven FILE, or standard input if none are given or for a FILE of `-'.Synopsis:cksum [OPTION]... [FILE]...`cksum' prints the CRC checksum for each file along with the numberof bytes in the file, and the file name unless no arguments were given.`cksum' is typically used to ensure that files transferred byunreliable means (e.g., netnews) have not been corrupted, by comparingthe `cksum' output for the received files with the `cksum' output forthe original files (typically given in the distribution).The CRC algorithm is specified by the POSIX standard. It is notcompatible with the BSD or System V `sum' algorithms (see the previoussection); it is more robust.The only options are `--help' and `--version'. *Note Commonoptions::.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: md5sum invocation, Next: sha1sum invocation, Prev: cksum invocation, Up: Summarizing files6.4 `md5sum': Print or check MD5 digests========================================`md5sum' computes a 128-bit checksum (or "fingerprint" or"message-digest") for each specified FILE.Note: The MD5 digest is more reliable than a simple CRC (provided bythe `cksum' command) for detecting accidental file corruption, as thechances of accidentally having two files with identical MD5 arevanishingly small. However, it should not be considered truly secureagainst malicious tampering: although finding a file with a given MD5fingerprint, or modifying a file so as to retain its MD5 are consideredinfeasible at the moment, it is known how to produce different fileswith identical MD5 (a "collision"), something which can be a securityissue in certain contexts. For more secure hashes, consider usingSHA-1 or SHA-2. *Note sha1sum invocation::, and *note sha2 utilities::.If a FILE is specified as `-' or if no files are given `md5sum'computes the checksum for the standard input. `md5sum' can alsodetermine whether a file and checksum are consistent. Synopsis:md5sum [OPTION]... [FILE]...For each FILE, `md5sum' outputs the MD5 checksum, a flag indicatinga binary or text input file, and the file name. If FILE contains abackslash or newline, the line is started with a backslash, and eachproblematic character in the file name is escaped with a backslash,making the output unambiguous even in the presence of arbitrary filenames. If FILE is omitted or specified as `-', standard input is read.The program accepts the following options. Also see *note Commonoptions::.`-b'`--binary'Treat each input file as binary, by reading it in binary mode andoutputting a `*' flag. This is the inverse of `--text'. Onsystems like GNU that do not distinguish between binary and textfiles, this option merely flags each input file as binary: the MD5checksum is unaffected. This option is the default on systemslike MS-DOS that distinguish between binary and text files, exceptfor reading standard input when standard input is a terminal.`-c'`--check'Read file names and checksum information (not data) from each FILE(or from stdin if no FILE was specified) and report whether thechecksums match the contents of the named files. The input tothis mode of `md5sum' is usually the output of a prior,checksum-generating run of `md5sum'. Each valid line of inputconsists of an MD5 checksum, a binary/text flag, and then a filename. Binary files are marked with `*', text with ` '. For eachsuch line, `md5sum' reads the named file and computes its MD5checksum. Then, if the computed message digest does not match theone on the line with the file name, the file is noted as havingfailed the test. Otherwise, the file passes the test. Bydefault, for each valid line, one line is written to standardoutput indicating whether the named file passed the test. Afterall checks have been performed, if there were any failures, awarning is issued to standard error. Use the `--status' option toinhibit that output. If any listed file cannot be opened or read,if any valid line has an MD5 checksum inconsistent with theassociated file, or if no valid line is found, `md5sum' exits withnonzero status. Otherwise, it exits successfully.`--quiet'This option is useful only when verifying checksums. Whenverifying checksums, don't generate an 'OK' message persuccessfully checked file. Files that fail the verification arereported in the default one-line-per-file format. If there is anychecksum mismatch, print a warning summarizing the failures tostandard error.`--status'This option is useful only when verifying checksums. Whenverifying checksums, don't generate the default one-line-per-filediagnostic and don't output the warning summarizing any failures.Failures to open or read a file still evoke individual diagnosticsto standard error. If all listed files are readable and areconsistent with the associated MD5 checksums, exit successfully.Otherwise exit with a status code indicating there was a failure.`-t'`--text'Treat each input file as text, by reading it in text mode andoutputting a ` ' flag. This is the inverse of `--binary'. Thisoption is the default on systems like GNU that do not distinguishbetween binary and text files. On other systems, it is thedefault for reading standard input when standard input is aterminal.`-w'`--warn'When verifying checksums, warn about improperly formatted MD5checksum lines. This option is useful only if all but a few linesin the checked input are valid.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: sha1sum invocation, Next: sha2 utilities, Prev: md5sum invocation, Up: Summarizing files6.5 `sha1sum': Print or check SHA-1 digests===========================================`sha1sum' computes a 160-bit checksum for each specified FILE. Theusage and options of this command are precisely the same as for`md5sum'. *Note md5sum invocation::.Note: The SHA-1 digest is more secure than MD5, and no collisions ofit are known (different files having the same fingerprint). However,it is known that they can be produced with considerable, but notunreasonable, resources. For this reason, it is generally consideredthat SHA-1 should be gradually phased out in favor of the more secureSHA-2 hash algorithms. *Note sha2 utilities::.File: coreutils.info, Node: sha2 utilities, Prev: sha1sum invocation, Up: Summarizing files6.6 sha2 utilities: Print or check SHA-2 digests================================================The commands `sha224sum', `sha256sum', `sha384sum' and `sha512sum'compute checksums of various lengths (respectively 224, 256, 384 and512 bits), collectively known as the SHA-2 hashes. The usage andoptions of these commands are precisely the same as for `md5sum'.*Note md5sum invocation::.Note: The SHA384 and SHA512 digests are considerably slower tocompute, especially on 32-bit computers, than SHA224 or SHA256.File: coreutils.info, Node: Operating on sorted files, Next: Operating on fields within a line, Prev: Summarizing files, Up: Top7 Operating on sorted files***************************These commands work with (or produce) sorted files.* Menu:* sort invocation:: Sort text files.* shuf invocation:: Shuffle text files.* uniq invocation:: Uniquify files.* comm invocation:: Compare two sorted files line by line.* ptx invocation:: Produce a permuted index of file contents.* tsort invocation:: Topological sort.File: coreutils.info, Node: sort invocation, Next: shuf invocation, Up: Operating on sorted files7.1 `sort': Sort text files===========================`sort' sorts, merges, or compares all the lines from the given files,or standard input if none are given or for a FILE of `-'. By default,`sort' writes the results to standard output. Synopsis:sort [OPTION]... [FILE]...`sort' has three modes of operation: sort (the default), merge, andcheck for sortedness. The following options change the operation mode:`-c'`--check'`--check=diagnose-first'Check whether the given file is already sorted: if it is not allsorted, print a diagnostic containing the first out-of-order lineand exit with a status of 1. Otherwise, exit successfully. Atmost one input file can be given.`-C'`--check=quiet'`--check=silent'Exit successfully if the given file is already sorted, and exitwith status 1 otherwise. At most one input file can be given.This is like `-c', except it does not print a diagnostic.`-m'`--merge'Merge the given files by sorting them as a group. Each input filemust always be individually sorted. It always works to sortinstead of merge; merging is provided because it is faster, in thecase where it works.A pair of lines is compared as follows: `sort' compares each pair offields, in the order specified on the command line, according to theassociated ordering options, until a difference is found or no fieldsare left. If no key fields are specified, `sort' uses a default key ofthe entire line. Finally, as a last resort when all keys compareequal, `sort' compares entire lines as if no ordering options otherthan `--reverse' (`-r') were specified. The `--stable' (`-s') optiondisables this "last-resort comparison" so that lines in which allfields compare equal are left in their original relative order. The`--unique' (`-u') option also disables the last-resort comparison.Unless otherwise specified, all comparisons use the charactercollating sequence specified by the `LC_COLLATE' locale.(1)GNU `sort' (as specified for all GNU utilities) has no limit oninput line length or restrictions on bytes allowed within lines. Inaddition, if the final byte of an input file is not a newline, GNU`sort' silently supplies one. A line's trailing newline is not part ofthe line for comparison purposes.Exit status:0 if no error occurred1 if invoked with `-c' or `-C' and the input is not sorted2 if an error occurredIf the environment variable `TMPDIR' is set, `sort' uses its valueas the directory for temporary files instead of `/tmp'. The`--temporary-directory' (`-T') option in turn overrides the environmentvariable.The following options affect the ordering of output lines. They maybe specified globally or as part of a specific key field. If no keyfields are specified, global options apply to comparison of entirelines; otherwise the global options are inherited by key fields that donot specify any special options of their own. In pre-POSIX versions of`sort', global options affect only later key fields, so portable shellscripts should specify global options first.`-b'`--ignore-leading-blanks'Ignore leading blanks when finding sort keys in each line. Bydefault a blank is a space or a tab, but the `LC_CTYPE' locale canchange this.`-d'`--dictionary-order'Sort in "phone directory" order: ignore all characters exceptletters, digits and blanks when sorting. By default letters anddigits are those of ASCII and a blank is a space or a tab, but the`LC_CTYPE' locale can change this.`-f'`--ignore-case'Fold lowercase characters into the equivalent uppercase characterswhen comparing so that, for example, `b' and `B' sort as equal.The `LC_CTYPE' locale determines character types. When used with`--unique' those lower case equivalent lines are thrown away.(There is currently no way to throw away the upper case equivalentinstead. (Any `--reverse' given would only affect the finalresult, after the throwing away.))`-g'`--general-numeric-sort'`--sort=general-numeric'Sort numerically, using the standard C function `strtod' to converta prefix of each line to a double-precision floating point number.This allows floating point numbers to be specified in scientificnotation, like `1.0e-34' and `10e100'. The `LC_NUMERIC' localedetermines the decimal-point character. Do not report overflow,underflow, or conversion errors. Use the following collatingsequence:* Lines that do not start with numbers (all considered to beequal).* NaNs ("Not a Number" values, in IEEE floating pointarithmetic) in a consistent but machine-dependent order.* Minus infinity.* Finite numbers in ascending numeric order (with -0 and +0equal).* Plus infinity.Use this option only if there is no alternative; it is much slowerthan `--numeric-sort' (`-n') and it can lose information whenconverting to floating point.`-i'`--ignore-nonprinting'Ignore nonprinting characters. The `LC_CTYPE' locale determinescharacter types. This option has no effect if the stronger`--dictionary-order' (`-d') option is also given.`-M'`--month-sort'`--sort=month'An initial string, consisting of any amount of blanks, followed bya month name abbreviation, is folded to UPPER case and compared inthe order `JAN' < `FEB' < ... < `DEC'. Invalid names compare lowto valid names. The `LC_TIME' locale category determines themonth spellings. By default a blank is a space or a tab, but the`LC_CTYPE' locale can change this.`-n'`--numeric-sort'`--sort=numeric'Sort numerically. The number begins each line and consists ofoptional blanks, an optional `-' sign, and zero or more digitspossibly separated by thousands separators, optionally followed bya decimal-point character and zero or more digits. An emptynumber is treated as `0'. The `LC_NUMERIC' locale specifies thedecimal-point character and thousands separator. By default ablank is a space or a tab, but the `LC_CTYPE' locale can changethis.Comparison is exact; there is no rounding error.Neither a leading `+' nor exponential notation is recognized. Tocompare such strings numerically, use the `--general-numeric-sort'(`-g') option.`-V'`--version-sort'Sort per `strverscmp(3)'. This is a normal string comparison,except that embedded decimal numbers are sorted by numeric value(see `--numeric-sort' above).`-r'`--reverse'Reverse the result of comparison, so that lines with greater keyvalues appear earlier in the output instead of later.`-R'`--random-sort'`--sort=random'Sort by hashing the input keys and then sorting the hash values.Choose the hash function at random, ensuring that it is free ofcollisions so that differing keys have differing hash values.This is like a random permutation of the inputs (*note shufinvocation::), except that keys with the same value sort together.If multiple random sort fields are specified, the same random hashfunction is used for all fields. To use different random hashfunctions for different fields, you can invoke `sort' more thanonce.The choice of hash function is affected by the `--random-source'option.Other options are:`--compress-program=PROG'Compress any temporary files with the program PROG.With no arguments, PROG must compress standard input to standardoutput, and when given the `-d' option it must decompress standardinput to standard output.Terminate with an error if PROG exits with nonzero status.White space and the backslash character should not appear in PROG;they are reserved for future use.`--files0-from=FILE'Disallow processing files named on the command line, and insteadprocess those named in file FILE; each name being terminated by azero byte (ASCII NUL). This is useful when the list of file namesis so long that it may exceed a command line length limitation.In such cases, running `sort' via `xargs' is undesirable becauseit splits the list into pieces and makes `sort' print sortedoutput for each sublist rather than for the entire list. One wayto produce a list of ASCII NUL terminated file names is with GNU`find', using its `-print0' predicate. If FILE is `-' then theASCII NUL terminated file names are read from standard input.`-k POS1[,POS2]'`--key=POS1[,POS2]'Specify a sort field that consists of the part of the line betweenPOS1 and POS2 (or the end of the line, if POS2 is omitted),_inclusive_.Each POS has the form `F[.C][OPTS]', where F is the number of thefield to use, and C is the number of the first character from thebeginning of the field. Fields and character positions arenumbered starting with 1; a character position of zero in POS2indicates the field's last character. If `.C' is omitted fromPOS1, it defaults to 1 (the beginning of the field); if omittedfrom POS2, it defaults to 0 (the end of the field). OPTS areordering options, allowing individual keys to be sorted accordingto different rules; see below for details. Keys can span multiplefields.Example: To sort on the second field, use `--key=2,2' (`-k 2,2').See below for more examples.`--batch-size=NMERGE'Merge at most NMERGE inputs at once.When `sort' has to merge more than NMERGE inputs, it merges themin groups of NMERGE, saving the result in a temporary file, whichis then used as an input in a subsequent merge.A large value of NMERGE may improve merge performance and decreasetemporary storage utilization at the expense of increased memoryusage and I/0. Conversely a small value of NMERGE may reducememory requirements and I/0 at the expense of temporary storageconsumption and merge performance.The value of NMERGE must be at least 2. The default value iscurrently 16, but this is implementation-dependent and may changein the future.The value of NMERGE may be bounded by a resource limit for openfile descriptors. The commands `ulimit -n' or `getconf OPEN_MAX'may display limits for your systems; these limits may be modifiedfurther if your program already has some files open, or if theoperating system has other limits on the number of open files. Ifthe value of NMERGE exceeds the resource limit, `sort' silentlyuses a smaller value.`-o OUTPUT-FILE'`--output=OUTPUT-FILE'Write output to OUTPUT-FILE instead of standard output. Normally,`sort' reads all input before opening OUTPUT-FILE, so you cansafely sort a file in place by using commands like `sort -o F F'and `cat F | sort -o F'. However, `sort' with `--merge' (`-m')can open the output file before reading all input, so a commandlike `cat F | sort -m -o F - G' is not safe as `sort' might startwriting `F' before `cat' is done reading it.On newer systems, `-o' cannot appear after an input file if`POSIXLY_CORRECT' is set, e.g., `sort F -o F'. Portable scriptsshould specify `-o OUTPUT-FILE' before any input files.`--random-source=FILE'Use FILE as a source of random data used to determine which randomhash function to use with the `-R' option. *Note Random sources::.`-s'`--stable'Make `sort' stable by disabling its last-resort comparison. Thisoption has no effect if no fields or global ordering options otherthan `--reverse' (`-r') are specified.`-S SIZE'`--buffer-size=SIZE'Use a main-memory sort buffer of the given SIZE. By default, SIZEis in units of 1024 bytes. Appending `%' causes SIZE to beinterpreted as a percentage of physical memory. Appending `K'multiplies SIZE by 1024 (the default), `M' by 1,048,576, `G' by1,073,741,824, and so on for `T', `P', `E', `Z', and `Y'.Appending `b' causes SIZE to be interpreted as a byte count, withno multiplication.This option can improve the performance of `sort' by causing it tostart with a larger or smaller sort buffer than the default.However, this option affects only the initial buffer size. Thebuffer grows beyond SIZE if `sort' encounters input lines largerthan SIZE.`-t SEPARATOR'`--field-separator=SEPARATOR'Use character SEPARATOR as the field separator when finding thesort keys in each line. By default, fields are separated by theempty string between a non-blank character and a blank character.By default a blank is a space or a tab, but the `LC_CTYPE' localecan change this.That is, given the input line ` foo bar', `sort' breaks it intofields ` foo' and ` bar'. The field separator is not consideredto be part of either the field preceding or the field following,so with `sort -t " "' the same input line has three fields: anempty field, `foo', and `bar'. However, fields that extend to theend of the line, as `-k 2', or fields consisting of a range, as`-k 2,3', retain the field separators present between theendpoints of the range.To specify ASCII NUL as the field separator, use the two-characterstring `\0', e.g., `sort -t '\0''.`-T TEMPDIR'`--temporary-directory=TEMPDIR'Use directory TEMPDIR to store temporary files, overriding the`TMPDIR' environment variable. If this option is given more thanonce, temporary files are stored in all the directories given. Ifyou have a large sort or merge that is I/O-bound, you can oftenimprove performance by using this option to specify directories ondifferent disks and controllers.`-u'`--unique'Normally, output only the first of a sequence of lines that compareequal. For the `--check' (`-c' or `-C') option, check that nopair of consecutive lines compares equal.This option also disables the default last-resort comparison.The commands `sort -u' and `sort | uniq' are equivalent, but thisequivalence does not extend to arbitrary `sort' options. Forexample, `sort -n -u' inspects only the value of the initialnumeric string when checking for uniqueness, whereas `sort -n |uniq' inspects the entire line. *Note uniq invocation::.`-z'`--zero-terminated'Delimit items with a zero byte rather than a newline (ASCII LF).I.E. treat input as items separated by ASCII NUL and terminateoutput items with ASCII NUL. This option can be useful inconjunction with `perl -0' or `find -print0' and `xargs -0' whichdo the same in order to reliably handle arbitrary file names (eventhose containing blanks or other special characters).Historical (BSD and System V) implementations of `sort' havediffered in their interpretation of some options, particularly `-b',`-f', and `-n'. GNU sort follows the POSIX behavior, which is usually(but not always!) like the System V behavior. According to POSIX, `-n'no longer implies `-b'. For consistency, `-M' has been changed in thesame way. This may affect the meaning of character positions in fieldspecifications in obscure cases. The only fix is to add an explicit`-b'.A position in a sort field specified with `-k' may have any of theoption letters `Mbdfinr' appended to it, in which case the globalordering options are not used for that particular field. The `-b'option may be independently attached to either or both of the start andend positions of a field specification, and if it is inherited from theglobal options it will be attached to both. If input lines can containleading or adjacent blanks and `-t' is not used, then `-k' is typicallycombined with `-b', `-g', `-M', or `-n'; otherwise the varying numbersof leading blanks in fields can cause confusing results.If the start position in a sort field specifier falls after the endof the line or after the end field, the field is empty. If the `-b'option was specified, the `.C' part of a field specification is countedfrom the first nonblank character of the field.On older systems, `sort' supports an obsolete origin-zero syntax`+POS1 [-POS2]' for specifying sort keys. This obsolete behavior canbe enabled or disabled with the `_POSIX2_VERSION' environment variable(*note Standards conformance::); it can also be enabled when`POSIXLY_CORRECT' is not set by using the obsolete syntax with `-POS2'present.Scripts intended for use on standard hosts should avoid obsoletesyntax and should use `-k' instead. For example, avoid `sort +2',since it might be interpreted as either `sort ./+2' or `sort -k 3'. Ifyour script must also run on hosts that support only the obsoletesyntax, it can use a test like `if sort -k 1 </dev/null >/dev/null2>&1; then ...' to decide which syntax to use.Here are some examples to illustrate various combinations of options.* Sort in descending (reverse) numeric order.sort -n -r* Sort alphabetically, omitting the first and second fields and theblanks at the start of the third field. This uses a single keycomposed of the characters beginning at the start of the firstnonblank character in field three and extending to the end of eachline.sort -k 3b* Sort numerically on the second field and resolve ties by sortingalphabetically on the third and fourth characters of field five.Use `:' as the field delimiter.sort -t : -k 2,2n -k 5.3,5.4Note that if you had written `-k 2n' instead of `-k 2,2n' `sort'would have used all characters beginning in the second field andextending to the end of the line as the primary _numeric_ key.For the large majority of applications, treating keys spanningmore than one field as numeric will not do what you expect.Also note that the `n' modifier was applied to the field-endspecifier for the first key. It would have been equivalent tospecify `-k 2n,2' or `-k 2n,2n'. All modifiers except `b' applyto the associated _field_, regardless of whether the modifiercharacter is attached to the field-start and/or the field-end partof the key specifier.* Sort the password file on the fifth field and ignore any leadingblanks. Sort lines with equal values in field five on the numericuser ID in field three. Fields are separated by `:'.sort -t : -k 5b,5 -k 3,3n /etc/passwdsort -t : -n -k 5b,5 -k 3,3 /etc/passwdsort -t : -b -k 5,5 -k 3,3n /etc/passwdThese three commands have equivalent effect. The first specifiesthat the first key's start position ignores leading blanks and thesecond key is sorted numerically. The other two commands rely onglobal options being inherited by sort keys that lack modifiers.The inheritance works in this case because `-k 5b,5b' and `-k5b,5' are equivalent, as the location of a field-end lacking a `.C'character position is not affected by whether initial blanks areskipped.* Sort a set of log files, primarily by IPv4 address and secondarilyby time stamp. If two lines' primary and secondary keys areidentical, output the lines in the same order that they wereinput. The log files contain lines that look like this:4.150.156.3 - - [01/Apr/2004:06:31:51 +0000] message 1211.24.3.231 - - [24/Apr/2004:20:17:39 +0000] message 2Fields are separated by exactly one space. Sort IPv4 addresseslexicographically, e.g., 212.61.52.2 sorts before 212.129.233.201because 61 is less than 129.sort -s -t ' ' -k 4.9n -k 4.5M -k 4.2n -k 4.14,4.21 file*.log |sort -s -t '.' -k 1,1n -k 2,2n -k 3,3n -k 4,4nThis example cannot be done with a single `sort' invocation, sinceIPv4 address components are separated by `.' while dates come justafter a space. So it is broken down into two invocations of`sort': the first sorts by time stamp and the second by IPv4address. The time stamp is sorted by year, then month, then day,and finally by hour-minute-second field, using `-k' to isolate eachfield. Except for hour-minute-second there's no need to specifythe end of each key field, since the `n' and `M' modifiers sortbased on leading prefixes that cannot cross field boundaries. TheIPv4 addresses are sorted lexicographically. The second sort uses`-s' so that ties in the primary key are broken by the secondarykey; the first sort uses `-s' so that the combination of the twosorts is stable.* Generate a tags file in case-insensitive sorted order.find src -type f -print0 | sort -z -f | xargs -0 etags --appendThe use of `-print0', `-z', and `-0' in this case means that filenames that contain blanks or other special characters are notbroken up by the sort operation.* Shuffle a list of directories, but preserve the order of fileswithin each directory. For instance, one could use this togenerate a music playlist in which albums are shuffled but thesongs of each album are played in order.ls */* | sort -t / -k 1,1R -k 2,2---------- Footnotes ----------(1) If you use a non-POSIX locale (e.g., by setting `LC_ALL' to`en_US'), then `sort' may produce output that is sorted differentlythan you're accustomed to. In that case, set the `LC_ALL' environmentvariable to `C'. Note that setting only `LC_COLLATE' has two problems.First, it is ineffective if `LC_ALL' is also set. Second, it hasundefined behavior if `LC_CTYPE' (or `LANG', if `LC_CTYPE' is unset) isset to an incompatible value. For example, you get undefined behaviorif `LC_CTYPE' is `ja_JP.PCK' but `LC_COLLATE' is `en_US.UTF-8'.File: coreutils.info, Node: shuf invocation, Next: uniq invocation, Prev: sort invocation, Up: Operating on sorted files7.2 `shuf': Shuffling text==========================`shuf' shuffles its input by outputting a random permutation of itsinput lines. Each output permutation is equally likely. Synopses:shuf [OPTION]... [FILE]shuf -e [OPTION]... [ARG]...shuf -i LO-HI [OPTION]...`shuf' has three modes of operation that affect where it obtains itsinput lines. By default, it reads lines from standard input. Thefollowing options change the operation mode:`-e'`--echo'Treat each command-line operand as an input line.`-i LO-HI'`--input-range=LO-HI'Act as if input came from a file containing the range of unsigneddecimal integers LO...HI, one per line.`shuf''s other options can affect its behavior in all operationmodes:`-n LINES'`--head-count=COUNT'Output at most COUNT lines. By default, all input lines areoutput.`-o OUTPUT-FILE'`--output=OUTPUT-FILE'Write output to OUTPUT-FILE instead of standard output. `shuf'reads all input before opening OUTPUT-FILE, so you can safelyshuffle a file in place by using commands like `shuf -o F <F' and`cat F | shuf -o F'.`--random-source=FILE'Use FILE as a source of random data used to determine whichpermutation to generate. *Note Random sources::.`-z'`--zero-terminated'Delimit items with a zero byte rather than a newline (ASCII LF).I.E. treat input as items separated by ASCII NUL and terminateoutput items with ASCII NUL. This option can be useful inconjunction with `perl -0' or `find -print0' and `xargs -0' whichdo the same in order to reliably handle arbitrary file names (eventhose containing blanks or other special characters).For example:shuf <<EOFA man,a plan,a canal:Panama!EOFmight produce the outputPanama!A man,a canal:a plan,Similarly, the command:shuf -e clubs hearts diamonds spadesmight output:clubsdiamondsspadesheartsand the command `shuf -i 1-4' might output:4213These examples all have four input lines, so `shuf' might produce anyof the twenty-four possible permutations of the input. In general, ifthere are N input lines, there are N! (i.e., N factorial, or N * (N -1) * ... * 1) possible output permutations.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: uniq invocation, Next: comm invocation, Prev: shuf invocation, Up: Operating on sorted files7.3 `uniq': Uniquify files==========================`uniq' writes the unique lines in the given `input', or standard inputif nothing is given or for an INPUT name of `-'. Synopsis:uniq [OPTION]... [INPUT [OUTPUT]]By default, `uniq' prints its input lines, except that it discardsall but the first of adjacent repeated lines, so that no output linesare repeated. Optionally, it can instead discard lines that are notrepeated, or all repeated lines.The input need not be sorted, but repeated input lines are detectedonly if they are adjacent. If you want to discard non-adjacentduplicate lines, perhaps you want to use `sort -u'. *Note sortinvocation::.Comparisons honor the rules specified by the `LC_COLLATE' localecategory.If no OUTPUT file is specified, `uniq' writes to standard output.The program accepts the following options. Also see *note Commonoptions::.`-f N'`--skip-fields=N'Skip N fields on each line before checking for uniqueness. Use anull string for comparison if a line has fewer than N fields.Fields are sequences of non-space non-tab characters that areseparated from each other by at least one space or tab.For compatibility `uniq' supports an obsolete option syntax `-N'.New scripts should use `-f N' instead.`-s N'`--skip-chars=N'Skip N characters before checking for uniqueness. Use a nullstring for comparison if a line has fewer than N characters. Ifyou use both the field and character skipping options, fields areskipped over first.On older systems, `uniq' supports an obsolete option syntax `+N'.This obsolete behavior can be enabled or disabled with the`_POSIX2_VERSION' environment variable (*note Standardsconformance::), but portable scripts should avoid commands whosebehavior depends on this variable. For example, use `uniq ./+10'or `uniq -s 10' rather than the ambiguous `uniq +10'.`-c'`--count'Print the number of times each line occurred along with the line.`-i'`--ignore-case'Ignore differences in case when comparing lines.`-d'`--repeated'Discard lines that are not repeated. When used by itself, thisoption causes `uniq' to print the first copy of each repeated line,and nothing else.`-D'`--all-repeated[=DELIMIT-METHOD]'Do not discard the second and subsequent repeated input lines, butdiscard lines that are not repeated. This option is useful mainlyin conjunction with other options e.g., to ignore case or tocompare only selected fields. The optional DELIMIT-METHOD tellshow to delimit groups of repeated lines, and must be one of thefollowing:`none'Do not delimit groups of repeated lines. This is equivalentto `--all-repeated' (`-D').`prepend'Output a newline before each group of repeated lines. With`--zero-terminated' (`-z'), use a zero byte (ASCII NUL)instead of a newline.`separate'Separate groups of repeated lines with a single newline.With `--zero-terminated' (`-z'), use a zero byte (ASCII NUL)instead of a newline. This is the same as using `prepend',except that no delimiter is inserted before the first group,and hence may be better suited for output direct to users.Note that when groups are delimited and the input stream containstwo or more consecutive blank lines, then the output is ambiguous.To avoid that, filter the input through `tr -s '\n'' to replaceeach sequence of consecutive newlines with a single newline.This is a GNU extension.`-u'`--unique'Discard the first repeated line. When used by itself, this optioncauses `uniq' to print unique lines, and nothing else.`-w N'`--check-chars=N'Compare at most N characters on each line (after skipping anyspecified fields and characters). By default the entire rest ofthe lines are compared.`-z'`--zero-terminated'Delimit items with a zero byte rather than a newline (ASCII LF).I.E. treat input as items separated by ASCII NUL and terminateoutput items with ASCII NUL. This option can be useful inconjunction with `perl -0' or `find -print0' and `xargs -0' whichdo the same in order to reliably handle arbitrary file names (eventhose containing blanks or other special characters).An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: comm invocation, Next: ptx invocation, Prev: uniq invocation, Up: Operating on sorted files7.4 `comm': Compare two sorted files line by line=================================================`comm' writes to standard output lines that are common, and lines thatare unique, to two input files; a file name of `-' means standardinput. Synopsis:comm [OPTION]... FILE1 FILE2Before `comm' can be used, the input files must be sorted using thecollating sequence specified by the `LC_COLLATE' locale. If an inputfile ends in a non-newline character, a newline is silently appended.The `sort' command with no options always outputs a file that issuitable input to `comm'.With no options, `comm' produces three-column output. Column onecontains lines unique to FILE1, column two contains lines unique toFILE2, and column three contains lines common to both files. Columnsare separated by a single TAB character.The options `-1', `-2', and `-3' suppress printing of thecorresponding columns. Also see *note Common options::.Unlike some other comparison utilities, `comm' has an exit statusthat does not depend on the result of the comparison. Upon normalcompletion `comm' produces an exit code of zero. If there is an errorit exits with nonzero status.If the `--check-order' option is given, unsorted inputs will cause afatal error message. If the option `--nocheck-order' is given,unsorted inputs will never cause an error message. If neither of theseoptions is given, wrongly sorted inputs are diagnosed only if an inputfile is found to contain unpairable lines. If an input file isdiagnosed as being unsorted, the `comm' command will exit with anonzero status (and the output should not be used).Forcing `comm' to process wrongly sorted input files containingunpairable lines by specifying `--nocheck-order' is not guaranteed toproduce any particular output. The output will probably not correspondwith whatever you hoped it would be.`--check-order'Fail with an error message if either input file is wrongly ordered.`--nocheck-order'Do not check that both input files are in sorted order.Other options are:`--output-delimiter=STR'Print STR between adjacent output columns, rather than the defaultof a single TAB character.The delimiter STR may not be empty.File: coreutils.info, Node: ptx invocation, Next: tsort invocation, Prev: comm invocation, Up: Operating on sorted files7.5 `ptx': Produce permuted indexes===================================`ptx' reads a text file and essentially produces a permuted index, witheach keyword in its context. The calling sketch is either one of:ptx [OPTION ...] [FILE ...]ptx -G [OPTION ...] [INPUT [OUTPUT]]The `-G' (or its equivalent: `--traditional') option disables allGNU extensions and reverts to traditional mode, thus introducing somelimitations and changing several of the program's default option values.When `-G' is not specified, GNU extensions are always enabled. GNUextensions to `ptx' are documented wherever appropriate in thisdocument. For the full list, see *Note Compatibility in ptx::.Individual options are explained in the following sections.When GNU extensions are enabled, there may be zero, one or severalFILEs after the options. If there is no FILE, the program reads thestandard input. If there is one or several FILEs, they give the nameof input files which are all read in turn, as if all the input fileswere concatenated. However, there is a full contextual break betweeneach file and, when automatic referencing is requested, file names andline numbers refer to individual text input files. In all cases, theprogram outputs the permuted index to the standard output.When GNU extensions are _not_ enabled, that is, when the programoperates in traditional mode, there may be zero, one or two parametersbesides the options. If there are no parameters, the program reads thestandard input and outputs the permuted index to the standard output.If there is only one parameter, it names the text INPUT to be readinstead of the standard input. If two parameters are given, they giverespectively the name of the INPUT file to read and the name of theOUTPUT file to produce. _Be very careful_ to note that, in this case,the contents of file given by the second parameter is destroyed. Thisbehavior is dictated by System V `ptx' compatibility; GNU Standardsnormally discourage output parameters not introduced by an option.Note that for _any_ file named as the value of an option or as aninput text file, a single dash `-' may be used, in which case standardinput is assumed. However, it would not make sense to use thisconvention more than once per program invocation.* Menu:* General options in ptx:: Options which affect general program behavior.* Charset selection in ptx:: Underlying character set considerations.* Input processing in ptx:: Input fields, contexts, and keyword selection.* Output formatting in ptx:: Types of output format, and sizing the fields.* Compatibility in ptx::File: coreutils.info, Node: General options in ptx, Next: Charset selection in ptx, Up: ptx invocation7.5.1 General options---------------------`-G'`--traditional'As already explained, this option disables all GNU extensions to`ptx' and switches to traditional mode.`--help'Print a short help on standard output, then exit without furtherprocessing.`--version'Print the program version on standard output, then exit withoutfurther processing.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Charset selection in ptx, Next: Input processing in ptx, Prev: General options in ptx, Up: ptx invocation7.5.2 Charset selection-----------------------As it is set up now, the program assumes that the input file is codedusing 8-bit ISO 8859-1 code, also known as Latin-1 character set,_unless_ it is compiled for MS-DOS, in which case it uses the characterset of the IBM-PC. (GNU `ptx' is not known to work on smaller MS-DOSmachines anymore.) Compared to 7-bit ASCII, the set of characterswhich are letters is different; this alters the behavior of regularexpression matching. Thus, the default regular expression for akeyword allows foreign or diacriticized letters. Keyword sorting,however, is still crude; it obeys the underlying character set orderingquite blindly.`-f'`--ignore-case'Fold lower case letters to upper case for sorting.File: coreutils.info, Node: Input processing in ptx, Next: Output formatting in ptx, Prev: Charset selection in ptx, Up: ptx invocation7.5.3 Word selection and input processing-----------------------------------------`-b FILE'`--break-file=FILE'This option provides an alternative (to `-W') method of describingwhich characters make up words. It introduces the name of a filewhich contains a list of characters which can_not_ be part of oneword; this file is called the "Break file". Any character whichis not part of the Break file is a word constituent. If bothoptions `-b' and `-W' are specified, then `-W' has precedence and`-b' is ignored.When GNU extensions are enabled, the only way to avoid newline as abreak character is to write all the break characters in the filewith no newline at all, not even at the end of the file. When GNUextensions are disabled, spaces, tabs and newlines are alwaysconsidered as break characters even if not included in the Breakfile.`-i FILE'`--ignore-file=FILE'The file associated with this option contains a list of wordswhich will never be taken as keywords in concordance output. Itis called the "Ignore file". The file contains exactly one wordin each line; the end of line separation of words is not subjectto the value of the `-S' option.`-o FILE'`--only-file=FILE'The file associated with this option contains a list of wordswhich will be retained in concordance output; any word notmentioned in this file is ignored. The file is called the "Onlyfile". The file contains exactly one word in each line; the endof line separation of words is not subject to the value of the`-S' option.There is no default for the Only file. When both an Only file andan Ignore file are specified, a word is considered a keyword onlyif it is listed in the Only file and not in the Ignore file.`-r'`--references'On each input line, the leading sequence of non-white spacecharacters will be taken to be a reference that has the purpose ofidentifying this input line in the resulting permuted index. Formore information about reference production, see *Note Outputformatting in ptx::. Using this option changes the default valuefor option `-S'.Using this option, the program does not try very hard to removereferences from contexts in output, but it succeeds in doing so_when_ the context ends exactly at the newline. If option `-r' isused with `-S' default value, or when GNU extensions are disabled,this condition is always met and references are completelyexcluded from the output contexts.`-S REGEXP'`--sentence-regexp=REGEXP'This option selects which regular expression will describe the endof a line or the end of a sentence. In fact, this regularexpression is not the only distinction between end of lines or endof sentences, and input line boundaries have no specialsignificance outside this option. By default, when GNU extensionsare enabled and if `-r' option is not used, end of sentences areused. In this case, this REGEX is imported from GNU Emacs:[.?!][]\"')}]*\\($\\|\t\\| \\)[ \t\n]*Whenever GNU extensions are disabled or if `-r' option is used, endof lines are used; in this case, the default REGEXP is just:\nUsing an empty REGEXP is equivalent to completely disabling end ofline or end of sentence recognition. In this case, the whole fileis considered to be a single big line or sentence. The user mightwant to disallow all truncation flag generation as well, throughoption `-F ""'. *Note Syntax of Regular Expressions:(emacs)Regexps.When the keywords happen to be near the beginning of the inputline or sentence, this often creates an unused area at thebeginning of the output context line; when the keywords happen tobe near the end of the input line or sentence, this often createsan unused area at the end of the output context line. The programtries to fill those unused areas by wrapping around context inthem; the tail of the input line or sentence is used to fill theunused area on the left of the output line; the head of the inputline or sentence is used to fill the unused area on the right ofthe output line.As a matter of convenience to the user, many usual backslashedescape sequences from the C language are recognized and convertedto the corresponding characters by `ptx' itself.`-W REGEXP'`--word-regexp=REGEXP'This option selects which regular expression will describe eachkeyword. By default, if GNU extensions are enabled, a word is asequence of letters; the REGEXP used is `\w+'. When GNUextensions are disabled, a word is by default anything which endswith a space, a tab or a newline; the REGEXP used is `[^ \t\n]+'.An empty REGEXP is equivalent to not using this option. *NoteSyntax of Regular Expressions: (emacs)Regexps.As a matter of convenience to the user, many usual backslashedescape sequences, as found in the C language, are recognized andconverted to the corresponding characters by `ptx' itself.File: coreutils.info, Node: Output formatting in ptx, Next: Compatibility in ptx, Prev: Input processing in ptx, Up: ptx invocation7.5.4 Output formatting-----------------------Output format is mainly controlled by the `-O' and `-T' optionsdescribed in the table below. When neither `-O' nor `-T' are selected,and if GNU extensions are enabled, the program chooses an output formatsuitable for a dumb terminal. Each keyword occurrence is output to thecenter of one line, surrounded by its left and right contexts. Eachfield is properly justified, so the concordance output can be readilyobserved. As a special feature, if automatic references are selectedby option `-A' and are output before the left context, that is, ifoption `-R' is _not_ selected, then a colon is added after thereference; this nicely interfaces with GNU Emacs `next-error'processing. In this default output format, each white space character,like newline and tab, is merely changed to exactly one space, with nospecial attempt to compress consecutive spaces. This might change inthe future. Except for those white space characters, every othercharacter of the underlying set of 256 characters is transmittedverbatim.Output format is further controlled by the following options.`-g NUMBER'`--gap-size=NUMBER'Select the size of the minimum white space gap between the fieldson the output line.`-w NUMBER'`--width=NUMBER'Select the maximum output width of each final line. If referencesare used, they are included or excluded from the maximum outputwidth depending on the value of option `-R'. If this option is notselected, that is, when references are output before the leftcontext, the maximum output width takes into account the maximumlength of all references. If this option is selected, that is,when references are output after the right context, the maximumoutput width does not take into account the space taken byreferences, nor the gap that precedes them.`-A'`--auto-reference'Select automatic references. Each input line will have anautomatic reference made up of the file name and the line ordinal,with a single colon between them. However, the file name will beempty when standard input is being read. If both `-A' and `-r'are selected, then the input reference is still read and skipped,but the automatic reference is used at output time, overriding theinput reference.`-R'`--right-side-refs'In the default output format, when option `-R' is not used, anyreferences produced by the effect of options `-r' or `-A' areplaced to the far right of output lines, after the right context.With default output format, when the `-R' option is specified,references are rather placed at the beginning of each output line,before the left context. For any other output format, option `-R'is ignored, with one exception: with `-R' the width of referencesis _not_ taken into account in total output width given by `-w'.This option is automatically selected whenever GNU extensions aredisabled.`-F STRING'`--flac-truncation=STRING'This option will request that any truncation in the output bereported using the string STRING. Most output fieldstheoretically extend towards the beginning or the end of thecurrent line, or current sentence, as selected with option `-S'.But there is a maximum allowed output line width, changeablethrough option `-w', which is further divided into space forvarious output fields. When a field has to be truncated becauseit cannot extend beyond the beginning or the end of the currentline to fit in, then a truncation occurs. By default, the stringused is a single slash, as in `-F /'.STRING may have more than one character, as in `-F ...'. Also, inthe particular case when STRING is empty (`-F ""'), truncationflagging is disabled, and no truncation marks are appended in thiscase.As a matter of convenience to the user, many usual backslashedescape sequences, as found in the C language, are recognized andconverted to the corresponding characters by `ptx' itself.`-M STRING'`--macro-name=STRING'Select another STRING to be used instead of `xx', while generatingoutput suitable for `nroff', `troff' or TeX.`-O'`--format=roff'Choose an output format suitable for `nroff' or `troff'processing. Each output line will look like:.xx "TAIL" "BEFORE" "KEYWORD_AND_AFTER" "HEAD" "REF"so it will be possible to write a `.xx' roff macro to take care ofthe output typesetting. This is the default output format when GNUextensions are disabled. Option `-M' can be used to change `xx'to another macro name.In this output format, each non-graphical character, like newlineand tab, is merely changed to exactly one space, with no specialattempt to compress consecutive spaces. Each quote character: `"'is doubled so it will be correctly processed by `nroff' or `troff'.`-T'`--format=tex'Choose an output format suitable for TeX processing. Each outputline will look like:\xx {TAIL}{BEFORE}{KEYWORD}{AFTER}{HEAD}{REF}so it will be possible to write a `\xx' definition to take care ofthe output typesetting. Note that when references are not beingproduced, that is, neither option `-A' nor option `-r' isselected, the last parameter of each `\xx' call is inhibited.Option `-M' can be used to change `xx' to another macro name.In this output format, some special characters, like `$', `%',`&', `#' and `_' are automatically protected with a backslash.Curly brackets `{', `}' are protected with a backslash and a pairof dollar signs (to force mathematical mode). The backslashitself produces the sequence `\backslash{}'. Circumflex and tildediacritical marks produce the sequence `^\{ }' and `~\{ }'respectively. Other diacriticized characters of the underlyingcharacter set produce an appropriate TeX sequence as far aspossible. The other non-graphical characters, like newline andtab, and all other characters which are not part of ASCII, aremerely changed to exactly one space, with no special attempt tocompress consecutive spaces. Let me know how to improve thisspecial character processing for TeX.File: coreutils.info, Node: Compatibility in ptx, Prev: Output formatting in ptx, Up: ptx invocation7.5.5 The GNU extensions to `ptx'---------------------------------This version of `ptx' contains a few features which do not exist inSystem V `ptx'. These extra features are suppressed by using the `-G'command line option, unless overridden by other command line options.Some GNU extensions cannot be recovered by overriding, so the simplerule is to avoid `-G' if you care about GNU extensions. Here are thedifferences between this program and System V `ptx'.* This program can read many input files at once, it always writesthe resulting concordance on standard output. On the other hand,System V `ptx' reads only one file and sends the result tostandard output or, if a second FILE parameter is given on thecommand, to that FILE.Having output parameters not introduced by options is a dangerouspractice which GNU avoids as far as possible. So, for using `ptx'portably between GNU and System V, you should always use it with asingle input file, and always expect the result on standardoutput. You might also want to automatically configure in a `-G'option to `ptx' calls in products using `ptx', if the configuratorfinds that the installed `ptx' accepts `-G'.* The only options available in System V `ptx' are options `-b',`-f', `-g', `-i', `-o', `-r', `-t' and `-w'. All other optionsare GNU extensions and are not repeated in this enumeration.Moreover, some options have a slightly different meaning when GNUextensions are enabled, as explained below.* By default, concordance output is not formatted for `troff' or`nroff'. It is rather formatted for a dumb terminal. `troff' or`nroff' output may still be selected through option `-O'.* Unless `-R' option is used, the maximum reference width issubtracted from the total output line width. With GNU extensionsdisabled, width of references is not taken into account in theoutput line width computations.* All 256 bytes, even ASCII NUL bytes, are always read and processedfrom input file with no adverse effect, even if GNU extensions aredisabled. However, System V `ptx' does not accept 8-bit characters,a few control characters are rejected, and the tilde `~' is alsorejected.* Input line length is only limited by available memory, even if GNUextensions are disabled. However, System V `ptx' processes onlythe first 200 characters in each line.* The break (non-word) characters default to be every characterexcept all letters of the underlying character set, diacriticizedor not. When GNU extensions are disabled, the break charactersdefault to space, tab and newline only.* The program makes better use of output line width. If GNUextensions are disabled, the program rather tries to imitateSystem V `ptx', but still, there are some slight dispositionglitches this program does not completely reproduce.* The user can specify both an Ignore file and an Only file. Thisis not allowed with System V `ptx'.File: coreutils.info, Node: tsort invocation, Prev: ptx invocation, Up: Operating on sorted files7.6 `tsort': Topological sort=============================`tsort' performs a topological sort on the given FILE, or standardinput if no input file is given or for a FILE of `-'. For more detailsand some history, see *note tsort background::. Synopsis:tsort [OPTION] [FILE]`tsort' reads its input as pairs of strings, separated by blanks,indicating a partial ordering. The output is a total ordering thatcorresponds to the given partial ordering.For exampletsort <<EOFa b cde fb c d eEOFwill produce the outputabcdefConsider a more realistic example. You have a large set offunctions all in one file, and they may all be declared static exceptone. Currently that one (say `main') is the first function defined inthe file, and the ones it calls directly follow it, followed by thosethey call, etc. Let's say that you are determined to take advantage ofprototypes, so you have to choose between declaring all of thosefunctions (which means duplicating a lot of information from thedefinitions) and rearranging the functions so that as many as possibleare defined before they are used. One way to automate the latterprocess is to get a list for each function of the functions it callsdirectly. Many programs can generate such lists. They describe a callgraph. Consider the following list, in which a given line indicatesthat the function on the left calls the one on the right directly.main parse_optionsmain tail_filemain tail_forevertail_file pretty_nametail_file write_headertail_file tailtail_forever rechecktail_forever pretty_nametail_forever write_headertail_forever dump_remaindertail tail_linestail tail_bytestail_lines start_linestail_lines dump_remaindertail_lines file_linestail_lines pipe_linestail_bytes xlseektail_bytes start_bytestail_bytes dump_remaindertail_bytes pipe_bytesfile_lines dump_remainderrecheck pretty_namethen you can use `tsort' to produce an ordering of those functionsthat satisfies your requirement.example$ tsort call-graph | tacdump_remainderstart_linesfile_linespipe_linesxlseekstart_bytespipe_bytestail_linestail_bytespretty_namewrite_headertailrecheckparse_optionstail_filetail_forevermain`tsort' detects any cycles in the input and writes the first cycleencountered to standard error.Note that for a given partial ordering, generally there is no uniquetotal ordering. In the context of the call graph above, the function`parse_options' may be placed anywhere in the list as long as itprecedes `main'.The only options are `--help' and `--version'. *Note Commonoptions::.An exit status of zero indicates success, and a nonzero valueindicates failure.* Menu:* tsort background:: Where tsort came from.File: coreutils.info, Node: tsort background, Up: tsort invocation7.6.1 `tsort': Background-------------------------`tsort' exists because very early versions of the Unix linker processedan archive file exactly once, and in order. As `ld' read each objectin the archive, it decided whether it was needed in the program based onwhether it defined any symbols which were undefined at that point inthe link.This meant that dependencies within the archive had to be handledspecially. For example, `scanf' probably calls `read'. That meansthat in a single pass through an archive, it was important for `scanf.o'to appear before read.o, because otherwise a program which calls`scanf' but not `read' might end up with an unexpected unresolvedreference to `read'.The way to address this problem was to first generate a set ofdependencies of one object file on another. This was done by a shellscript called `lorder'. The GNU tools don't provide a version oflorder, as far as I know, but you can still find it in BSDdistributions.Then you ran `tsort' over the `lorder' output, and you used theresulting sort to define the order in which you added objects to thearchive.This whole procedure has been obsolete since about 1980, becauseUnix archives now contain a symbol table (traditionally built by`ranlib', now generally built by `ar' itself), and the Unix linker usesthe symbol table to effectively make multiple passes over an archivefile.Anyhow, that's where tsort came from. To solve an old problem withthe way the linker handled archive files, which has since been solvedin different ways.File: coreutils.info, Node: Operating on fields within a line, Next: Operating on characters, Prev: Operating on sorted files, Up: Top8 Operating on fields within a line************************************ Menu:* cut invocation:: Print selected parts of lines.* paste invocation:: Merge lines of files.* join invocation:: Join lines on a common field.File: coreutils.info, Node: cut invocation, Next: paste invocation, Up: Operating on fields within a line8.1 `cut': Print selected parts of lines========================================`cut' writes to standard output selected parts of each line of eachinput file, or standard input if no files are given or for a file nameof `-'. Synopsis:cut OPTION... [FILE]...In the table which follows, the BYTE-LIST, CHARACTER-LIST, andFIELD-LIST are one or more numbers or ranges (two numbers separated bya dash) separated by commas. Bytes, characters, and fields arenumbered starting at 1. Incomplete ranges may be given: `-M' means`1-M'; `N-' means `N' through end of line or last field. The listelements can be repeated, can overlap, and can be specified in anyorder; but the selected input is written in the same order that it isread, and is written exactly once.The program accepts the following options. Also see *note Commonoptions::.`-b BYTE-LIST'`--bytes=BYTE-LIST'Select for printing only the bytes in positions listed inBYTE-LIST. Tabs and backspaces are treated like any othercharacter; they take up 1 byte. If an output delimiter isspecified, (see the description of `--output-delimiter'), thenoutput that string between ranges of selected bytes.`-c CHARACTER-LIST'`--characters=CHARACTER-LIST'Select for printing only the characters in positions listed inCHARACTER-LIST. The same as `-b' for now, butinternationalization will change that. Tabs and backspaces aretreated like any other character; they take up 1 character. If anoutput delimiter is specified, (see the description of`--output-delimiter'), then output that string between ranges ofselected bytes.`-f FIELD-LIST'`--fields=FIELD-LIST'Select for printing only the fields listed in FIELD-LIST. Fieldsare separated by a TAB character by default. Also print any linethat contains no delimiter character, unless the`--only-delimited' (`-s') option is specified`-d INPUT_DELIM_BYTE'`--delimiter=INPUT_DELIM_BYTE'With `-f', use the first byte of INPUT_DELIM_BYTE as the inputfields separator (default is TAB).`-n'Do not split multi-byte characters (no-op for now).`-s'`--only-delimited'For `-f', do not print lines that do not contain the fieldseparator character. Normally, any line without a field separatoris printed verbatim.`--output-delimiter=OUTPUT_DELIM_STRING'With `-f', output fields are separated by OUTPUT_DELIM_STRING.The default with `-f' is to use the input delimiter. When using`-b' or `-c' to select ranges of byte or character offsets (asopposed to ranges of fields), output OUTPUT_DELIM_STRING betweennon-overlapping ranges of selected bytes.`--complement'This option is a GNU extension. Select for printing thecomplement of the bytes, characters or fields selected with the`-b', `-c' or `-f' options. In other words, do _not_ print thebytes, characters or fields specified via those options. Thisoption is useful when you have many fields and want to print allbut a few of them.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: paste invocation, Next: join invocation, Prev: cut invocation, Up: Operating on fields within a line8.2 `paste': Merge lines of files=================================`paste' writes to standard output lines consisting of sequentiallycorresponding lines of each given file, separated by a TAB character.Standard input is used for a file name of `-' or if no input files aregiven.For example:$ cat num212$ cat let3abc$ paste num2 let31 a2 bcSynopsis:paste [OPTION]... [FILE]...The program accepts the following options. Also see *note Commonoptions::.`-s'`--serial'Paste the lines of one file at a time rather than one line fromeach file. Using the above example data:$ paste -s num2 let31 2a b c`-d DELIM-LIST'`--delimiters=DELIM-LIST'Consecutively use the characters in DELIM-LIST instead of TAB toseparate merged lines. When DELIM-LIST is exhausted, start againat its beginning. Using the above example data:$ paste -d '%_' num2 let3 num21%a_12%b_2%c_An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: join invocation, Prev: paste invocation, Up: Operating on fields within a line8.3 `join': Join lines on a common field========================================`join' writes to standard output a line for each pair of input linesthat have identical join fields. Synopsis:join [OPTION]... FILE1 FILE2Either FILE1 or FILE2 (but not both) can be `-', meaning standardinput. FILE1 and FILE2 should be sorted on the join fields.Normally, the sort order is that of the collating sequence specifiedby the `LC_COLLATE' locale. Unless the `-t' option is given, the sortcomparison ignores blanks at the start of the join field, as in `sort-b'. If the `--ignore-case' option is given, the sort comparisonignores the case of characters in the join field, as in `sort -f'.The `sort' and `join' commands should use consistent locales andoptions if the output of `sort' is fed to `join'. You can use acommand like `sort -k 1b,1' to sort a file on its default join field,but if you select a non-default locale, join field, separator, orcomparison options, then you should do so consistently between `join'and `sort'.If the input has no unpairable lines, a GNU extension is available;the sort order can be any order that considers two fields to be equalif and only if the sort comparison described above considers them to beequal. For example:$ cat file1a a1c c1b b1$ cat file2a a2c c2b b2$ join file1 file2a a1 a2c c1 c2b b1 b2If the `--check-order' option is given, unsorted inputs will cause afatal error message. If the option `--nocheck-order' is given,unsorted inputs will never cause an error message. If neither of theseoptions is given, wrongly sorted inputs are diagnosed only if an inputfile is found to contain unpairable lines. If an input file isdiagnosed as being unsorted, the `join' command will exit with anonzero status (and the output should not be used).Forcing `join' to process wrongly sorted input files containingunpairable lines by specifying `--nocheck-order' is not guaranteed toproduce any particular output. The output will probably not correspondwith whatever you hoped it would be.The defaults are:* the join field is the first field in each line;* fields in the input are separated by one or more blanks, withleading blanks on the line ignored;* fields in the output are separated by a space;* each output line consists of the join field, the remaining fieldsfrom FILE1, then the remaining fields from FILE2.The program accepts the following options. Also see *note Commonoptions::.`-a FILE-NUMBER'Print a line for each unpairable line in file FILE-NUMBER (either`1' or `2'), in addition to the normal output.`--check-order'Fail with an error message if either input file is wrongly ordered.`--nocheck-order'Do not check that both input files are in sorted order. This isthe default.`-e STRING'Replace those output fields that are missing in the input withSTRING.`-i'`--ignore-case'Ignore differences in case when comparing keys. With this option,the lines of the input files must be ordered in the same way. Use`sort -f' to produce this ordering.`-1 FIELD'Join on field FIELD (a positive integer) of file 1.`-2 FIELD'Join on field FIELD (a positive integer) of file 2.`-j FIELD'Equivalent to `-1 FIELD -2 FIELD'.`-o FIELD-LIST'Construct each output line according to the format in FIELD-LIST.Each element in FIELD-LIST is either the single character `0' orhas the form M.N where the file number, M, is `1' or `2' and N isa positive field number.A field specification of `0' denotes the join field. In mostcases, the functionality of the `0' field spec may be reproducedusing the explicit M.N that corresponds to the join field.However, when printing unpairable lines (using either of the `-a'or `-v' options), there is no way to specify the join field usingM.N in FIELD-LIST if there are unpairable lines in both files. Togive `join' that functionality, POSIX invented the `0' fieldspecification notation.The elements in FIELD-LIST are separated by commas or blanks.Blank separators typically need to be quoted for the shell. Forexample, the commands `join -o 1.2,2.2' and `join -o '1.2 2.2''are equivalent.All output lines--including those printed because of any -a or -voption--are subject to the specified FIELD-LIST.`-t CHAR'Use character CHAR as the input and output field separator. Treatas significant each occurrence of CHAR in the input file. Use`sort -t CHAR', without the `-b' option of `sort', to produce thisordering.`-v FILE-NUMBER'Print a line for each unpairable line in file FILE-NUMBER (either`1' or `2'), instead of the normal output.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Operating on characters, Next: Directory listing, Prev: Operating on fields within a line, Up: Top9 Operating on characters*************************This commands operate on individual characters.* Menu:* tr invocation:: Translate, squeeze, and/or delete characters.* expand invocation:: Convert tabs to spaces.* unexpand invocation:: Convert spaces to tabs.File: coreutils.info, Node: tr invocation, Next: expand invocation, Up: Operating on characters9.1 `tr': Translate, squeeze, and/or delete characters======================================================Synopsis:tr [OPTION]... SET1 [SET2]`tr' copies standard input to standard output, performing one of thefollowing operations:* translate, and optionally squeeze repeated characters in theresult,* squeeze repeated characters,* delete characters,* delete characters, then squeeze repeated characters from theresult.The SET1 and (if given) SET2 arguments define ordered sets ofcharacters, referred to below as SET1 and SET2. These sets are thecharacters of the input that `tr' operates on. The `--complement'(`-c', `-C') option replaces SET1 with its complement (all of thecharacters that are not in SET1).Currently `tr' fully supports only single-byte characters.Eventually it will support multibyte characters; when it does, the `-C'option will cause it to complement the set of characters, whereas `-c'will cause it to complement the set of values. This distinction willmatter only when some values are not characters, and this is possibleonly in locales using multibyte encodings when the input containsencoding errors.The program accepts the `--help' and `--version' options. *NoteCommon options::. Options must precede operands.An exit status of zero indicates success, and a nonzero valueindicates failure.* Menu:* Character sets:: Specifying sets of characters.* Translating:: Changing one set of characters to another.* Squeezing:: Squeezing repeats and deleting.File: coreutils.info, Node: Character sets, Next: Translating, Up: tr invocation9.1.1 Specifying sets of characters-----------------------------------The format of the SET1 and SET2 arguments resembles the format ofregular expressions; however, they are not regular expressions, onlylists of characters. Most characters simply represent themselves inthese strings, but the strings can contain the shorthands listed below,for convenience. Some of them can be used only in SET1 or SET2, asnoted below.Backslash escapesThe following backslash escape sequences are recognized:`\a'Control-G.`\b'Control-H.`\f'Control-L.`\n'Control-J.`\r'Control-M.`\t'Control-I.`\v'Control-K.`\OOO'The character with the value given by OOO, which is 1 to 3octal digits,`\\'A backslash.While a backslash followed by a character not listed above isinterpreted as that character, the backslash also effectivelyremoves any special significance, so it is useful to escape `[',`]', `*', and `-'.RangesThe notation `M-N' expands to all of the characters from M throughN, in ascending order. M should collate before N; if it doesn't,an error results. As an example, `0-9' is the same as`0123456789'.GNU `tr' does not support the System V syntax that uses squarebrackets to enclose ranges. Translations specified in that formatsometimes work as expected, since the brackets are oftentransliterated to themselves. However, they should be avoidedbecause they sometimes behave unexpectedly. For example, `tr -d'[0-9]'' deletes brackets as well as digits.Many historically common and even accepted uses of ranges are notportable. For example, on EBCDIC hosts using the `A-Z' range willnot do what most would expect because `A' through `Z' are notcontiguous as they are in ASCII. If you can rely on a POSIXcompliant version of `tr', then the best way to work around thisis to use character classes (see below). Otherwise, it is mostportable (and most ugly) to enumerate the members of the ranges.Repeated charactersThe notation `[C*N]' in SET2 expands to N copies of character C.Thus, `[y*6]' is the same as `yyyyyy'. The notation `[C*]' inSTRING2 expands to as many copies of C as are needed to make SET2as long as SET1. If N begins with `0', it is interpreted inoctal, otherwise in decimal.Character classesThe notation `[:CLASS:]' expands to all of the characters in the(predefined) class CLASS. The characters expand in no particularorder, except for the `upper' and `lower' classes, which expand inascending order. When the `--delete' (`-d') and`--squeeze-repeats' (`-s') options are both given, any characterclass can be used in SET2. Otherwise, only the character classes`lower' and `upper' are accepted in SET2, and then only if thecorresponding character class (`upper' and `lower', respectively)is specified in the same relative position in SET1. Doing thisspecifies case conversion. The class names are given below; anerror results when an invalid class name is given.`alnum'Letters and digits.`alpha'Letters.`blank'Horizontal whitespace.`cntrl'Control characters.`digit'Digits.`graph'Printable characters, not including space.`lower'Lowercase letters.`print'Printable characters, including space.`punct'Punctuation characters.`space'Horizontal or vertical whitespace.`upper'Uppercase letters.`xdigit'Hexadecimal digits.Equivalence classesThe syntax `[=C=]' expands to all of the characters that areequivalent to C, in no particular order. Equivalence classes area relatively recent invention intended to support non-Englishalphabets. But there seems to be no standard way to define themor determine their contents. Therefore, they are not fullyimplemented in GNU `tr'; each character's equivalence classconsists only of that character, which is of no particular use.File: coreutils.info, Node: Translating, Next: Squeezing, Prev: Character sets, Up: tr invocation9.1.2 Translating-----------------`tr' performs translation when SET1 and SET2 are both given and the`--delete' (`-d') option is not given. `tr' translates each characterof its input that is in SET1 to the corresponding character in SET2.Characters not in SET1 are passed through unchanged. When a characterappears more than once in SET1 and the corresponding characters in SET2are not all the same, only the final one is used. For example, thesetwo commands are equivalent:tr aaa xyztr a zA common use of `tr' is to convert lowercase characters touppercase. This can be done in many ways. Here are three of them:tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZtr a-z A-Ztr '[:lower:]' '[:upper:]'But note that using ranges like `a-z' above is not portable.When `tr' is performing translation, SET1 and SET2 typically havethe same length. If SET1 is shorter than SET2, the extra characters atthe end of SET2 are ignored.On the other hand, making SET1 longer than SET2 is not portable;POSIX says that the result is undefined. In this situation, BSD `tr'pads SET2 to the length of SET1 by repeating the last character of SET2as many times as necessary. System V `tr' truncates SET1 to the lengthof SET2.By default, GNU `tr' handles this case like BSD `tr'. When the`--truncate-set1' (`-t') option is given, GNU `tr' handles this caselike the System V `tr' instead. This option is ignored for operationsother than translation.Acting like System V `tr' in this case breaks the relatively commonBSD idiom:tr -cs A-Za-z0-9 '\012'because it converts only zero bytes (the first element in thecomplement of SET1), rather than all non-alphanumerics, to newlines.By the way, the above idiom is not portable because it uses ranges, andit assumes that the octal code for newline is 012. Assuming a POSIXcompliant `tr', here is a better way to write it:tr -cs '[:alnum:]' '[\n*]'File: coreutils.info, Node: Squeezing, Prev: Translating, Up: tr invocation9.1.3 Squeezing repeats and deleting------------------------------------When given just the `--delete' (`-d') option, `tr' removes any inputcharacters that are in SET1.When given just the `--squeeze-repeats' (`-s') option, `tr' replaceseach input sequence of a repeated character that is in SET1 with asingle occurrence of that character.When given both `--delete' and `--squeeze-repeats', `tr' firstperforms any deletions using SET1, then squeezes repeats from anyremaining characters using SET2.The `--squeeze-repeats' option may also be used when translating, inwhich case `tr' first performs translation, then squeezes repeats fromany remaining characters using SET2.Here are some examples to illustrate various combinations of options:* Remove all zero bytes:tr -d '\0'* Put all words on lines by themselves. This converts allnon-alphanumeric characters to newlines, then squeezes each stringof repeated newlines into a single newline:tr -cs '[:alnum:]' '[\n*]'* Convert each sequence of repeated newlines to a single newline:tr -s '\n'* Find doubled occurrences of words in a document. For example,people often write "the the" with the repeated words separated bya newline. The Bourne shell script below works first byconverting each sequence of punctuation and blank characters to asingle newline. That puts each "word" on a line by itself. Nextit maps all uppercase characters to lower case, and finally itruns `uniq' with the `-d' option to print out only the words thatwere repeated.#!/bin/shcat -- "$@" \| tr -s '[:punct:][:blank:]' '[\n*]' \| tr '[:upper:]' '[:lower:]' \| uniq -d* Deleting a small set of characters is usually straightforward.For example, to remove all `a's, `x's, and `M's you would do this:tr -d axMHowever, when `-' is one of those characters, it can be trickybecause `-' has special meanings. Performing the same task asabove but also removing all `-' characters, we might try `tr -d-axM', but that would fail because `tr' would try to interpret`-a' as a command-line option. Alternatively, we could tryputting the hyphen inside the string, `tr -d a-xM', but thatwouldn't work either because it would make `tr' interpret `a-x' asthe range of characters `a'...`x' rather than the three. One wayto solve the problem is to put the hyphen at the end of the listof characters:tr -d axM-Or you can use `--' to terminate option processing:tr -d -- -axMMore generally, use the character class notation `[=c=]' with `-'(or any other character) in place of the `c':tr -d '[=-=]axM'Note how single quotes are used in the above example to protect thesquare brackets from interpretation by a shell.File: coreutils.info, Node: expand invocation, Next: unexpand invocation, Prev: tr invocation, Up: Operating on characters9.2 `expand': Convert tabs to spaces====================================`expand' writes the contents of each given FILE, or standard input ifnone are given or for a FILE of `-', to standard output, with tabcharacters converted to the appropriate number of spaces. Synopsis:expand [OPTION]... [FILE]...By default, `expand' converts all tabs to spaces. It preservesbackspace characters in the output; they decrement the column count fortab calculations. The default action is equivalent to `-t 8' (set tabsevery 8 columns).The program accepts the following options. Also see *note Commonoptions::.`-t TAB1[,TAB2]...'`--tabs=TAB1[,TAB2]...'If only one tab stop is given, set the tabs TAB1 spaces apart(default is 8). Otherwise, set the tabs at columns TAB1, TAB2,... (numbered from 0), and replace any tabs beyond the last tabstop given with single spaces. Tab stops can be separated byblanks as well as by commas.For compatibility, GNU `expand' also accepts the obsolete optionsyntax, `-T1[,T2]...'. New scripts should use `-t T1[,T2]...'instead.`-i'`--initial'Only convert initial tabs (those that precede all non-space ornon-tab characters) on each line to spaces.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: unexpand invocation, Prev: expand invocation, Up: Operating on characters9.3 `unexpand': Convert spaces to tabs======================================`unexpand' writes the contents of each given FILE, or standard input ifnone are given or for a FILE of `-', to standard output, convertingblanks at the beginning of each line into as many tab characters asneeded. In the default POSIX locale, a "blank" is a space or a tab;other locales may specify additional blank characters. Synopsis:unexpand [OPTION]... [FILE]...By default, `unexpand' converts only initial blanks (those thatprecede all non-blank characters) on each line. It preserves backspacecharacters in the output; they decrement the column count for tabcalculations. By default, tabs are set at every 8th column.The program accepts the following options. Also see *note Commonoptions::.`-t TAB1[,TAB2]...'`--tabs=TAB1[,TAB2]...'If only one tab stop is given, set the tabs TAB1 columns apartinstead of the default 8. Otherwise, set the tabs at columnsTAB1, TAB2, ... (numbered from 0), and leave blanks beyond the tabstops given unchanged. Tab stops can be separated by blanks aswell as by commas. This option implies the `-a' option.For compatibility, GNU `unexpand' supports the obsolete optionsyntax, `-TAB1[,TAB2]...', where tab stops must be separated bycommas. (Unlike `-t', this obsolete option does not imply `-a'.)New scripts should use `--first-only -t TAB1[,TAB2]...' instead.`-a'`--all'Also convert all sequences of two or more blanks just before a tabstop, even if they occur after non-blank characters in a line.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Directory listing, Next: Basic operations, Prev: Operating on characters, Up: Top10 Directory listing********************This chapter describes the `ls' command and its variants `dir' and`vdir', which list information about files.* Menu:* ls invocation:: List directory contents.* dir invocation:: Briefly ls.* vdir invocation:: Verbosely ls.* dircolors invocation:: Color setup for ls, etc.File: coreutils.info, Node: ls invocation, Next: dir invocation, Up: Directory listing10.1 `ls': List directory contents==================================The `ls' program lists information about files (of any type, includingdirectories). Options and file arguments can be intermixedarbitrarily, as usual.For non-option command-line arguments that are directories, bydefault `ls' lists the contents of directories, not recursively, andomitting files with names beginning with `.'. For other non-optionarguments, by default `ls' lists just the file name. If no non-optionargument is specified, `ls' operates on the current directory, actingas if it had been invoked with a single argument of `.'.By default, the output is sorted alphabetically, according to thelocale settings in effect.(1) If standard output is a terminal, theoutput is in columns (sorted vertically) and control characters areoutput as question marks; otherwise, the output is listed one per lineand control characters are output as-is.Because `ls' is such a fundamental program, it has accumulated manyoptions over the years. They are described in the subsections below;within each section, options are listed alphabetically (ignoring case).The division of options into the subsections is not absolute, since someoptions affect more than one aspect of `ls''s operation.Exit status:0 success1 minor problems (e.g., failure to access a file or directory notspecified as a command line argument. This happens when listing adirectory in which entries are actively being removed or renamed.)2 serious trouble (e.g., memory exhausted, invalid option or failureto access file or directory specified as a command line argument)Also see *note Common options::.* Menu:* Which files are listed::* What information is listed::* Sorting the output::* More details about version sort::* General output formatting::* Formatting file timestamps::* Formatting the file names::---------- Footnotes ----------(1) If you use a non-POSIX locale (e.g., by setting `LC_ALL' to`en_US'), then `ls' may produce output that is sorted differently thanyou're accustomed to. In that case, set the `LC_ALL' environmentvariable to `C'.File: coreutils.info, Node: Which files are listed, Next: What information is listed, Up: ls invocation10.1.1 Which files are listed-----------------------------These options determine which files `ls' lists information for. Bydefault, `ls' lists files and the contents of any directories on thecommand line, except that in directories it ignores files whose namesstart with `.'.`-a'`--all'In directories, do not ignore file names that start with `.'.`-A'`--almost-all'In directories, do not ignore all file names that start with `.';ignore only `.' and `..'. The `--all' (`-a') option overridesthis option.`-B'`--ignore-backups'In directories, ignore files that end with `~'. This option isequivalent to `--ignore='*~' --ignore='.*~''.`-d'`--directory'List just the names of directories, as with other types of files,rather than listing their contents. Do not follow symbolic linkslisted on the command line unless the `--dereference-command-line'(`-H'), `--dereference' (`-L'), or`--dereference-command-line-symlink-to-dir' options are specified.`-H'`--dereference-command-line'If a command line argument specifies a symbolic link, showinformation for the file the link references rather than for thelink itself.`--dereference-command-line-symlink-to-dir'Do not dereference symbolic links, with one exception: if acommand line argument specifies a symbolic link that refers to adirectory, show information for that directory rather than for thelink itself. This is the default behavior when no otherdereferencing-related option has been specified (`--classify'(`-F'), `--directory' (`-d'), (`-l'), `--dereference' (`-L'), or`--dereference-command-line' (`-H')).`--group-directories-first'Group all the directories before the files and then sort thedirectories and the files separately using the selected sort key(see -sort option). That is, this option specifies a primary sortkey, and the -sort option specifies a secondary key. However, anyuse of `--sort=none' (`-U') disables this option altogether.`--hide=PATTERN'In directories, ignore files whose names match the shell patternPATTERN, unless the `--all' (`-a') or `--almost-all' (`-A') isalso given. This option acts like `--ignore=PATTERN' except thatit has no effect if `--all' (`-a') or `--almost-all' (`-A') isalso given.This option can be useful in shell aliases. For example, if `lx'is an alias for `ls --hide='*~'' and `ly' is an alias for `ls--ignore='*~'', then the command `lx -A' lists the file `README~'even though `ly -A' would not.`-I PATTERN'`--ignore=PATTERN'In directories, ignore files whose names match the shell pattern(not regular expression) PATTERN. As in the shell, an initial `.'in a file name does not match a wildcard at the start of PATTERN.Sometimes it is useful to give this option several times. Forexample,$ ls --ignore='.??*' --ignore='.[^.]' --ignore='#*'The first option ignores names of length 3 or more that start with`.', the second ignores all two-character names that start with `.'except `..', and the third ignores names that start with `#'.`-L'`--dereference'When showing file information for a symbolic link, show informationfor the file the link references rather than the link itself.However, even with this option, `ls' still prints the name of thelink itself, not the name of the file that the link points to.`-R'`--recursive'List the contents of all directories recursively.File: coreutils.info, Node: What information is listed, Next: Sorting the output, Prev: Which files are listed, Up: ls invocation10.1.2 What information is listed---------------------------------These options affect the information that `ls' displays. By default,only file names are shown.`--author'List each file's author when producing long format directorylistings. In GNU/Hurd, file authors can differ from their owners,but in other operating systems the two are the same.`-D'`--dired'With the long listing (`-l') format, print an additional line afterthe main output://DIRED// BEG1 END1 BEG2 END2 ...The BEGN and ENDN are unsigned integers that record the byteposition of the beginning and end of each file name in the output.This makes it easy for Emacs to find the names, even when theycontain unusual characters such as space or newline, without fancysearching.If directories are being listed recursively (`-R'), output asimilar line with offsets for each subdirectory name://SUBDIRED// BEG1 END1 ...Finally, output a line of the form://DIRED-OPTIONS// --quoting-style=WORDwhere WORD is the quoting style (*note Formatting the filenames::).Here is an actual example:$ mkdir -p a/sub/deeper a/sub2$ touch a/f1 a/f2$ touch a/sub/deeper/file$ ls -gloRF --dired aa:total 8-rw-r--r-- 1 0 Jun 10 12:27 f1-rw-r--r-- 1 0 Jun 10 12:27 f2drwxr-xr-x 3 4096 Jun 10 12:27 sub/drwxr-xr-x 2 4096 Jun 10 12:27 sub2/a/sub:total 4drwxr-xr-x 2 4096 Jun 10 12:27 deeper/a/sub/deeper:total 0-rw-r--r-- 1 0 Jun 10 12:27 filea/sub2:total 0//DIRED// 48 50 84 86 120 123 158 162 217 223 282 286//SUBDIRED// 2 3 167 172 228 240 290 296//DIRED-OPTIONS// --quoting-style=literalNote that the pairs of offsets on the `//DIRED//' line abovedelimit these names: `f1', `f2', `sub', `sub2', `deeper', `file'.The offsets on the `//SUBDIRED//' line delimit the followingdirectory names: `a', `a/sub', `a/sub/deeper', `a/sub2'.Here is an example of how to extract the fifth entry name,`deeper', corresponding to the pair of offsets, 222 and 228:$ ls -gloRF --dired a > out$ dd bs=1 skip=222 count=6 < out 2>/dev/null; echodeeperNote that although the listing above includes a trailing slash forthe `deeper' entry, the offsets select the name without thetrailing slash. However, if you invoke `ls' with `--dired' alongwith an option like `--escape' (aka `-b') and operate on a filewhose name contains special characters, notice that the backslash_is_ included:$ touch 'a b'$ ls -blog --dired 'a b'-rw-r--r-- 1 0 Jun 10 12:28 a\ b//DIRED// 30 34//DIRED-OPTIONS// --quoting-style=escapeIf you use a quoting style that adds quote marks (e.g.,`--quoting-style=c'), then the offsets include the quote marks.So beware that the user may select the quoting style via theenvironment variable `QUOTING_STYLE'. Hence, applications using`--dired' should either specify an explicit`--quoting-style=literal' option (aka `-N' or `--literal') on thecommand line, or else be prepared to parse the escaped names.`--full-time'Produce long format directory listings, and list times in full.It is equivalent to using `--format=long' with`--time-style=full-iso' (*note Formatting file timestamps::).`-g'Produce long format directory listings, but don't display ownerinformation.`-G'`--no-group'Inhibit display of group information in a long format directorylisting. (This is the default in some non-GNU versions of `ls',so we provide this option for compatibility.)`-h'`--human-readable'Append a size letter to each size, such as `M' for mebibytes.Powers of 1024 are used, not 1000; `M' stands for 1,048,576 bytes.This option is equivalent to `--block-size=human-readable'. Usethe `--si' option if you prefer powers of 1000.`-i'`--inode'Print the inode number (also called the file serial number andindex number) of each file to the left of the file name. (Thisnumber uniquely identifies each file within a particular filesystem.)`-l'`--format=long'`--format=verbose'In addition to the name of each file, print the file type, filemode bits, number of hard links, owner name, group name, size, andtimestamp (*note Formatting file timestamps::), normally themodification time. Print question marks for information thatcannot be determined.Normally the size is printed as a byte count without punctuation,but this can be overridden (*note Block size::). For example, `-h'prints an abbreviated, human-readable count, and`--block-size="'1"' prints a byte count with the thousandsseparator of the current locale.For each directory that is listed, preface the files with a line`total BLOCKS', where BLOCKS is the total disk allocation for allfiles in that directory. The block size currently defaults to 1024bytes, but this can be overridden (*note Block size::). TheBLOCKS computed counts each hard link separately; this is arguablya deficiency.The file type is one of the following characters:`-'regular file`b'block special file`c'character special file`C'high performance ("contiguous data") file`d'directory`D'door (Solaris 2.5 and up)`l'symbolic link`M'off-line ("migrated") file (Cray DMF)`n'network special file (HP-UX)`p'FIFO (named pipe)`P'port (Solaris 10 and up)`s'socket`?'some other file typeThe file mode bits listed are similar to symbolic modespecifications (*note Symbolic Modes::). But `ls' combinesmultiple bits into the third character of each set of permissionsas follows:`s'If the set-user-ID or set-group-ID bit and the correspondingexecutable bit are both set.`S'If the set-user-ID or set-group-ID bit is set but thecorresponding executable bit is not set.`t'If the restricted deletion flag or sticky bit, and theother-executable bit, are both set. The restricted deletionflag is another name for the sticky bit. *Note ModeStructure::.`T'If the restricted deletion flag or sticky bit is set but theother-executable bit is not set.`x'If the executable bit is set and none of the above apply.`-'Otherwise.Following the file mode bits is a single character that specifieswhether an alternate access method such as an access control listapplies to the file. When the character following the file modebits is a space, there is no alternate access method. When it isa printing character, then there is such a method.GNU `ls' uses a `.' character to indicate a file with an SELinuxsecurity context, but no other alternate access method.A file with any other combination of alternate access methods ismarked with a `+' character.`-n'`--numeric-uid-gid'Produce long format directory listings, but display numeric userand group IDs instead of the owner and group names.`-o'Produce long format directory listings, but don't display groupinformation. It is equivalent to using `--format=long' with`--no-group' .`-s'`--size'Print the disk allocation of each file to the left of the filename. This is the amount of disk space used by the file, which isusually a bit more than the file's size, but it can be less if thefile has holes.Normally the disk allocation is printed in units of 1024 bytes,but this can be overridden (*note Block size::).For files that are NFS-mounted from an HP-UX system to a BSDsystem, this option reports sizes that are half the correctvalues. On HP-UX systems, it reports sizes that are twice thecorrect values for files that are NFS-mounted from BSD systems.This is due to a flaw in HP-UX; it also affects the HP-UX `ls'program.`--si'Append an SI-style abbreviation to each size, such as `M' formegabytes. Powers of 1000 are used, not 1024; `M' stands for1,000,000 bytes. This option is equivalent to `--block-size=si'.Use the `-h' or `--human-readable' option if you prefer powers of1024.`-Z'`--context'Display the SELinux security context or `?' if none is found.When used with the `-l' option, print the security context to theleft of the size column.File: coreutils.info, Node: Sorting the output, Next: More details about version sort, Prev: What information is listed, Up: ls invocation10.1.3 Sorting the output-------------------------These options change the order in which `ls' sorts the information itoutputs. By default, sorting is done by character code (e.g., ASCIIorder).`-c'`--time=ctime'`--time=status'If the long listing format (e.g., `-l', `-o') is being used, printthe status change time (the `ctime' in the inode) instead of themodification time. When explicitly sorting by time (`--sort=time'or `-t') or when not using a long listing format, sort accordingto the status change time.`-f'Primarily, like `-U'--do not sort; list the files in whateverorder they are stored in the directory. But also enable `-a' (listall files) and disable `-l', `--color', and `-s' (if they werespecified before the `-f').`-r'`--reverse'Reverse whatever the sorting method is--e.g., list files in reversealphabetical order, youngest first, smallest first, or whatever.`-S'`--sort=size'Sort by file size, largest first.`-t'`--sort=time'Sort by modification time (the `mtime' in the inode), newest first.`-u'`--time=atime'`--time=access'`--time=use'If the long listing format (e.g., `--format=long') is being used,print the last access time (the `atime' in the inode). Whenexplicitly sorting by time (`--sort=time' or `-t') or when notusing a long listing format, sort according to the access time.`-U'`--sort=none'Do not sort; list the files in whatever order they are stored inthe directory. (Do not do any of the other unrelated things that`-f' does.) This is especially useful when listing very largedirectories, since not doing any sorting can be noticeably faster.`-v'`--sort=version'Sort by version name and number, lowest first. It behaves like adefault sort, except that each sequence of decimal digits istreated numerically as an index/version number. (*Note Moredetails about version sort::.)`-X'`--sort=extension'Sort directory contents alphabetically by file extension(characters after the last `.'); files with no extension aresorted first.File: coreutils.info, Node: More details about version sort, Next: General output formatting, Prev: Sorting the output, Up: ls invocation10.1.4 More details about version sort--------------------------------------The version sort takes into account the fact that file names frequentlyinclude indices or version numbers. Standard sorting functions usuallydo not produce the ordering that people expect because comparisons aremade on a character-by-character basis. The version sort addressesthis problem, and is especially useful when browsing directories thatcontain many files with indices/version numbers in their names:$ ls -1 $ ls -1vfoo.zml-1.gz foo.zml-1.gzfoo.zml-100.gz foo.zml-2.gzfoo.zml-12.gz foo.zml-6.gzfoo.zml-13.gz foo.zml-12.gzfoo.zml-2.gz foo.zml-13.gzfoo.zml-25.gz foo.zml-25.gzfoo.zml-6.gz foo.zml-100.gzVersion-sorted strings are compared such that if VER1 and VER2 areversion numbers and PREFIX and SUFFIX (SUFFIX matching the regularexpression `(\.[A-Za-z~][A-Za-z0-9~]*)*') are strings then VER1 < VER2implies that the name composed of "PREFIX VER1 SUFFIX" sorts before"PREFIX VER2 SUFFIX".Note also that leading zeros of numeric parts are ignored:$ ls -1 $ ls -1vabc-1.007.tgz abc-1.01a.tgzabc-1.012b.tgz abc-1.007.tgzabc-1.01a.tgz abc-1.012b.tgzThis functionality is implemented using gnulib's `filevercmp'function. One result of that implementation decision is that `ls -v'and `sort -V' do not use the locale category, `LC_COLLATE', which meansnon-numeric prefixes are sorted as if `LC_COLLATE' were set to `C'.File: coreutils.info, Node: General output formatting, Next: Formatting file timestamps, Prev: More details about version sort, Up: ls invocation10.1.5 General output formatting--------------------------------These options affect the appearance of the overall output.`-1'`--format=single-column'List one file per line. This is the default for `ls' when standardoutput is not a terminal.`-C'`--format=vertical'List files in columns, sorted vertically. This is the default for`ls' if standard output is a terminal. It is always the defaultfor the `dir' program. GNU `ls' uses variable width columns todisplay as many files as possible in the fewest lines.`--color [=WHEN]'Specify whether to use color for distinguishing file types. WHENmay be omitted, or one of:* none - Do not use color at all. This is the default.* auto - Only use color if standard output is a terminal.* always - Always use color.Specifying `--color' and no WHEN is equivalent to `--color=always'.Piping a colorized listing through a pager like `more' or `less'usually produces unreadable results. However, using `more -f'does seem to work.`-F'`--classify'`--indicator-style=classify'Append a character to each file name indicating the file type.Also, for regular files that are executable, append `*'. The filetype indicators are `/' for directories, `@' for symbolic links,`|' for FIFOs, `=' for sockets, `>' for doors, and nothing forregular files. Do not follow symbolic links listed on the commandline unless the `--dereference-command-line' (`-H'),`--dereference' (`-L'), or`--dereference-command-line-symlink-to-dir' options are specified.`--file-type'`--indicator-style=file-type'Append a character to each file name indicating the file type.This is like `-F', except that executables are not marked.`--indicator-style=WORD'Append a character indicator with style WORD to entry names, asfollows:`none'Do not append any character indicator; this is the default.`slash'Append `/' for directories. This is the same as the `-p'option.`file-type'Append `/' for directories, `@' for symbolic links, `|' forFIFOs, `=' for sockets, and nothing for regular files. Thisis the same as the `--file-type' option.`classify'Append `*' for executable regular files, otherwise behave asfor `file-type'. This is the same as the `-F' or`--classify' option.`-k'Print file sizes in 1024-byte blocks, overriding the default blocksize (*note Block size::). This option is equivalent to`--block-size=1K'.`-m'`--format=commas'List files horizontally, with as many as will fit on each line,separated by `, ' (a comma and a space).`-p'`--indicator-style=slash'Append a `/' to directory names.`-x'`--format=across'`--format=horizontal'List the files in columns, sorted horizontally.`-T COLS'`--tabsize=COLS'Assume that each tab stop is COLS columns wide. The default is 8.`ls' uses tabs where possible in the output, for efficiency. IfCOLS is zero, do not use tabs at all.Some terminal emulators (at least Apple Terminal 1.5 (133) fromMac OS X 10.4.8) do not properly align columns to the right of aTAB following a non-ASCII byte. If you use such a terminalemulator, use the `-T0' option or put `TABSIZE=0' in yourenvironment to tell `ls' to align using spaces, not tabs.`-w'`--width=COLS'Assume the screen is COLS columns wide. The default is taken fromthe terminal settings if possible; otherwise the environmentvariable `COLUMNS' is used if it is set; otherwise the default is80.File: coreutils.info, Node: Formatting file timestamps, Next: Formatting the file names, Prev: General output formatting, Up: ls invocation10.1.6 Formatting file timestamps---------------------------------By default, file timestamps are listed in abbreviated form. Mostlocales use a timestamp like `2002-03-30 23:45'. However, the defaultPOSIX locale uses a date like `Mar 30 2002' for non-recent timestamps,and a date-without-year and time like `Mar 30 23:45' for recenttimestamps.A timestamp is considered to be "recent" if it is less than sixmonths old, and is not dated in the future. If a timestamp dated todayis not listed in recent form, the timestamp is in the future, whichmeans you probably have clock skew problems which may break programslike `make' that rely on file timestamps.Time stamps are listed according to the time zone rules specified bythe `TZ' environment variable, or by the system default rules if `TZ'is not set. *Note Specifying the Time Zone with `TZ': (libc)TZVariable.The following option changes how file timestamps are printed.`--time-style=STYLE'List timestamps in style STYLE. The STYLE should be one of thefollowing:`+FORMAT'List timestamps using FORMAT, where FORMAT is interpretedlike the format argument of `date' (*note date invocation::).For example, `--time-style="+%Y-%m-%d %H:%M:%S"' causes `ls'to list timestamps like `2002-03-30 23:45:56'. As with`date', FORMAT's interpretation is affected by the `LC_TIME'locale category.If FORMAT contains two format strings separated by a newline,the former is used for non-recent files and the latter forrecent files; if you want output columns to line up, you mayneed to insert spaces in one of the two formats.`full-iso'List timestamps in full using ISO 8601 date, time, and timezone format with nanosecond precision, e.g., `2002-03-3023:45:56.477817180 -0700'. This style is equivalent to`+%Y-%m-%d %H:%M:%S.%N %z'.This is useful because the time output includes all theinformation that is available from the operating system. Forexample, this can help explain `make''s behavior, since GNU`make' uses the full timestamp to determine whether a file isout of date.`long-iso'List ISO 8601 date and time in minutes, e.g., `2002-03-3023:45'. These timestamps are shorter than `full-iso'timestamps, and are usually good enough for everyday work.This style is equivalent to `+%Y-%m-%d %H:%M'.`iso'List ISO 8601 dates for non-recent timestamps (e.g.,`2002-03-30 '), and ISO 8601 month, day, hour, and minute forrecent timestamps (e.g., `03-30 23:45'). These timestampsare uglier than `long-iso' timestamps, but they carry nearlythe same information in a smaller space and their brevityhelps `ls' output fit within traditional 80-column outputlines. The following two `ls' invocations are equivalent:newline=''ls -l --time-style="+%Y-%m-%d $newline%m-%d %H:%M"ls -l --time-style="iso"`locale'List timestamps in a locale-dependent form. For example, aFinnish locale might list non-recent timestamps like `maalis30 2002' and recent timestamps like `maalis 30 23:45'.Locale-dependent timestamps typically consume more space than`iso' timestamps and are harder for programs to parse becauselocale conventions vary so widely, but they are easier formany people to read.The `LC_TIME' locale category specifies the timestamp format.The default POSIX locale uses timestamps like `Mar 30 2002'and `Mar 30 23:45'; in this locale, the following two `ls'invocations are equivalent:newline=''ls -l --time-style="+%b %e %Y$newline%b %e %H:%M"ls -l --time-style="locale"Other locales behave differently. For example, in a Germanlocale, `--time-style="locale"' might be equivalent to`--time-style="+%e. %b %Y $newline%e. %b %H:%M"' and mightgenerate timestamps like `30. Ma"r 2002 ' and `30. Ma"r23:45'.`posix-STYLE'List POSIX-locale timestamps if the `LC_TIME' locale categoryis POSIX, STYLE timestamps otherwise. For example, the`posix-long-iso' style lists timestamps like `Mar 30 2002'and `Mar 30 23:45' when in the POSIX locale, and like`2002-03-30 23:45' otherwise.You can specify the default value of the `--time-style' option withthe environment variable `TIME_STYLE'; if `TIME_STYLE' is not set thedefault style is `locale'. GNU Emacs 21.3 and later use the `--dired'option and therefore can parse any date format, but if you are usingEmacs 21.1 or 21.2 and specify a non-POSIX locale you may need to set`TIME_STYLE="posix-long-iso"'.To avoid certain denial-of-service attacks, timestamps that would belonger than 1000 bytes may be treated as errors.File: coreutils.info, Node: Formatting the file names, Prev: Formatting file timestamps, Up: ls invocation10.1.7 Formatting the file names--------------------------------These options change how file names themselves are printed.`-b'`--escape'`--quoting-style=escape'Quote nongraphic characters in file names using alphabetic andoctal backslash sequences like those used in C.`-N'`--literal'`--quoting-style=literal'Do not quote file names. However, with `ls' nongraphic charactersare still printed as question marks if the output is a terminaland you do not specify the `--show-control-chars' option.`-q'`--hide-control-chars'Print question marks instead of nongraphic characters in filenames. This is the default if the output is a terminal and theprogram is `ls'.`-Q'`--quote-name'`--quoting-style=c'Enclose file names in double quotes and quote nongraphiccharacters as in C.`--quoting-style=WORD'Use style WORD to quote file names and other strings that maycontain arbitrary characters. The WORD should be one of thefollowing:`literal'Output strings as-is; this is the same as the `-N' or`--literal' option.`shell'Quote strings for the shell if they contain shellmetacharacters or would cause ambiguous output. The quotingis suitable for POSIX-compatible shells like `bash', but itdoes not always work for incompatible shells like `csh'.`shell-always'Quote strings for the shell, even if they would normally notrequire quoting.`c'Quote strings as for C character string literals, includingthe surrounding double-quote characters; this is the same asthe `-Q' or `--quote-name' option.`escape'Quote strings as for C character string literals, except omitthe surrounding double-quote characters; this is the same asthe `-b' or `--escape' option.`clocale'Quote strings as for C character string literals, except usesurrounding quotation marks appropriate for the locale.`locale'Quote strings as for C character string literals, except usesurrounding quotation marks appropriate for the locale, andquote `like this' instead of "like this" in the default Clocale. This looks nicer on many displays.You can specify the default value of the `--quoting-style' optionwith the environment variable `QUOTING_STYLE'. If that environmentvariable is not set, the default value is `literal', but thisdefault may change to `shell' in a future version of this package.`--show-control-chars'Print nongraphic characters as-is in file names. This is thedefault unless the output is a terminal and the program is `ls'.File: coreutils.info, Node: dir invocation, Next: vdir invocation, Prev: ls invocation, Up: Directory listing10.2 `dir': Briefly list directory contents===========================================`dir' is equivalent to `ls -C -b'; that is, by default files are listedin columns, sorted vertically, and special characters are representedby backslash escape sequences.*Note `ls': ls invocation.File: coreutils.info, Node: vdir invocation, Next: dircolors invocation, Prev: dir invocation, Up: Directory listing10.3 `vdir': Verbosely list directory contents==============================================`vdir' is equivalent to `ls -l -b'; that is, by default files arelisted in long format and special characters are represented bybackslash escape sequences.File: coreutils.info, Node: dircolors invocation, Prev: vdir invocation, Up: Directory listing10.4 `dircolors': Color setup for `ls'======================================`dircolors' outputs a sequence of shell commands to set up the terminalfor color output from `ls' (and `dir', etc.). Typical usage:eval "`dircolors [OPTION]... [FILE]`"If FILE is specified, `dircolors' reads it to determine which colorsto use for which file types and extensions. Otherwise, a precompileddatabase is used. For details on the format of these files, run`dircolors --print-database'.To make `dircolors' read a `~/.dircolors' file if it exists, you canput the following lines in your `~/.bashrc' (or adapt them to yourfavorite shell):d=.dircolorstest -r $d && eval "$(dircolors $d)"The output is a shell command to set the `LS_COLORS' environmentvariable. You can specify the shell syntax to use on the command line,or `dircolors' will guess it from the value of the `SHELL' environmentvariable.The program accepts the following options. Also see *note Commonoptions::.`-b'`--sh'`--bourne-shell'Output Bourne shell commands. This is the default if the `SHELL'environment variable is set and does not end with `csh' or `tcsh'.`-c'`--csh'`--c-shell'Output C shell commands. This is the default if `SHELL' ends with`csh' or `tcsh'.`-p'`--print-database'Print the (compiled-in) default color configuration database. Thisoutput is itself a valid configuration file, and is fairlydescriptive of the possibilities.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Basic operations, Next: Special file types, Prev: Directory listing, Up: Top11 Basic operations*******************This chapter describes the commands for basic file manipulation:copying, moving (renaming), and deleting (removing).* Menu:* cp invocation:: Copy files.* dd invocation:: Convert and copy a file.* install invocation:: Copy files and set attributes.* mv invocation:: Move (rename) files.* rm invocation:: Remove files or directories.* shred invocation:: Remove files more securely.File: coreutils.info, Node: cp invocation, Next: dd invocation, Up: Basic operations11.1 `cp': Copy files and directories=====================================`cp' copies files (or, optionally, directories). The copy iscompletely independent of the original. You can either copy one file toanother, or copy arbitrarily many files to a destination directory.Synopses:cp [OPTION]... [-T] SOURCE DESTcp [OPTION]... SOURCE... DIRECTORYcp [OPTION]... -t DIRECTORY SOURCE...* If two file names are given, `cp' copies the first file to thesecond.* If the `--target-directory' (`-t') option is given, or failingthat if the last file is a directory and the`--no-target-directory' (`-T') option is not given, `cp' copieseach SOURCE file to the specified directory, using the SOURCEs'names.Generally, files are written just as they are read. For exceptions,see the `--sparse' option below.By default, `cp' does not copy directories. However, the `-R',`-a', and `-r' options cause `cp' to copy recursively by descendinginto source directories and copying files to corresponding destinationdirectories.When copying from a symbolic link, `cp' normally follows the linkonly when not copying recursively. This default can be overridden withthe `--archive' (`-a'), `-d', `--dereference' (`-L'),`--no-dereference' (`-P'), and `-H' options. If more than one of theseoptions is specified, the last one silently overrides the others.When copying to a symbolic link, `cp' follows the link only when itrefers to an existing regular file. However, when copying to adangling symbolic link, `cp' refuses by default, and fails with adiagnostic, since the operation is inherently dangerous. This behavioris contrary to historical practice and to POSIX. Set `POSIXLY_CORRECT'to make `cp' attempt to create the target of a dangling destinationsymlink, in spite of the possible risk. Also, when an option like`--backup' or `--link' acts to rename or remove the destination beforecopying, `cp' renames or removes the symbolic link rather than the fileit points to.By default, `cp' copies the contents of special files only when notcopying recursively. This default can be overridden with the`--copy-contents' option.`cp' generally refuses to copy a file onto itself, with thefollowing exception: if `--force --backup' is specified with SOURCE andDEST identical, and referring to a regular file, `cp' will make abackup file, either regular or numbered, as specified in the usual ways(*note Backup options::). This is useful when you simply want to makea backup of an existing file before changing it.The program accepts the following options. Also see *note Commonoptions::.`-a'`--archive'Preserve as much as possible of the structure and attributes of theoriginal files in the copy (but do not attempt to preserve internaldirectory structure; i.e., `ls -U' may list the entries in a copieddirectory in a different order). Try to preserve SELinux securitycontext and extended attributes (xattr), but ignore any failure todo that and print no corresponding diagnostic. Equivalent to `-dR--preserve=all' with the reduced diagnostics.`-b'`--backup[=METHOD]'*Note Backup options::. Make a backup of each file that wouldotherwise be overwritten or removed. As a special case, `cp'makes a backup of SOURCE when the force and backup options aregiven and SOURCE and DEST are the same name for an existing,regular file. One useful application of this combination ofoptions is this tiny Bourne shell script:#!/bin/sh# Usage: backup FILE...# Create a GNU-style backup of each listed FILE.for i; docp --backup --force -- "$i" "$i"done`--copy-contents'If copying recursively, copy the contents of any special files(e.g., FIFOs and device files) as if they were regular files.This means trying to read the data in each source file and writingit to the destination. It is usually a mistake to use thisoption, as it normally has undesirable effects on special fileslike FIFOs and the ones typically found in the `/dev' directory.In most cases, `cp -R --copy-contents' will hang indefinitelytrying to read from FIFOs and special files like `/dev/console',and it will fill up your destination disk if you use it to copy`/dev/zero'. This option has no effect unless copyingrecursively, and it does not affect the copying of symbolic links.`-d'Copy symbolic links as symbolic links rather than copying thefiles that they point to, and preserve hard links between sourcefiles in the copies. Equivalent to `--no-dereference--preserve=links'.`-f'`--force'When copying without this option and an existing destination filecannot be opened for writing, the copy fails. However, with`--force'), when a destination file cannot be opened, `cp' thenremoves it and tries to open it again. Contrast this behaviorwith that enabled by `--link' and `--symbolic-link', whereby thedestination file is never opened but rather is removedunconditionally. Also see the description of`--remove-destination'.This option is independent of the `--interactive' or `-i' option:neither cancels the effect of the other.This option is redundant if the `--no-clobber' or `-n' option isused.`-H'If a command line argument specifies a symbolic link, then copy thefile it points to rather than the symbolic link itself. However,copy (preserving its nature) any symbolic link that is encounteredvia recursive traversal.`-i'`--interactive'When copying a file other than a directory, prompt whether tooverwrite an existing destination file. The `-i' option overridesa previous `-n' option.`-l'`--link'Make hard links instead of copies of non-directories.`-L'`--dereference'Follow symbolic links when copying from them.`-n'`--no-clobber'Do not overwrite an existing file. The `-n' option overrides aprevious `-i' option. This option is mutually exclusive with `-b'or `--backup' option.`-P'`--no-dereference'Copy symbolic links as symbolic links rather than copying thefiles that they point to. This option affects only symbolic linksin the source; symbolic links in the destination are alwaysfollowed if possible.`-p'`--preserve[=ATTRIBUTE_LIST]'Preserve the specified attributes of the original files. Ifspecified, the ATTRIBUTE_LIST must be a comma-separated list ofone or more of the following strings:`mode'Preserve the file mode bits and access control lists.`ownership'Preserve the owner and group. On most modern systems, onlyusers with appropriate privileges may change the owner of afile, and ordinary users may preserve the group ownership ofa file only if they happen to be a member of the desiredgroup.`timestamps'Preserve the times of last access and last modification, whenpossible. In general, it is not possible to preserve theseattributes when the affected file is a symbolic link.However, FreeBSD now provides the `lutimes' function, whichmakes it possible even for symbolic links. However, thisimplementation does not yet take advantage of that.`links'Preserve in the destination files any links betweencorresponding source files.`context'Preserve SELinux security context of the file. `cp' will failif the preserving of SELinux security context is notsuccesful.`xattr'Preserve extended attributes if `cp' is built with xattrsupport, and xattrs are supported and enabled on your filesystem. If SELinux context and/or ACLs are implemented usingxattrs, they are preserved by this option as well.`all'Preserve all file attributes. Equivalent to specifying allof the above, but with the difference that failure topreserve SELinux security context or extended attributes doesnot change `cp''s exit status. `cp' does diagnose suchfailures.Using `--preserve' with no ATTRIBUTE_LIST is equivalent to`--preserve=mode,ownership,timestamps'.In the absence of this option, each destination file is createdwith the mode bits of the corresponding source file, minus thebits set in the umask and minus the set-user-ID and set-group-IDbits. *Note File permissions::.`--no-preserve=ATTRIBUTE_LIST'Do not preserve the specified attributes. The ATTRIBUTE_LIST hasthe same form as for `--preserve'.`--parents'Form the name of each destination file by appending to the targetdirectory a slash and the specified name of the source file. Thelast argument given to `cp' must be the name of an existingdirectory. For example, the command:cp --parents a/b/c existing_dircopies the file `a/b/c' to `existing_dir/a/b/c', creating anymissing intermediate directories.`-R'`-r'`--recursive'Copy directories recursively. By default, do not follow symboliclinks in the source; see the `--archive' (`-a'), `-d',`--dereference' (`-L'), `--no-dereference' (`-P'), and `-H'options. Special files are copied by creating a destination fileof the same type as the source; see the `--copy-contents' option.It is not portable to use `-r' to copy symbolic links or specialfiles. On some non-GNU systems, `-r' implies the equivalent of`-L' and `--copy-contents' for historical reasons. Also, it isnot portable to use `-R' to copy symbolic links unless you alsospecify `-P', as POSIX allows implementations that dereferencesymbolic links by default.`--remove-destination'Remove each existing destination file before attempting to open it(contrast with `-f' above).`--sparse=WHEN'A "sparse file" contains "holes"--a sequence of zero bytes thatdoes not occupy any physical disk blocks; the `read' system callreads these as zeros. This can both save considerable disk spaceand increase speed, since many binary files contain lots ofconsecutive zero bytes. By default, `cp' detects holes in inputsource files via a crude heuristic and makes the correspondingoutput file sparse as well. Only regular files may be sparse.The WHEN value can be one of the following:`auto'The default behavior: if the input file is sparse, attempt tomake the output file sparse, too. However, if an output fileexists but refers to a non-regular file, then do not attemptto make it sparse.`always'For each sufficiently long sequence of zero bytes in theinput file, attempt to create a corresponding hole in theoutput file, even if the input file does not appear to besparse. This is useful when the input file resides on a filesystem that does not support sparse files (for example,`efs' file systems in SGI IRIX 5.3 and earlier), but theoutput file is on a type of file system that does supportthem. Holes may be created only in regular files, so if thedestination file is of some other type, `cp' does not eventry to make it sparse.`never'Never make the output file sparse. This is useful increating a file for use with the `mkswap' command, since sucha file must not have any holes.`--strip-trailing-slashes'Remove any trailing slashes from each SOURCE argument. *NoteTrailing slashes::.`-s'`--symbolic-link'Make symbolic links instead of copies of non-directories. Allsource file names must be absolute (starting with `/') unless thedestination files are in the current directory. This option merelyresults in an error message on systems that do not supportsymbolic links.`-S SUFFIX'`--suffix=SUFFIX'Append SUFFIX to each backup file made with `-b'. *Note Backupoptions::.`-t DIRECTORY'`--target-directory=DIRECTORY'Specify the destination DIRECTORY. *Note Target directory::.`-T'`--no-target-directory'Do not treat the last operand specially when it is a directory or asymbolic link to a directory. *Note Target directory::.`-u'`--update'Do not copy a non-directory that has an existing destination withthe same or newer modification time. If time stamps are beingpreserved, the comparison is to the source time stamp truncated tothe resolutions of the destination file system and of the systemcalls used to update time stamps; this avoids duplicate work ifseveral `cp -pu' commands are executed with the same source anddestination.`-v'`--verbose'Print the name of each file before copying it.`-x'`--one-file-system'Skip subdirectories that are on different file systems from theone that the copy started on. However, mount point directories_are_ copied.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: dd invocation, Next: install invocation, Prev: cp invocation, Up: Basic operations11.2 `dd': Convert and copy a file==================================`dd' copies a file (from standard input to standard output, by default)with a changeable I/O block size, while optionally performingconversions on it. Synopses:dd [OPERAND]...dd OPTIONThe only options are `--help' and `--version'. *Note Commonoptions::. `dd' accepts the following operands.`if=FILE'Read from FILE instead of standard input.`of=FILE'Write to FILE instead of standard output. Unless `conv=notrunc'is given, `dd' truncates FILE to zero bytes (or the size specifiedwith `seek=').`ibs=BYTES'Set the input block size to BYTES. This makes `dd' read BYTES perblock. The default is 512 bytes.`obs=BYTES'Set the output block size to BYTES. This makes `dd' write BYTESper block. The default is 512 bytes.`bs=BYTES'Set both input and output block sizes to BYTES. This makes `dd'read and write BYTES per block, overriding any `ibs' and `obs'settings. In addition, if no data-transforming `conv' option isspecified, each input block is copied to the output as a singleblock, without aggregating short reads.`cbs=BYTES'Set the conversion block size to BYTES. When convertingvariable-length records to fixed-length ones (`conv=block') or thereverse (`conv=unblock'), use BYTES as the fixed record length.`skip=BLOCKS'Skip BLOCKS `ibs'-byte blocks in the input file before copying.`seek=BLOCKS'Skip BLOCKS `obs'-byte blocks in the output file before copying.`count=BLOCKS'Copy BLOCKS `ibs'-byte blocks from the input file, instead ofeverything until the end of the file.`status=noxfer'Do not print the overall transfer rate and volume statistics thatnormally make up the third status line when `dd' exits.`conv=CONVERSION[,CONVERSION]...'Convert the file as specified by the CONVERSION argument(s). (Nospaces around any comma(s).)Conversions:`ascii'Convert EBCDIC to ASCII, using the conversion table specifiedby POSIX. This provides a 1:1 translation for all 256 bytes.`ebcdic'Convert ASCII to EBCDIC. This is the inverse of the `ascii'conversion.`ibm'Convert ASCII to alternate EBCDIC, using the alternateconversion table specified by POSIX. This is not a 1:1translation, but reflects common historical practice for `~',`[', and `]'.The `ascii', `ebcdic', and `ibm' conversions are mutuallyexclusive.`block'For each line in the input, output `cbs' bytes, replacing theinput newline with a space and padding with spaces asnecessary.`unblock'Replace trailing spaces in each `cbs'-sized input block with anewline.The `block' and `unblock' conversions are mutually exclusive.`lcase'Change uppercase letters to lowercase.`ucase'Change lowercase letters to uppercase.The `lcase' and `ucase' conversions are mutually exclusive.`swab'Swap every pair of input bytes. GNU `dd', unlike others,works when an odd number of bytes are read--the last byte issimply copied (since there is nothing to swap it with).`noerror'Continue after read errors.`nocreat'Do not create the output file; the output file must alreadyexist.`excl'Fail if the output file already exists; `dd' must create theoutput file itself.The `excl' and `nocreat' conversions are mutually exclusive.`notrunc'Do not truncate the output file.`sync'Pad every input block to size of `ibs' with trailing zerobytes. When used with `block' or `unblock', pad with spacesinstead of zero bytes.`fdatasync'Synchronize output data just before finishing. This forces aphysical write of output data.`fsync'Synchronize output data and metadata just before finishing.This forces a physical write of output data and metadata.`iflag=FLAG[,FLAG]...'Access the input file using the flags specified by the FLAGargument(s). (No spaces around any comma(s).)`oflag=FLAG[,FLAG]...'Access the output file using the flags specified by the FLAGargument(s). (No spaces around any comma(s).)Here are the flags. Not every flag is supported on every operatingsystem.`append'Write in append mode, so that even if some other process iswriting to this file, every `dd' write will append to thecurrent contents of the file. This flag makes sense only foroutput. If you combine this flag with the `of=FILE' operand,you should also specify `conv=notrunc' unless you want theoutput file to be truncated before being appended to.`cio'Use concurrent I/O mode for data. This mode performs directI/O and drops the POSIX requirement to serialize all I/O tothe same file. A file cannot be opened in CIO mode and witha standard open at the same time.`direct'Use direct I/O for data, avoiding the buffer cache.`directory'Fail unless the file is a directory. Most operating systemsdo not allow I/O to a directory, so this flag has limitedutility.`dsync'Use synchronized I/O for data. For the output file, thisforces a physical write of output data on each write. Forthe input file, this flag can matter when reading from aremote file that has been written to synchronously by someother process. Metadata (e.g., last-access and last-modifiedtime) is not necessarily synchronized.`sync'Use synchronized I/O for both data and metadata.`nonblock'Use non-blocking I/O.`noatime'Do not update the file's access time. Some older filesystems silently ignore this flag, so it is a good idea totest it on your files before relying on it.`noctty'Do not assign the file to be a controlling terminal for `dd'.This has no effect when the file is not a terminal. On manyhosts (e.g., GNU/Linux hosts), this option has no effect atall.`nofollow'Do not follow symbolic links.`nolinks'Fail if the file has multiple hard links.`binary'Use binary I/O. This option has an effect only on nonstandardplatforms that distinguish binary from text I/O.`text'Use text I/O. Like `binary', this option has no effect onstandard platforms.`fullblock'Accumulate full blocks from input. The `read' system callmay return early if a full block is not available. When thathappens, continue calling `read' to fill the remainder of theblock. This flag can be used only with `iflag'.These flags are not supported on all systems, and `dd' rejectsattempts to use them when they are not supported. When readingfrom standard input or writing to standard output, the `nofollow'and `noctty' flags should not be specified, and the other flags(e.g., `nonblock') can affect how other processes behave with theaffected file descriptors, even after `dd' exits.The numeric-valued strings above (BYTES and BLOCKS) can be followedby a multiplier: `b'=512, `c'=1, `w'=2, `xM'=M, or any of the standardblock size suffixes like `k'=1024 (*note Block size::).Use different `dd' invocations to use different block sizes forskipping and I/O. For example, the following shell commands copy datain 512 KiB blocks between a disk and a tape, but do not save or restorea 4 KiB label at the start of the disk:disk=/dev/rdsk/c0t1d0s2tape=/dev/rmt/0# Copy all but the label from disk to tape.(dd bs=4k skip=1 count=0 && dd bs=512k) <$disk >$tape# Copy from tape back to disk, but leave the disk label alone.(dd bs=4k seek=1 count=0 && dd bs=512k) <$tape >$diskSending an `INFO' signal to a running `dd' process makes it printI/O statistics to standard error and then resume copying. In theexample below, `dd' is run in the background to copy 10 million blocks.The `kill' command makes it output intermediate I/O statistics, andwhen `dd' completes normally or is killed by the `SIGINT' signal, itoutputs the final statistics.$ dd if=/dev/zero of=/dev/null count=10MB & pid=$!$ kill -s INFO $pid; wait $pid3385223+0 records in3385223+0 records out1733234176 bytes (1.7 GB) copied, 6.42173 seconds, 270 MB/s10000000+0 records in10000000+0 records out5120000000 bytes (5.1 GB) copied, 18.913 seconds, 271 MB/sOn systems lacking the `INFO' signal `dd' responds to the `USR1'signal instead, unless the `POSIXLY_CORRECT' environment variable isset.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: install invocation, Next: mv invocation, Prev: dd invocation, Up: Basic operations11.3 `install': Copy files and set attributes=============================================`install' copies files while setting their file mode bits and, ifpossible, their owner and group. Synopses:install [OPTION]... [-T] SOURCE DESTinstall [OPTION]... SOURCE... DIRECTORYinstall [OPTION]... -t DIRECTORY SOURCE...install [OPTION]... -d DIRECTORY...* If two file names are given, `install' copies the first file to thesecond.* If the `--target-directory' (`-t') option is given, or failingthat if the last file is a directory and the`--no-target-directory' (`-T') option is not given, `install'copies each SOURCE file to the specified directory, using theSOURCEs' names.* If the `--directory' (`-d') option is given, `install' createseach DIRECTORY and any missing parent directories. Parentdirectories are created with mode `u=rwx,go=rx' (755), regardlessof the `-m' option or the current umask. *Note Directory Setuidand Setgid::, for how the set-user-ID and set-group-ID bits ofparent directories are inherited.`install' is similar to `cp', but allows you to control theattributes of destination files. It is typically used in Makefiles tocopy programs into their destination directories. It refuses to copyfiles onto themselves.`install' never preserves extended attributes (xattr).The program accepts the following options. Also see *note Commonoptions::.`-b'`--backup[=METHOD]'*Note Backup options::. Make a backup of each file that wouldotherwise be overwritten or removed.`-c'Ignored; for compatibility with old Unix versions of `install'.`-D'Create any missing parent directories of DEST, then copy SOURCE toDEST. This option is ignored if a destination directory isspecified via `--target-directory=DIR'.`-d'`--directory'Create any missing parent directories, giving them the defaultattributes. Then create each given directory, setting their owner,group and mode as given on the command line or to the defaults.`-g GROUP'`--group=GROUP'Set the group ownership of installed files or directories toGROUP. The default is the process's current group. GROUP may beeither a group name or a numeric group ID.`-m MODE'`--mode=MODE'Set the file mode bits for the installed file or directory to MODE,which can be either an octal number, or a symbolic mode as in`chmod', with `a=' (no access allowed to anyone) as the point ofdeparture (*note File permissions::). The default mode is`u=rwx,go=rx,a-s'--read, write, and execute for the owner, readand execute for group and other, and with set-user-ID andset-group-ID disabled. This default is not quite the same as`755', since it disables instead of preserving set-user-ID andset-group-ID on directories. *Note Directory Setuid and Setgid::.`-o OWNER'`--owner=OWNER'If `install' has appropriate privileges (is run as root), set theownership of installed files or directories to OWNER. The defaultis `root'. OWNER may be either a user name or a numeric user ID.`--preserve-context'Preserve the SELinux security context of files and directories.Failure to preserve the context in all of the files or directorieswill result in an exit status of 1. If SELinux is disabled thenprint a warning and ignore the option.`-p'`--preserve-timestamps'Set the time of last access and the time of last modification ofeach installed file to match those of each corresponding originalfile. When a file is installed without this option, its lastaccess and last modification times are both set to the time ofinstallation. This option is useful if you want to use the lastmodification times of installed files to keep track of when theywere last built as opposed to when they were last installed.`-s'`--strip'Strip the symbol tables from installed binary executables.`--strip-program=PROGRAM'Program used to strip binaries.`-S SUFFIX'`--suffix=SUFFIX'Append SUFFIX to each backup file made with `-b'. *Note Backupoptions::.`-t DIRECTORY'`--target-directory=DIRECTORY'Specify the destination DIRECTORY. *Note Target directory::.`-T'`--no-target-directory'Do not treat the last operand specially when it is a directory or asymbolic link to a directory. *Note Target directory::.`-v'`--verbose'Print the name of each file before copying it.`-Z CONTEXT'`--context=CONTEXT'Set the default SELinux security context to be used for anycreated files and directories. If SELinux is disabled then printa warning and ignore the option.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: mv invocation, Next: rm invocation, Prev: install invocation, Up: Basic operations11.4 `mv': Move (rename) files==============================`mv' moves or renames files (or directories). Synopses:mv [OPTION]... [-T] SOURCE DESTmv [OPTION]... SOURCE... DIRECTORYmv [OPTION]... -t DIRECTORY SOURCE...* If two file names are given, `mv' moves the first file to thesecond.* If the `--target-directory' (`-t') option is given, or failingthat if the last file is a directory and the`--no-target-directory' (`-T') option is not given, `mv' moveseach SOURCE file to the specified directory, using the SOURCEs'names.`mv' can move any type of file from one file system to another.Prior to version `4.0' of the fileutils, `mv' could move only regularfiles between file systems. For example, now `mv' can move an entiredirectory hierarchy including special device files from one partitionto another. It first uses some of the same code that's used by `cp -a'to copy the requested directories and files, then (assuming the copysucceeded) it removes the originals. If the copy fails, then the partthat was copied to the destination partition is removed. If you wereto copy three directories from one partition to another and the copy ofthe first directory succeeded, but the second didn't, the first wouldbe left on the destination partition and the second and third would beleft on the original partition.`mv' always tries to copy extended attributes (xattr).If a destination file exists but is normally unwritable, standardinput is a terminal, and the `-f' or `--force' option is not given,`mv' prompts the user for whether to replace the file. (You might ownthe file, or have write permission on its directory.) If the responseis not affirmative, the file is skipped._Warning_: Avoid specifying a source name with a trailing slash,when it might be a symlink to a directory. Otherwise, `mv' may dosomething very surprising, since its behavior depends on the underlyingrename system call. On a system with a modern Linux-based kernel, itfails with `errno=ENOTDIR'. However, on other systems (at leastFreeBSD 6.1 and Solaris 10) it silently renames not the symlink butrather the directory referenced by the symlink. *Note Trailingslashes::.The program accepts the following options. Also see *note Commonoptions::.`-b'`--backup[=METHOD]'*Note Backup options::. Make a backup of each file that wouldotherwise be overwritten or removed.`-f'`--force'Do not prompt the user before removing a destination file. If youspecify more than one of the `-i', `-f', `-n' options, only thefinal one takes effect.`-i'`--interactive'Prompt whether to overwrite each existing destination file,regardless of its permissions. If the response is notaffirmative, the file is skipped. If you specify more than one ofthe `-i', `-f', `-n' options, only the final one takes effect.`-n'`--no-clobber'Do not overwrite an existing file. If you specify more than oneof the `-i', `-f', `-n' options, only the final one takes effect.This option is mutually exclusive with `-b' or `--backup' option.`-u'`--update'Do not move a non-directory that has an existing destination withthe same or newer modification time. If the move is across filesystem boundaries, the comparison is to the source time stamptruncated to the resolutions of the destination file system and ofthe system calls used to update time stamps; this avoids duplicatework if several `mv -u' commands are executed with the same sourceand destination.`-v'`--verbose'Print the name of each file before moving it.`--strip-trailing-slashes'Remove any trailing slashes from each SOURCE argument. *NoteTrailing slashes::.`-S SUFFIX'`--suffix=SUFFIX'Append SUFFIX to each backup file made with `-b'. *Note Backupoptions::.`-t DIRECTORY'`--target-directory=DIRECTORY'Specify the destination DIRECTORY. *Note Target directory::.`-T'`--no-target-directory'Do not treat the last operand specially when it is a directory or asymbolic link to a directory. *Note Target directory::.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: rm invocation, Next: shred invocation, Prev: mv invocation, Up: Basic operations11.5 `rm': Remove files or directories======================================`rm' removes each given FILE. By default, it does not removedirectories. Synopsis:rm [OPTION]... [FILE]...If the `-I' or `--interactive=once' option is given, and there aremore than three files or the `-r', `-R', or `--recursive' are given,then `rm' prompts the user for whether to proceed with the entireoperation. If the response is not affirmative, the entire command isaborted.Otherwise, if a file is unwritable, standard input is a terminal, andthe `-f' or `--force' option is not given, or the `-i' or`--interactive=always' option _is_ given, `rm' prompts the user forwhether to remove the file. If the response is not affirmative, thefile is skipped.Any attempt to remove a file whose last file name component is `.'or `..' is rejected without any prompting._Warning_: If you use `rm' to remove a file, it is usually possibleto recover the contents of that file. If you want more assurance thatthe contents are truly unrecoverable, consider using `shred'.The program accepts the following options. Also see *note Commonoptions::.`-f'`--force'Ignore nonexistent files and never prompt the user. Ignore anyprevious `--interactive' (`-i') option.`-i'Prompt whether to remove each file. If the response is notaffirmative, the file is skipped. Ignore any previous `--force'(`-f') option. Equivalent to `--interactive=always'.`-I'Prompt once whether to proceed with the command, if more than threefiles are named or if a recursive removal is requested. Ignore anyprevious `--force' (`-f') option. Equivalent to`--interactive=once'.`--interactive [=WHEN]'Specify when to issue an interactive prompt. WHEN may be omitted,or one of:* never - Do not prompt at all.* once - Prompt once if more than three files are named or if arecursive removal is requested. Equivalent to `-I'.* always - Prompt for every file being removed. Equivalent to`-i'.`--interactive' with no WHEN is equivalent to`--interactive=always'.`--one-file-system'When removing a hierarchy recursively, skip any directory that ison a file system different from that of the corresponding commandline argument.This option is useful when removing a build "chroot" hierarchy,which normally contains no valuable data. However, it is notuncommon to bind-mount `/home' into such a hierarchy, to make iteasier to use one's start-up file. The catch is that it's easy toforget to unmount `/home'. Then, when you use `rm -rf' to removeyour normally throw-away chroot, that command will removeeverything under `/home', too. Use the `--one-file-system'option, and it will warn about and skip directories on other filesystems. Of course, this will not save your `/home' if it and yourchroot happen to be on the same file system.`--preserve-root'Fail upon any attempt to remove the root directory, `/', when usedwith the `--recursive' option. This is the default behavior.*Note Treating / specially::.`--no-preserve-root'Do not treat `/' specially when removing recursively. This optionis not recommended unless you really want to remove all the fileson your computer. *Note Treating / specially::.`-r'`-R'`--recursive'Remove the listed directories and their contents recursively.`-v'`--verbose'Print the name of each file before removing it.One common question is how to remove files whose names begin with a`-'. GNU `rm', like every program that uses the `getopt' function toparse its arguments, lets you use the `--' option to indicate that allfollowing arguments are non-options. To remove a file called `-f' inthe current directory, you could type either:rm -- -for:rm ./-fThe Unix `rm' program's use of a single `-' for this purposepredates the development of the getopt standard syntax.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: shred invocation, Prev: rm invocation, Up: Basic operations11.6 `shred': Remove files more securely========================================`shred' overwrites devices or files, to help prevent even veryexpensive hardware from recovering the data.Ordinarily when you remove a file (*note rm invocation::), the datais not actually destroyed. Only the index listing where the file isstored is destroyed, and the storage is made available for reuse.There are undelete utilities that will attempt to reconstruct the indexand can bring the file back if the parts were not reused.On a busy system with a nearly-full drive, space can get reused in afew seconds. But there is no way to know for sure. If you havesensitive data, you may want to be sure that recovery is not possibleby actually overwriting the file with non-sensitive data.However, even after doing that, it is possible to take the disk backto a laboratory and use a lot of sensitive (and expensive) equipment tolook for the faint "echoes" of the original data underneath theoverwritten data. If the data has only been overwritten once, it's noteven that hard.The best way to remove something irretrievably is to destroy themedia it's on with acid, melt it down, or the like. For cheapremovable media like floppy disks, this is the preferred method.However, hard drives are expensive and hard to melt, so the `shred'utility tries to achieve a similar effect non-destructively.This uses many overwrite passes, with the data patterns chosen tomaximize the damage they do to the old data. While this will work onfloppies, the patterns are designed for best effect on hard drives.For more details, see the source code and Peter Gutmann's paper `SecureDeletion of Data from Magnetic and Solid-State Memory'(http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html), from theproceedings of the Sixth USENIX Security Symposium (San Jose,California, July 22-25, 1996).*Please note* that `shred' relies on a very important assumption:that the file system overwrites data in place. This is the traditionalway to do things, but many modern file system designs do not satisfythis assumption. Exceptions include:* Log-structured or journaled file systems, such as those suppliedwith AIX and Solaris, and JFS, ReiserFS, XFS, Ext3 (in`data=journal' mode), BFS, NTFS, etc. when they are configured tojournal _data_.* File systems that write redundant data and carry on even if somewrites fail, such as RAID-based file systems.* File systems that make snapshots, such as Network Appliance's NFSserver.* File systems that cache in temporary locations, such as NFSversion 3 clients.* Compressed file systems.In the particular case of ext3 file systems, the above disclaimerapplies (and `shred' is thus of limited effectiveness) only in`data=journal' mode, which journals file data in addition to justmetadata. In both the `data=ordered' (default) and `data=writeback'modes, `shred' works as usual. Ext3 journaling modes can be changed byadding the `data=something' option to the mount options for aparticular file system in the `/etc/fstab' file, as documented in themount man page (man mount).If you are not sure how your file system operates, then you shouldassume that it does not overwrite data in place, which means that shredcannot reliably operate on regular files in your file system.Generally speaking, it is more reliable to shred a device than afile, since this bypasses the problem of file system design mentionedabove. However, even shredding devices is not always completelyreliable. For example, most disks map out bad sectors invisibly to theapplication; if the bad sectors contain sensitive data, `shred' won'tbe able to destroy it.`shred' makes no attempt to detect or report this problem, just asit makes no attempt to do anything about backups. However, since it ismore reliable to shred devices than files, `shred' by default does nottruncate or remove the output file. This default is more suitable fordevices, which typically cannot be truncated and should not be removed.Finally, consider the risk of backups and mirrors. File systembackups and remote mirrors may contain copies of the file that cannotbe removed, and that will allow a shredded file to be recovered later.So if you keep any data you may later want to destroy using `shred', besure that it is not backed up or mirrored.shred [OPTION]... FILE[...]The program accepts the following options. Also see *note Commonoptions::.`-f'`--force'Override file permissions if necessary to allow overwriting.`-NUMBER'`-n NUMBER'`--iterations=NUMBER'By default, `shred' uses 3 passes of overwrite. You can reducethis to save time, or increase it if you think it's appropriate.After 25 passes all of the internal overwrite patterns will havebeen used at least once.`--random-source=FILE'Use FILE as a source of random data used to overwrite and tochoose pass ordering. *Note Random sources::.`-s BYTES'`--size=BYTES'Shred the first BYTES bytes of the file. The default is to shredthe whole file. BYTES can be followed by a size specification like`K', `M', or `G' to specify a multiple. *Note Block size::.`-u'`--remove'After shredding a file, truncate it (if possible) and then removeit. If a file has multiple links, only the named links will beremoved.`-v'`--verbose'Display to standard error all status updates as sterilizationproceeds.`-x'`--exact'By default, `shred' rounds the size of a regular file up to thenext multiple of the file system block size to fully erase thelast block of the file. Use `--exact' to suppress that behavior.Thus, by default if you shred a 10-byte regular file on a systemwith 512-byte blocks, the resulting file will be 512 bytes long.With this option, shred does not increase the apparent size of thefile.`-z'`--zero'Normally, the last pass that `shred' writes is made up of randomdata. If this would be conspicuous on your hard drive (forexample, because it looks like encrypted data), or you just thinkit's tidier, the `--zero' option adds an additional overwrite passwith all zero bits. This is in addition to the number of passesspecified by the `--iterations' option.You might use the following command to erase all trace of the filesystem you'd created on the floppy disk in your first drive. Thatcommand takes about 20 minutes to erase a "1.44MB" (actually 1440 KiB)floppy.shred --verbose /dev/fd0Similarly, to erase all data on a selected partition of your harddisk, you could give a command like this:shred --verbose /dev/sda5A FILE of `-' denotes standard output. The intended use of this isto shred a removed temporary file. For example:i=`tempfile -m 0600`exec 3<>"$i"rm -- "$i"echo "Hello, world" >&3shred - >&3exec 3>-However, the command `shred - >file' does not shred the contents ofFILE, since the shell truncates FILE before invoking `shred'. Use thecommand `shred file' or (if using a Bourne-compatible shell) thecommand `shred - 1<>file' instead.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Special file types, Next: Changing file attributes, Prev: Basic operations, Up: Top12 Special file types*********************This chapter describes commands which create special types of files (and`rmdir', which removes directories, one special file type).Although Unix-like operating systems have markedly fewer special filetypes than others, not _everything_ can be treated only as theundifferentiated byte stream of "normal files". For example, when afile is created or removed, the system must record this information,which it does in a "directory"--a special type of file. Although youcan read directories as normal files, if you're curious, in order forthe system to do its job it must impose a structure, a certain order,on the bytes of the file. Thus it is a "special" type of file.Besides directories, other special file types include named pipes(FIFOs), symbolic links, sockets, and so-called "special files".* Menu:* link invocation:: Make a hard link via the link syscall* ln invocation:: Make links between files.* mkdir invocation:: Make directories.* mkfifo invocation:: Make FIFOs (named pipes).* mknod invocation:: Make block or character special files.* readlink invocation:: Print the referent of a symbolic link.* rmdir invocation:: Remove empty directories.* unlink invocation:: Remove files via the unlink syscallFile: coreutils.info, Node: link invocation, Next: ln invocation, Up: Special file types12.1 `link': Make a hard link via the link syscall==================================================`link' creates a single hard link at a time. It is a minimalistinterface to the system-provided `link' function. *Note Hard Links:(libc)Hard Links. It avoids the bells and whistles of the morecommonly-used `ln' command (*note ln invocation::). Synopsis:link FILENAME LINKNAMEFILENAME must specify an existing file, and LINKNAME must specify anonexistent entry in an existing directory. `link' simply calls `link(FILENAME, LINKNAME)' to create the link.On a GNU system, this command acts like `ln --directory--no-target-directory FILENAME LINKNAME'. However, the `--directory'and `--no-target-directory' options are not specified by POSIX, and the`link' command is more portable in practice.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: ln invocation, Next: mkdir invocation, Prev: link invocation, Up: Special file types12.2 `ln': Make links between files===================================`ln' makes links between files. By default, it makes hard links; withthe `-s' option, it makes symbolic (or "soft") links. Synopses:ln [OPTION]... [-T] TARGET LINKNAMEln [OPTION]... TARGETln [OPTION]... TARGET... DIRECTORYln [OPTION]... -t DIRECTORY TARGET...* If two file names are given, `ln' creates a link to the first filefrom the second.* If one TARGET is given, `ln' creates a link to that file in thecurrent directory.* If the `--target-directory' (`-t') option is given, or failingthat if the last file is a directory and the`--no-target-directory' (`-T') option is not given, `ln' creates alink to each TARGET file in the specified directory, using theTARGETs' names.Normally `ln' does not remove existing files. Use the `--force'(`-f') option to remove them unconditionally, the `--interactive'(`-i') option to remove them conditionally, and the `--backup' (`-b')option to rename them.A "hard link" is another name for an existing file; the link and theoriginal are indistinguishable. Technically speaking, they share thesame inode, and the inode contains all the information about afile--indeed, it is not incorrect to say that the inode _is_ the file.On all existing implementations, you cannot make a hard link to adirectory, and hard links cannot cross file system boundaries. (Theserestrictions are not mandated by POSIX, however.)"Symbolic links" ("symlinks" for short), on the other hand, are aspecial file type (which not all kernels support: System V release 3(and older) systems lack symlinks) in which the link file actuallyrefers to a different file, by name. When most operations (opening,reading, writing, and so on) are passed the symbolic link file, thekernel automatically "dereferences" the link and operates on the targetof the link. But some operations (e.g., removing) work on the linkfile itself, rather than on its target. The owner, group, and mode ofa symlink are not significant to file access performed through thelink. *Note Symbolic Links: (libc)Symbolic Links.Symbolic links can contain arbitrary strings; a "dangling symlink"occurs when the string in the symlink does not resolve to a file.There are no restrictions against creating dangling symbolic links.There are trade-offs to using absolute or relative symlinks. Anabsolute symlink always points to the same file, even if the directorycontaining the link is moved. However, if the symlink is visible frommore than one machine (such as on a networked file system), the filepointed to might not always be the same. A relative symbolic link isresolved in relation to the directory that contains the link, and isoften useful in referring to files on the same device without regardsto what name that device is mounted on when accessed via networkedmachines.When creating a relative symlink in a different location than thecurrent directory, the resolution of the symlink will be different thanthe resolution of the same string from the current directory.Therefore, many users prefer to first change directories to thelocation where the relative symlink will be created, so thattab-completion or other file resolution will find the same target aswhat will be placed in the symlink.The program accepts the following options. Also see *note Commonoptions::.`-b'`--backup[=METHOD]'*Note Backup options::. Make a backup of each file that wouldotherwise be overwritten or removed.`-d'`-F'`--directory'Allow users with appropriate privileges to attempt to make hardlinks to directories. However, note that this will probably faildue to system restrictions, even for the super-user.`-f'`--force'Remove existing destination files.`-i'`--interactive'Prompt whether to remove existing destination files.`-n'`--no-dereference'Do not treat the last operand specially when it is a symbolic linkto a directory. Instead, treat it as if it were a normal file.When the destination is an actual directory (not a symlink to one),there is no ambiguity. The link is created in that directory.But when the specified destination is a symlink to a directory,there are two ways to treat the user's request. `ln' can treatthe destination just as it would a normal directory and create thelink in it. On the other hand, the destination can be viewed as anon-directory--as the symlink itself. In that case, `ln' mustdelete or backup that symlink before creating the new link. Thedefault is to treat a destination that is a symlink to a directoryjust like a directory.This option is weaker than the `--no-target-directory' (`-T')option, so it has no effect if both options are given.`-s'`--symbolic'Make symbolic links instead of hard links. This option merelyproduces an error message on systems that do not support symboliclinks.`-S SUFFIX'`--suffix=SUFFIX'Append SUFFIX to each backup file made with `-b'. *Note Backupoptions::.`-t DIRECTORY'`--target-directory=DIRECTORY'Specify the destination DIRECTORY. *Note Target directory::.`-T'`--no-target-directory'Do not treat the last operand specially when it is a directory or asymbolic link to a directory. *Note Target directory::.`-v'`--verbose'Print the name of each file after linking it successfully.An exit status of zero indicates success, and a nonzero valueindicates failure.Examples:Bad Example:# Create link ../a pointing to a in that directory.# Not really useful because it points to itself.ln -s a ..Better Example:# Change to the target before creating symlinks to avoid being confused.cd ..ln -s adir/a .Bad Example:# Hard coded file names don't move well.ln -s $(pwd)/a /some/dir/Better Example:# Relative file names survive directory moves and also# work across networked file systems.ln -s afile anotherfileln -s ../adir/afile yetanotherfileFile: coreutils.info, Node: mkdir invocation, Next: mkfifo invocation, Prev: ln invocation, Up: Special file types12.3 `mkdir': Make directories==============================`mkdir' creates directories with the specified names. Synopsis:mkdir [OPTION]... NAME...`mkdir' creates each directory NAME in the order given. It reportsan error if NAME already exists, unless the `-p' option is given andNAME is a directory.The program accepts the following options. Also see *note Commonoptions::.`-m MODE'`--mode=MODE'Set the file permission bits of created directories to MODE, whichuses the same syntax as in `chmod' and uses `a=rwx' (read, writeand execute allowed for everyone) for the point of the departure.*Note File permissions::.Normally the directory has the desired file mode bits at themoment it is created. As a GNU extension, MODE may also mentionspecial mode bits, but in this case there may be a temporary windowduring which the directory exists but its special mode bits areincorrect. *Note Directory Setuid and Setgid::, for how theset-user-ID and set-group-ID bits of directories are inheritedunless overridden in this way.`-p'`--parents'Make any missing parent directories for each argument, settingtheir file permission bits to the umask modified by `u+wx'. Ignoreexisting parent directories, and do not change their filepermission bits.To set the file permission bits of any newly-created parentdirectories to a value that includes `u+wx', you can set the umaskbefore invoking `mkdir'. For example, if the shell command`(umask u=rwx,go=rx; mkdir -p P/Q)' creates the parent `P' it setsthe parent's permission bits to `u=rwx,go=rx'. To set a parent'sspecial mode bits as well, you can invoke `chmod' after `mkdir'.*Note Directory Setuid and Setgid::, for how the set-user-ID andset-group-ID bits of newly-created parent directories areinherited.`-v'`--verbose'Print a message for each created directory. This is most usefulwith `--parents'.`-Z CONTEXT'`--context=CONTEXT'Set the default SELinux security context to be used for createddirectories.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: mkfifo invocation, Next: mknod invocation, Prev: mkdir invocation, Up: Special file types12.4 `mkfifo': Make FIFOs (named pipes)=======================================`mkfifo' creates FIFOs (also called "named pipes") with the specifiednames. Synopsis:mkfifo [OPTION] NAME...A "FIFO" is a special file type that permits independent processesto communicate. One process opens the FIFO file for writing, andanother for reading, after which data can flow as with the usualanonymous pipe in shells or elsewhere.The program accepts the following option. Also see *note Commonoptions::.`-m MODE'`--mode=MODE'Set the mode of created FIFOs to MODE, which is symbolic as in`chmod' and uses `a=rw' (read and write allowed for everyone) forthe point of departure. MODE should specify only file permissionbits. *Note File permissions::.`-Z CONTEXT'`--context=CONTEXT'Set the default SELinux security context to be used for createdFIFOs.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: mknod invocation, Next: readlink invocation, Prev: mkfifo invocation, Up: Special file types12.5 `mknod': Make block or character special files===================================================`mknod' creates a FIFO, character special file, or block special filewith the specified name. Synopsis:mknod [OPTION]... NAME TYPE [MAJOR MINOR]Unlike the phrase "special file type" above, the term "special file"has a technical meaning on Unix: something that can generate or receivedata. Usually this corresponds to a physical piece of hardware, e.g.,a printer or a disk. (These files are typically created atsystem-configuration time.) The `mknod' command is what creates filesof this type. Such devices can be read either a character at a time ora "block" (many characters) at a time, hence we say there are "blockspecial" files and "character special" files.Due to shell aliases and built-in `mknod' command, using anunadorned `mknod' interactively or in a script may get you differentfunctionality than that described here. Invoke it via `env' (i.e.,`env mknod ...') to avoid interference from the shell.The arguments after NAME specify the type of file to make:`p'for a FIFO`b'for a block special file`c'for a character special fileWhen making a block or character special file, the major and minordevice numbers must be given after the file type. If a major or minordevice number begins with `0x' or `0X', it is interpreted ashexadecimal; otherwise, if it begins with `0', as octal; otherwise, asdecimal.The program accepts the following option. Also see *note Commonoptions::.`-m MODE'`--mode=MODE'Set the mode of created files to MODE, which is symbolic as in`chmod' and uses `a=rw' as the point of departure. MODE shouldspecify only file permission bits. *Note File permissions::.`-Z CONTEXT'`--context=CONTEXT'Set the default SELinux security context to be used for createdfiles.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: readlink invocation, Next: rmdir invocation, Prev: mknod invocation, Up: Special file types12.6 `readlink': Print the referent of a symbolic link======================================================`readlink' may work in one of two supported modes:`Readlink mode'`readlink' outputs the value of the given symbolic link. If`readlink' is invoked with an argument other than the name of asymbolic link, it produces no output and exits with a nonzero exitcode.`Canonicalize mode'`readlink' outputs the absolute name of the given file whichcontains no `.', `..' components nor any repeated separators (`/')or symbolic links.readlink [OPTION] FILEBy default, `readlink' operates in readlink mode.The program accepts the following options. Also see *note Commonoptions::.`-f'`--canonicalize'Activate canonicalize mode. If any component of the file nameexcept the last one is missing or unavailable, `readlink' producesno output and exits with a nonzero exit code.`-e'`--canonicalize-existing'Activate canonicalize mode. If any component is missing orunavailable, `readlink' produces no output and exits with anonzero exit code.`-m'`--canonicalize-missing'Activate canonicalize mode. If any component is missing orunavailable, `readlink' treats it as a directory.`-n'`--no-newline'Do not output the trailing newline.`-s'`-q'`--silent'`--quiet'Suppress most error messages.`-v'`--verbose'Report error messages.The `readlink' utility first appeared in OpenBSD 2.1.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: rmdir invocation, Next: unlink invocation, Prev: readlink invocation, Up: Special file types12.7 `rmdir': Remove empty directories======================================`rmdir' removes empty directories. Synopsis:rmdir [OPTION]... DIRECTORY...If any DIRECTORY argument does not refer to an existing emptydirectory, it is an error.The program accepts the following options. Also see *note Commonoptions::.`--ignore-fail-on-non-empty'Ignore each failure to remove a directory that is solely becausethe directory is non-empty.`-p'`--parents'Remove DIRECTORY, then try to remove each component of DIRECTORY.So, for example, `rmdir -p a/b/c' is similar to `rmdir a/b/c a/ba'. As such, it fails if any of those directories turns out notto be empty. Use the `--ignore-fail-on-non-empty' option to makeit so such a failure does not evoke a diagnostic and does notcause `rmdir' to exit unsuccessfully.`-v'`--verbose'Give a diagnostic for each successful removal. DIRECTORY isremoved.*Note rm invocation::, for how to remove non-empty directories(recursively).An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: unlink invocation, Prev: rmdir invocation, Up: Special file types12.8 `unlink': Remove files via the unlink syscall==================================================`unlink' deletes a single specified file name. It is a minimalistinterface to the system-provided `unlink' function. *Note DeletingFiles: (libc)Deleting Files. Synopsis: It avoids the bells andwhistles of the more commonly-used `rm' command (*note rm invocation::).unlink FILENAMEOn some systems `unlink' can be used to delete the name of adirectory. On others, it can be used that way only by a privilegeduser. In the GNU system `unlink' can never delete the name of adirectory.The `unlink' command honors the `--help' and `--version' options.To remove a file whose name begins with `-', prefix the name with `./',e.g., `unlink ./--help'.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Changing file attributes, Next: Disk usage, Prev: Special file types, Up: Top13 Changing file attributes***************************A file is not merely its contents, a name, and a file type (*noteSpecial file types::). A file also has an owner (a user ID), a group(a group ID), permissions (what the owner can do with the file, whatpeople in the group can do, and what everyone else can do), varioustimestamps, and other information. Collectively, we call these a file's"attributes".These commands change file attributes.* Menu:* chgrp invocation:: Change file groups.* chmod invocation:: Change access permissions.* chown invocation:: Change file owners and groups.* touch invocation:: Change file timestamps.File: coreutils.info, Node: chown invocation, Next: touch invocation, Prev: chmod invocation, Up: Changing file attributes13.1 `chown': Change file owner and group=========================================`chown' changes the user and/or group ownership of each given FILE toNEW-OWNER or to the user and group of an existing reference file.Synopsis:chown [OPTION]... {NEW-OWNER | --reference=REF_FILE} FILE...If used, NEW-OWNER specifies the new owner and/or group as follows(with no embedded white space):[OWNER] [ : [GROUP] ]Specifically:OWNERIf only an OWNER (a user name or numeric user ID) is given, thatuser is made the owner of each given file, and the files' group isnot changed.OWNER`:'GROUPIf the OWNER is followed by a colon and a GROUP (a group name ornumeric group ID), with no spaces between them, the groupownership of the files is changed as well (to GROUP).OWNER`:'If a colon but no group name follows OWNER, that user is made theowner of the files and the group of the files is changed toOWNER's login group.`:'GROUPIf the colon and following GROUP are given, but the owner isomitted, only the group of the files is changed; in this case,`chown' performs the same function as `chgrp'.`:'If only a colon is given, or if NEW-OWNER is empty, neither theowner nor the group is changed.If OWNER or GROUP is intended to represent a numeric user or groupID, then you may specify it with a leading `+'. *Note Disambiguatingnames and IDs::.Some older scripts may still use `.' in place of the `:' separator.POSIX 1003.1-2001 (*note Standards conformance::) does not requiresupport for that, but for backward compatibility GNU `chown' supports`.' so long as no ambiguity results. New scripts should avoid the useof `.' because it is not portable, and because it has undesirableresults if the entire OWNER`.'GROUP happens to identify a user whosename contains `.'.The `chown' command sometimes clears the set-user-ID or set-group-IDpermission bits. This behavior depends on the policy and functionalityof the underlying `chown' system call, which may make system-dependentfile mode modifications outside the control of the `chown' command.For example, the `chown' command might not affect those bits wheninvoked by a user with appropriate privileges, or when the bits signifysome function other than executable permission (e.g., mandatorylocking). When in doubt, check the underlying system behavior.The program accepts the following options. Also see *note Commonoptions::.`-c'`--changes'Verbosely describe the action for each FILE whose ownershipactually changes.`-f'`--silent'`--quiet'Do not print error messages about files whose ownership cannot bechanged.`--from=OLD-OWNER'Change a FILE's ownership only if it has current attributesspecified by OLD-OWNER. OLD-OWNER has the same form as NEW-OWNERdescribed above. This option is useful primarily from a securitystandpoint in that it narrows considerably the window of potentialabuse. For example, to reflect a user ID numbering change for oneuser's files without an option like this, `root' might runfind / -owner OLDUSER -print0 | xargs -0 chown -h NEWUSERBut that is dangerous because the interval between when the `find'tests the existing file's owner and when the `chown' is actuallyrun may be quite large. One way to narrow the gap would be toinvoke chown for each file as it is found:find / -owner OLDUSER -exec chown -h NEWUSER {} \;But that is very slow if there are many affected files. With thisoption, it is safer (the gap is narrower still) though still notperfect:chown -h -R --from=OLDUSER NEWUSER /`--dereference'Do not act on symbolic links themselves but rather on what theypoint to. This is the default.`-h'`--no-dereference'Act on symbolic links themselves instead of what they point to.This mode relies on the `lchown' system call. On systems that donot provide the `lchown' system call, `chown' fails when a filespecified on the command line is a symbolic link. By default, nodiagnostic is issued for symbolic links encountered during arecursive traversal, but see `--verbose'.`--preserve-root'Fail upon any attempt to recursively change the root directory,`/'. Without `--recursive', this option has no effect. *NoteTreating / specially::.`--no-preserve-root'Cancel the effect of any preceding `--preserve-root' option.*Note Treating / specially::.`--reference=REF_FILE'Change the user and group of each FILE to be the same as those ofREF_FILE. If REF_FILE is a symbolic link, do not use the user andgroup of the symbolic link, but rather those of the file it refersto.`-v'`--verbose'Output a diagnostic for every file processed. If a symbolic linkis encountered during a recursive traversal on a system withoutthe `lchown' system call, and `--no-dereference' is in effect,then issue a diagnostic saying neither the symbolic link nor itsreferent is being changed.`-R'`--recursive'Recursively change ownership of directories and their contents.`-H'If `--recursive' (`-R') is specified and a command line argumentis a symbolic link to a directory, traverse it. *Note Traversingsymlinks::.`-L'In a recursive traversal, traverse every symbolic link to adirectory that is encountered. *Note Traversing symlinks::.`-P'Do not traverse any symbolic links. This is the default if noneof `-H', `-L', or `-P' is specified. *Note Traversing symlinks::.An exit status of zero indicates success, and a nonzero valueindicates failure.Examples:# Change the owner of /u to "root".chown root /u# Likewise, but also change its group to "staff".chown root:staff /u# Change the owner of /u and subfiles to "root".chown -hR root /uFile: coreutils.info, Node: chgrp invocation, Next: chmod invocation, Up: Changing file attributes13.2 `chgrp': Change group ownership====================================`chgrp' changes the group ownership of each given FILE to GROUP (whichcan be either a group name or a numeric group ID) or to the group of anexisting reference file. Synopsis:chgrp [OPTION]... {GROUP | --reference=REF_FILE} FILE...If GROUP is intended to represent a numeric group ID, then you mayspecify it with a leading `+'. *Note Disambiguating names and IDs::.The program accepts the following options. Also see *note Commonoptions::.`-c'`--changes'Verbosely describe the action for each FILE whose group actuallychanges.`-f'`--silent'`--quiet'Do not print error messages about files whose group cannot bechanged.`--dereference'Do not act on symbolic links themselves but rather on what theypoint to. This is the default.`-h'`--no-dereference'Act on symbolic links themselves instead of what they point to.This mode relies on the `lchown' system call. On systems that donot provide the `lchown' system call, `chgrp' fails when a filespecified on the command line is a symbolic link. By default, nodiagnostic is issued for symbolic links encountered during arecursive traversal, but see `--verbose'.`--preserve-root'Fail upon any attempt to recursively change the root directory,`/'. Without `--recursive', this option has no effect. *NoteTreating / specially::.`--no-preserve-root'Cancel the effect of any preceding `--preserve-root' option.*Note Treating / specially::.`--reference=REF_FILE'Change the group of each FILE to be the same as that of REF_FILE.If REF_FILE is a symbolic link, do not use the group of thesymbolic link, but rather that of the file it refers to.`-v'`--verbose'Output a diagnostic for every file processed. If a symbolic linkis encountered during a recursive traversal on a system withoutthe `lchown' system call, and `--no-dereference' is in effect,then issue a diagnostic saying neither the symbolic link nor itsreferent is being changed.`-R'`--recursive'Recursively change the group ownership of directories and theircontents.`-H'If `--recursive' (`-R') is specified and a command line argumentis a symbolic link to a directory, traverse it. *Note Traversingsymlinks::.`-L'In a recursive traversal, traverse every symbolic link to adirectory that is encountered. *Note Traversing symlinks::.`-P'Do not traverse any symbolic links. This is the default if noneof `-H', `-L', or `-P' is specified. *Note Traversing symlinks::.An exit status of zero indicates success, and a nonzero valueindicates failure.Examples:# Change the group of /u to "staff".chgrp staff /u# Change the group of /u and subfiles to "staff".chgrp -hR staff /uFile: coreutils.info, Node: chmod invocation, Next: chown invocation, Prev: chgrp invocation, Up: Changing file attributes13.3 `chmod': Change access permissions=======================================`chmod' changes the access permissions of the named files. Synopsis:chmod [OPTION]... {MODE | --reference=REF_FILE} FILE...`chmod' never changes the permissions of symbolic links, since the`chmod' system call cannot change their permissions. This is not aproblem since the permissions of symbolic links are never used.However, for each symbolic link listed on the command line, `chmod'changes the permissions of the pointed-to file. In contrast, `chmod'ignores symbolic links encountered during recursive directorytraversals.A successful use of `chmod' clears the set-group-ID bit of a regularfile if the file's group ID does not match the user's effective groupID or one of the user's supplementary group IDs, unless the user hasappropriate privileges. Additional restrictions may cause theset-user-ID and set-group-ID bits of MODE or REF_FILE to be ignored.This behavior depends on the policy and functionality of the underlying`chmod' system call. When in doubt, check the underlying systembehavior.If used, MODE specifies the new file mode bits. For details, seethe section on *note File permissions::. If you really want MODE tohave a leading `-', you should use `--' first, e.g., `chmod -- -wfile'. Typically, though, `chmod a-w file' is preferable, and `chmod -wfile' (without the `--') complains if it behaves differently from what`chmod a-w file' would do.The program accepts the following options. Also see *note Commonoptions::.`-c'`--changes'Verbosely describe the action for each FILE whose permissionsactually changes.`-f'`--silent'`--quiet'Do not print error messages about files whose permissions cannot bechanged.`--preserve-root'Fail upon any attempt to recursively change the root directory,`/'. Without `--recursive', this option has no effect. *NoteTreating / specially::.`--no-preserve-root'Cancel the effect of any preceding `--preserve-root' option.*Note Treating / specially::.`-v'`--verbose'Verbosely describe the action or non-action taken for every FILE.`--reference=REF_FILE'Change the mode of each FILE to be the same as that of REF_FILE.*Note File permissions::. If REF_FILE is a symbolic link, do notuse the mode of the symbolic link, but rather that of the file itrefers to.`-R'`--recursive'Recursively change permissions of directories and their contents.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: touch invocation, Prev: chown invocation, Up: Changing file attributes13.4 `touch': Change file timestamps====================================`touch' changes the access and/or modification times of the specifiedfiles. Synopsis:touch [OPTION]... FILE...Any FILE argument that does not exist is created empty.A FILE argument string of `-' is handled specially and causes`touch' to change the times of the file associated with standard output.If changing both the access and modification times to the currenttime, `touch' can change the timestamps for files that the user runningit does not own but has write permission for. Otherwise, the user mustown the files.Although `touch' provides options for changing two of the times--thetimes of last access and modification--of a file, there is actually athird one as well: the inode change time. This is often referred to asa file's `ctime'. The inode change time represents the time when thefile's meta-information last changed. One common example of this iswhen the permissions of a file change. Changing the permissionsdoesn't access the file, so the atime doesn't change, nor does itmodify the file, so the mtime doesn't change. Yet, something about thefile itself has changed, and this must be noted somewhere. This is thejob of the ctime field. This is necessary, so that, for example, abackup program can make a fresh copy of the file, including the newpermissions value. Another operation that modifies a file's ctimewithout affecting the others is renaming. In any case, it is notpossible, in normal operations, for a user to change the ctime field toa user-specified value.Time stamps assume the time zone rules specified by the `TZ'environment variable, or by the system default rules if `TZ' is notset. *Note Specifying the Time Zone with `TZ': (libc)TZ Variable. Youcan avoid ambiguities during daylight saving transitions by using UTCtime stamps.The program accepts the following options. Also see *note Commonoptions::.`-a'`--time=atime'`--time=access'`--time=use'Change the access time only.`-c'`--no-create'Do not create files that do not exist.`-d'`--date=TIME'Use TIME instead of the current time. It can contain month names,time zones, `am' and `pm', `yesterday', etc. For example,`--date="2004-02-27 14:19:13.489392193 +0530"' specifies theinstant of time that is 489,392,193 nanoseconds after February 27,2004 at 2:19:13 PM in a time zone that is 5 hours and 30 minuteseast of UTC. *Note Date input formats::. File systems that donot support high-resolution time stamps silently ignore any excessprecision here.`-f'Ignored; for compatibility with BSD versions of `touch'.`-m'`--time=mtime'`--time=modify'Change the modification time only.`-r FILE'`--reference=FILE'Use the times of the reference FILE instead of the current time.If this option is combined with the `--date=TIME' (`-d TIME')option, the reference FILE's time is the origin for any relativeTIMEs given, but is otherwise ignored. For example, `-r foo -d'-5 seconds'' specifies a time stamp equal to five seconds beforethe corresponding time stamp for `foo'.`-t [[CC]YY]MMDDHHMM[.SS]'Use the argument (optional four-digit or two-digit years, months,days, hours, minutes, optional seconds) instead of the currenttime. If the year is specified with only two digits, then CC is20 for years in the range 0 ... 68, and 19 for years in 69 ... 99.If no digits of the year are specified, the argument isinterpreted as a date in the current year.On older systems, `touch' supports an obsolete syntax, as follows.If no timestamp is given with any of the `-d', `-r', or `-t' options,and if there are two or more FILEs and the first FILE is of the form`MMDDHHMM[YY]' and this would be a valid argument to the `-t' option(if the YY, if any, were moved to the front), and if the representedyear is in the range 1969-1999, that argument is interpreted as the timefor the other files instead of as a file name. This obsolete behaviorcan be enabled or disabled with the `_POSIX2_VERSION' environmentvariable (*note Standards conformance::), but portable scripts shouldavoid commands whose behavior depends on this variable. For example,use `touch ./12312359 main.c' or `touch -t 12312359 main.c' rather thanthe ambiguous `touch 12312359 main.c'.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Disk usage, Next: Printing text, Prev: Changing file attributes, Up: Top14 Disk usage*************No disk can hold an infinite amount of data. These commands report howmuch disk storage is in use or available, report other file and filestatus information, and write buffers to disk.* Menu:* df invocation:: Report file system disk space usage.* du invocation:: Estimate file space usage.* stat invocation:: Report file or file system status.* sync invocation:: Synchronize memory and disk.* truncate invocation:: Shrink or extend the size of a file.File: coreutils.info, Node: df invocation, Next: du invocation, Up: Disk usage14.1 `df': Report file system disk space usage==============================================`df' reports the amount of disk space used and available on filesystems. Synopsis:df [OPTION]... [FILE]...With no arguments, `df' reports the space used and available on allcurrently mounted file systems (of all types). Otherwise, `df' reportson the file system containing each argument FILE.Normally the disk space is printed in units of 1024 bytes, but thiscan be overridden (*note Block size::). Non-integer quantities arerounded up to the next higher unit.If an argument FILE is a disk device file containing a mounted filesystem, `df' shows the space available on that file system rather thanon the file system containing the device node (i.e., the root filesystem). GNU `df' does not attempt to determine the disk usage onunmounted file systems, because on most kinds of systems doing sorequires extremely nonportable intimate knowledge of file systemstructures.The program accepts the following options. Also see *note Commonoptions::.`-a'`--all'Include in the listing dummy file systems, which are omitted bydefault. Such file systems are typically special-purposepseudo-file-systems, such as automounter entries.`-B SIZE'`--block-size=SIZE'Scale sizes by SIZE before printing them (*note Block size::).For example, `-BG' prints sizes in units of 1,073,741,824 bytes.`--total'Print a grand total of all arguments after all arguments have beenprocessed. This can be used to find out the total disk size, usageand available space of all listed devices.`-h'`--human-readable'Append a size letter to each size, such as `M' for mebibytes.Powers of 1024 are used, not 1000; `M' stands for 1,048,576 bytes.This option is equivalent to `--block-size=human-readable'. Usethe `--si' option if you prefer powers of 1000.`-H'Equivalent to `--si'.`-i'`--inodes'List inode usage information instead of block usage. An inode(short for index node) contains information about a file such asits owner, permissions, timestamps, and location on the disk.`-k'Print sizes in 1024-byte blocks, overriding the default block size(*note Block size::). This option is equivalent to`--block-size=1K'.`-l'`--local'Limit the listing to local file systems. By default, remote filesystems are also listed.`--no-sync'Do not invoke the `sync' system call before getting any usage data.This may make `df' run significantly faster on systems with manydisks, but on some systems (notably SunOS) the results may beslightly out of date. This is the default.`-P'`--portability'Use the POSIX output format. This is like the default formatexcept for the following:1. The information about each file system is always printed onexactly one line; a mount device is never put on a line byitself. This means that if the mount device name is morethan 20 characters long (e.g., for some network mounts), thecolumns are misaligned.2. The labels in the header output line are changed to conformto POSIX.3. The default block size and output format are unaffected by the`DF_BLOCK_SIZE', `BLOCK_SIZE' and `BLOCKSIZE' environmentvariables. However, the default block size is still affectedby `POSIXLY_CORRECT': it is 512 if `POSIXLY_CORRECT' is set,1024 otherwise. *Note Block size::.`--si'Append an SI-style abbreviation to each size, such as `M' formegabytes. Powers of 1000 are used, not 1024; `M' stands for1,000,000 bytes. This option is equivalent to `--block-size=si'.Use the `-h' or `--human-readable' option if you prefer powers of1024.`--sync'Invoke the `sync' system call before getting any usage data. Onsome systems (notably SunOS), doing this yields more up to dateresults, but in general this option makes `df' much slower,especially when there are many or very busy file systems.`-t FSTYPE'`--type=FSTYPE'Limit the listing to file systems of type FSTYPE. Multiple filesystem types can be specified by giving multiple `-t' options. Bydefault, nothing is omitted.`-T'`--print-type'Print each file system's type. The types printed here are thesame ones you can include or exclude with `-t' and `-x'. Theparticular types printed are whatever is supported by the system.Here are some of the common names (this list is certainly notexhaustive):`nfs'An NFS file system, i.e., one mounted over a network fromanother machine. This is the one type name which seems to beused uniformly by all systems.`4.2, ufs, efs...'A file system on a locally-mounted hard disk. (The systemmight even support more than one type here; Linux does.)`hsfs, cdfs'A file system on a CD-ROM drive. HP-UX uses `cdfs', mostother systems use `hsfs' (`hs' for "High Sierra").`pcfs'An MS-DOS file system, usually on a diskette.`-x FSTYPE'`--exclude-type=FSTYPE'Limit the listing to file systems not of type FSTYPE. Multiplefile system types can be eliminated by giving multiple `-x'options. By default, no file system types are omitted.`-v'Ignored; for compatibility with System V versions of `df'.An exit status of zero indicates success, and a nonzero valueindicates failure. Failure includes the case where no output isgenerated, so you can inspect the exit status of a command like `df -text3 -t reiserfs DIR' to test whether DIR is on a file system of type`ext3' or `reiserfs'.File: coreutils.info, Node: du invocation, Next: stat invocation, Prev: df invocation, Up: Disk usage14.2 `du': Estimate file space usage====================================`du' reports the amount of disk space used by the specified files andfor each subdirectory (of directory arguments). Synopsis:du [OPTION]... [FILE]...With no arguments, `du' reports the disk space for the currentdirectory. Normally the disk space is printed in units of 1024 bytes,but this can be overridden (*note Block size::). Non-integerquantities are rounded up to the next higher unit.If two or more hard links point to the same file, only one of thehard links is counted. The FILE argument order affects which links arecounted, and changing the argument order may change the numbers that`du' outputs.The program accepts the following options. Also see *note Commonoptions::.`-a'`--all'Show counts for all files, not just directories.`--apparent-size'Print apparent sizes, rather than disk usage. The apparent sizeof a file is the number of bytes reported by `wc -c' on regularfiles, or more generally, `ls -l --block-size=1' or `stat--format=%s'. For example, a file containing the word `zoo' withno newline would, of course, have an apparent size of 3. Such asmall file may require anywhere from 0 to 16 KiB or more of diskspace, depending on the type and configuration of the file systemon which the file resides. However, a sparse file created withthis command:dd bs=1 seek=2GiB if=/dev/null of=bighas an apparent size of 2 GiB, yet on most modern systems, itactually uses almost no disk space.`-b'`--bytes'Equivalent to `--apparent-size --block-size=1'.`-B SIZE'`--block-size=SIZE'Scale sizes by SIZE before printing them (*note Block size::).For example, `-BG' prints sizes in units of 1,073,741,824 bytes.`-c'`--total'Print a grand total of all arguments after all arguments have beenprocessed. This can be used to find out the total disk usage of agiven set of files or directories.`-D'`--dereference-args'Dereference symbolic links that are command line arguments. Doesnot affect other symbolic links. This is helpful for finding outthe disk usage of directories, such as `/usr/tmp', which are oftensymbolic links.`--files0-from=FILE'Disallow processing files named on the command line, and insteadprocess those named in file FILE; each name being terminated by azero byte (ASCII NUL). This is useful when the list of file namesis so long that it may exceed a command line length limitation.In such cases, running `du' via `xargs' is undesirable because itsplits the list into pieces and makes `du' print with the`--total' (`-c') option for each sublist rather than for theentire list. One way to produce a list of ASCII NUL terminatedfile names is with GNU `find', using its `-print0' predicate. IfFILE is `-' then the ASCII NUL terminated file names are read fromstandard input.`-h'`--human-readable'Append a size letter to each size, such as `M' for mebibytes.Powers of 1024 are used, not 1000; `M' stands for 1,048,576 bytes.This option is equivalent to `--block-size=human-readable'. Usethe `--si' option if you prefer powers of 1000.`-H'Equivalent to `--dereference-args' (`-D').`-k'Print sizes in 1024-byte blocks, overriding the default block size(*note Block size::). This option is equivalent to`--block-size=1K'.`-l'`--count-links'Count the size of all files, even if they have appeared already(as a hard link).`-L'`--dereference'Dereference symbolic links (show the disk space used by the fileor directory that the link points to instead of the space used bythe link).`-m'Print sizes in 1,048,576-byte blocks, overriding the default blocksize (*note Block size::). This option is equivalent to`--block-size=1M'.`-P'`--no-dereference'For each symbolic links encountered by `du', consider the diskspace used by the symbolic link.`--max-depth=DEPTH'Show the total for each directory (and file if -all) that is atmost MAX_DEPTH levels down from the root of the hierarchy. Theroot is at level 0, so `du --max-depth=0' is equivalent to `du -s'.`-0'`--null'Output a zero byte (ASCII NUL) at the end of each line, ratherthan a newline. This option enables other programs to parse theoutput of `du' even when that output would contain file names withembedded newlines.`--si'Append an SI-style abbreviation to each size, such as `M' formegabytes. Powers of 1000 are used, not 1024; `M' stands for1,000,000 bytes. This option is equivalent to `--block-size=si'.Use the `-h' or `--human-readable' option if you prefer powers of1024.`-s'`--summarize'Display only a total for each argument.`-S'`--separate-dirs'Normally, in the output of `du' (when not using `--summarize'),the size listed next to a directory name, D, represents the sum ofsizes of all entries beneath D as well as the size of D itself.With `--separate-dirs', the size reported for a directory name, D,is merely the `stat.st_size'-derived size of the directory entry,D.`--time'Show time of the most recent modification of any file in thedirectory, or any of its subdirectories.`--time=ctime'`--time=status'`--time=use'Show the most recent status change time (the `ctime' in the inode)of any file in the directory, instead of the modification time.`--time=atime'`--time=access'Show the most recent access time (the `atime' in the inode) of anyfile in the directory, instead of the modification time.`--time-style=STYLE'List timestamps in style STYLE. This option has an effect only ifthe `--time' option is also specified. The STYLE should be one ofthe following:`+FORMAT'List timestamps using FORMAT, where FORMAT is interpretedlike the format argument of `date' (*note date invocation::).For example, `--time-style="+%Y-%m-%d %H:%M:%S"' causes `du'to list timestamps like `2002-03-30 23:45:56'. As with`date', FORMAT's interpretation is affected by the `LC_TIME'locale category.`full-iso'List timestamps in full using ISO 8601 date, time, and timezone format with nanosecond precision, e.g., `2002-03-3023:45:56.477817180 -0700'. This style is equivalent to`+%Y-%m-%d %H:%M:%S.%N %z'.`long-iso'List ISO 8601 date and time in minutes, e.g., `2002-03-3023:45'. These timestamps are shorter than `full-iso'timestamps, and are usually good enough for everyday work.This style is equivalent to `+%Y-%m-%d %H:%M'.`iso'List ISO 8601 dates for timestamps, e.g., `2002-03-30'. Thisstyle is equivalent to `+%Y-%m-%d'.You can specify the default value of the `--time-style' optionwith the environment variable `TIME_STYLE'; if `TIME_STYLE' is notset the default style is `long-iso'. For compatibility with `ls',if `TIME_STYLE' begins with `+' and contains a newline, thenewline and any later characters are ignored; if `TIME_STYLE'begins with `posix-' the `posix-' is ignored; and if `TIME_STYLE'is `locale' it is ignored.`-x'`--one-file-system'Skip directories that are on different file systems from the onethat the argument being processed is on.`--exclude=PATTERN'When recursing, skip subdirectories or files matching PATTERN.For example, `du --exclude='*.o'' excludes files whose names endin `.o'.`-X FILE'`--exclude-from=FILE'Like `--exclude', except take the patterns to exclude from FILE,one per line. If FILE is `-', take the patterns from standardinput.On BSD systems, `du' reports sizes that are half the correct valuesfor files that are NFS-mounted from HP-UX systems. On HP-UX systems,it reports sizes that are twice the correct values for files that areNFS-mounted from BSD systems. This is due to a flaw in HP-UX; it alsoaffects the HP-UX `du' program.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: stat invocation, Next: sync invocation, Prev: du invocation, Up: Disk usage14.3 `stat': Report file or file system status==============================================`stat' displays information about the specified file(s). Synopsis:stat [OPTION]... [FILE]...With no option, `stat' reports all information about the given files.But it also can be used to report the information of the file systemsthe given files are located on. If the files are links, `stat' canalso give information about the files the links point to.Due to shell aliases and built-in `stat' command, using an unadorned`stat' interactively or in a script may get you different functionalitythan that described here. Invoke it via `env' (i.e., `env stat ...')to avoid interference from the shell.`-L'`--dereference'Change how `stat' treats symbolic links. With this option, `stat'acts on the file referenced by each symbolic link argument.Without it, `stat' acts on any symbolic link argument directly.`-f'`--file-system'Report information about the file systems where the given filesare located instead of information about the files themselves.`-c'`--format=FORMAT'Use FORMAT rather than the default format. FORMAT isautomatically newline-terminated, so running a command like thefollowing with two or more FILE operands produces a line of outputfor each operand:$ stat --format=%d:%i / /usr2050:22057:2`--printf=FORMAT'Use FORMAT rather than the default format. Like `--format', butinterpret backslash escapes, and do not output a mandatorytrailing newline. If you want a newline, include `\n' in theFORMAT. Here's how you would use `--printf' to print the deviceand inode numbers of `/' and `/usr':$ stat --printf='%d:%i\n' / /usr2050:22057:2`-t'`--terse'Print the information in terse form, suitable for parsing by otherprograms.The valid FORMAT directives for files with `--format' and `--printf'are:* %a - Access rights in octal* %A - Access rights in human readable form* %b - Number of blocks allocated (see `%B')* %B - The size in bytes of each block reported by `%b'* %d - Device number in decimal* %D - Device number in hex* %f - Raw mode in hex* %F - File type* %g - Group ID of owner* %G - Group name of owner* %h - Number of hard links* %i - Inode number* %n - File name* %N - Quoted file name with dereference if symbolic link* %o - I/O block size* %s - Total size, in bytes* %t - Major device type in hex* %T - Minor device type in hex* %u - User ID of owner* %U - User name of owner* %x - Time of last access* %X - Time of last access as seconds since Epoch* %y - Time of last modification* %Y - Time of last modification as seconds since Epoch* %z - Time of last change* %Z - Time of last change as seconds since EpochWhen listing file system information (`--file-system' (`-f')), youmust use a different set of FORMAT directives:* %a - Free blocks available to non-super-user* %b - Total data blocks in file system* %c - Total file nodes in file system* %d - Free file nodes in file system* %f - Free blocks in file system* %i - File System ID in hex* %l - Maximum length of file names* %n - File name* %s - Block size (for faster transfers)* %S - Fundamental block size (for block counts)* %t - Type in hex* %T - Type in human readable formTime stamps are listed according to the time zone rules specified bythe `TZ' environment variable, or by the system default rules if `TZ'is not set. *Note Specifying the Time Zone with `TZ': (libc)TZVariable.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: sync invocation, Next: truncate invocation, Prev: stat invocation, Up: Disk usage14.4 `sync': Synchronize data on disk with memory=================================================`sync' writes any data buffered in memory out to disk. This caninclude (but is not limited to) modified superblocks, modified inodes,and delayed reads and writes. This must be implemented by the kernel;The `sync' program does nothing but exercise the `sync' system call.The kernel keeps data in memory to avoid doing (relatively slow) diskreads and writes. This improves performance, but if the computercrashes, data may be lost or the file system corrupted as a result.The `sync' command ensures everything in memory is written to disk.Any arguments are ignored, except for a lone `--help' or `--version'(*note Common options::).An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: truncate invocation, Prev: sync invocation, Up: Disk usage14.5 `truncate': Shrink or extend the size of a file====================================================`truncate' shrinks or extends the size of each FILE to the specifiedsize. Synopsis:truncate OPTION... FILE...Any FILE that does not exist is created.If a FILE is larger than the specified size, the extra data is lost.If a FILE is shorter, it is extended and the extended part (or hole)reads as zero bytes.The program accepts the following options. Also see *note Commonoptions::.`-c'`--no-create'Do not create files that do not exist.`-o'`--io-blocks'Treat SIZE as number of I/O blocks of the FILE rather than bytes.`-r RFILE'`--reference=RFILE'Set the size of each FILE to the same size as RFILE.`-s SIZE'`--size=SIZE'Set the size of each FILE to this SIZE. SIZE is a number whichmay have one of the following multiplicative suffixes:`KB' => 1000 (KiloBytes)`K' => 1024 (KibiBytes)`MB' => 1000*1000 (MegaBytes)`M' => 1024*1024 (MebiBytes)`GB' => 1000*1000*1000 (GigaBytes)`G' => 1024*1024*1024 (GibiBytes)and so on for `T', `P', `E', `Z', and `Y'.SIZE may also be prefixed by one of the following to adjust thesize of each FILE based on their current size:`+' => extend by`-' => reduce by`<' => at most`>' => at least`/' => round down to multiple of`%' => round up to multiple ofAn exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Printing text, Next: Conditions, Prev: Disk usage, Up: Top15 Printing text****************This section describes commands that display text strings.* Menu:* echo invocation:: Print a line of text.* printf invocation:: Format and print data.* yes invocation:: Print a string until interrupted.File: coreutils.info, Node: echo invocation, Next: printf invocation, Up: Printing text15.1 `echo': Print a line of text=================================`echo' writes each given STRING to standard output, with a spacebetween each and a newline after the last one. Synopsis:echo [OPTION]... [STRING]...Due to shell aliases and built-in `echo' command, using an unadorned`echo' interactively or in a script may get you different functionalitythan that described here. Invoke it via `env' (i.e., `env echo ...')to avoid interference from the shell.The program accepts the following options. Also see *note Commonoptions::. Options must precede operands, and the normally-specialargument `--' has no special meaning and is treated like any otherSTRING.`-n'Do not output the trailing newline.`-e'Enable interpretation of the following backslash-escapedcharacters in each STRING:`\a'alert (bell)`\b'backspace`\c'produce no further output`\f'form feed`\n'newline`\r'carriage return`\t'horizontal tab`\v'vertical tab`\\'backslash`\0NNN'the eight-bit value that is the octal number NNN (zero tothree octal digits)`\NNN'the eight-bit value that is the octal number NNN (one tothree octal digits)`\xHH'the eight-bit value that is the hexadecimal number HH (one ortwo hexadecimal digits)`-E'Disable interpretation of backslash escapes in each STRING. Thisis the default. If `-e' and `-E' are both specified, the last onegiven takes effect.If the `POSIXLY_CORRECT' environment variable is set, then when`echo''s first argument is not `-n' it outputs option-like argumentsinstead of treating them as options. For example, `echo -ne hello'outputs `-ne hello' instead of plain `hello'.POSIX does not require support for any options, and says that thebehavior of `echo' is implementation-defined if any STRING contains abackslash or if the first argument is `-n'. Portable programs can usethe `printf' command if they need to omit trailing newlines or outputcontrol characters or backslashes. *Note printf invocation::.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: printf invocation, Next: yes invocation, Prev: echo invocation, Up: Printing text15.2 `printf': Format and print data====================================`printf' does formatted printing of text. Synopsis:printf FORMAT [ARGUMENT]...`printf' prints the FORMAT string, interpreting `%' directives and`\' escapes to format numeric and string arguments in a way that ismostly similar to the C `printf' function. *Note `printf' formatdirectives: (libc)Output Conversion Syntax, for details. Thedifferences are listed below.Due to shell aliases and built-in `printf' command, using anunadorned `printf' interactively or in a script may get you differentfunctionality than that described here. Invoke it via `env' (i.e.,`env printf ...') to avoid interference from the shell.* The FORMAT argument is reused as necessary to convert all thegiven ARGUMENTs. For example, the command `printf %s a b' outputs`ab'.* Missing ARGUMENTs are treated as null strings or as zeros,depending on whether the context expects a string or a number. Forexample, the command `printf %sx%d' prints `x0'.* An additional escape, `\c', causes `printf' to produce no furtheroutput. For example, the command `printf 'A%sC\cD%sF' B E' prints`ABC'.* The hexadecimal escape sequence `\xHH' has at most two digits, asopposed to C where it can have an unlimited number of digits. Forexample, the command `printf '\x07e'' prints two bytes, whereasthe C statement `printf ("\x07e")' prints just one.* `printf' has an additional directive, `%b', which prints itsargument string with `\' escapes interpreted in the same way as inthe FORMAT string, except that octal escapes are of the form`\0OOO' where OOO is 0 to 3 octal digits. If a precision is alsogiven, it limits the number of bytes printed from the convertedstring.* Numeric arguments must be single C constants, possibly with leading`+' or `-'. For example, `printf %.4d -3' outputs `-0003'.* If the leading character of a numeric argument is `"' or `'' thenits value is the numeric value of the immediately followingcharacter. Any remaining characters are silently ignored if the`POSIXLY_CORRECT' environment variable is set; otherwise, awarning is printed. For example, `printf "%d" "'a"' outputs `97'on hosts that use the ASCII character set, since `a' has thenumeric value 97 in ASCII.A floating-point argument must use a period before any fractionaldigits, but is printed according to the `LC_NUMERIC' category of thecurrent locale. For example, in a locale whose radix character is acomma, the command `printf %g 3.14' outputs `3,14' whereas the command`printf %g 3,14' is an error.`printf' interprets `\OOO' in FORMAT as an octal number (if OOO is 1to 3 octal digits) specifying a character to print, and `\xHH' as ahexadecimal number (if HH is 1 to 2 hex digits) specifying a characterto print.`printf' interprets two character syntaxes introduced in ISO C 99:`\u' for 16-bit Unicode (ISO/IEC 10646) characters, specified as fourhexadecimal digits HHHH, and `\U' for 32-bit Unicode characters,specified as eight hexadecimal digits HHHHHHHH. `printf' outputs theUnicode characters according to the `LC_CTYPE' locale. Unicodecharacters in the ranges U+0000...U+009F, U+D800...U+DFFF cannot bespecified by this syntax, except for U+0024 ($), U+0040 (@), and U+0060()`.The processing of `\u' and `\U' requires a full-featured `iconv'facility. It is activated on systems with glibc 2.2 (or newer), orwhen `libiconv' is installed prior to this package. Otherwise `\u' and`\U' will print as-is.The only options are a lone `--help' or `--version'. *Note Commonoptions::. Options must precede operands.The Unicode character syntaxes are useful for writing strings in alocale independent way. For example, a string containing the Eurocurrency symbol$ env printf '\u20AC 14.95'will be output correctly in all locales supporting the Euro symbol(ISO-8859-15, UTF-8, and others). Similarly, a Chinese string$ env printf '\u4e2d\u6587'will be output correctly in all Chinese locales (GB2312, BIG5, UTF-8,etc).Note that in these examples, the `printf' command has been invokedvia `env' to ensure that we run the program found via your shell'ssearch path, and not a shell alias or a built-in function.For larger strings, you don't need to look up the hexadecimal codevalues of each character one by one. ASCII characters mixed with \uescape sequences is also known as the JAVA source file encoding. Youcan use GNU recode 3.5c (or newer) to convert strings to this encoding.Here is how to convert a piece of text into a shell script which willoutput this text in a locale-independent way:$ LC_CTYPE=zh_CN.big5 /usr/local/bin/printf \'\u4e2d\u6587\n' > sample.txt$ recode BIG5..JAVA < sample.txt \| sed -e "s|^|/usr/local/bin/printf '|" -e "s|$|\\\\n'|" \> sample.shAn exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: yes invocation, Prev: printf invocation, Up: Printing text15.3 `yes': Print a string until interrupted============================================`yes' prints the command line arguments, separated by spaces andfollowed by a newline, forever until it is killed. If no arguments aregiven, it prints `y' followed by a newline forever until killed.Upon a write error, `yes' exits with status `1'.The only options are a lone `--help' or `--version'. To output anargument that begins with `-', precede it with `--', e.g., `yes ----help'. *Note Common options::.File: coreutils.info, Node: Conditions, Next: Redirection, Prev: Printing text, Up: Top16 Conditions*************This section describes commands that are primarily useful for their exitstatus, rather than their output. Thus, they are often used as thecondition of shell `if' statements, or as the last command in apipeline.* Menu:* false invocation:: Do nothing, unsuccessfully.* true invocation:: Do nothing, successfully.* test invocation:: Check file types and compare values.* expr invocation:: Evaluate expressions.File: coreutils.info, Node: false invocation, Next: true invocation, Up: Conditions16.1 `false': Do nothing, unsuccessfully========================================`false' does nothing except return an exit status of 1, meaning"failure". It can be used as a place holder in shell scripts where anunsuccessful command is needed. In most modern shells, `false' is abuilt-in command, so when you use `false' in a script, you're probablyusing the built-in command, not the one documented here.`false' honors the `--help' and `--version' options.This version of `false' is implemented as a C program, and is thusmore secure and faster than a shell script implementation, and maysafely be used as a dummy shell for the purpose of disabling accounts.Note that `false' (unlike all other programs documented herein)exits unsuccessfully, even when invoked with `--help' or `--version'.Portable programs should not assume that the exit status of `false'is 1, as it is greater than 1 on some non-GNU hosts.File: coreutils.info, Node: true invocation, Next: test invocation, Prev: false invocation, Up: Conditions16.2 `true': Do nothing, successfully=====================================`true' does nothing except return an exit status of 0, meaning"success". It can be used as a place holder in shell scripts where asuccessful command is needed, although the shell built-in command `:'(colon) may do the same thing faster. In most modern shells, `true' isa built-in command, so when you use `true' in a script, you're probablyusing the built-in command, not the one documented here.`true' honors the `--help' and `--version' options.Note, however, that it is possible to cause `true' to exit withnonzero status: with the `--help' or `--version' option, and withstandard output already closed or redirected to a file that evokes anI/O error. For example, using a Bourne-compatible shell:$ ./true --version >&-./true: write error: Bad file number$ ./true --version > /dev/full./true: write error: No space left on deviceThis version of `true' is implemented as a C program, and is thusmore secure and faster than a shell script implementation, and maysafely be used as a dummy shell for the purpose of disabling accounts.File: coreutils.info, Node: test invocation, Next: expr invocation, Prev: true invocation, Up: Conditions16.3 `test': Check file types and compare values================================================`test' returns a status of 0 (true) or 1 (false) depending on theevaluation of the conditional expression EXPR. Each part of theexpression must be a separate argument.`test' has file status checks, string operators, and numericcomparison operators.`test' has an alternate form that uses opening and closing squarebrackets instead a leading `test'. For example, instead of `test -d/', you can write `[ -d / ]'. The square brackets must be separatearguments; for example, `[-d /]' does not have the desired effect.Since `test EXPR' and `[ EXPR ]' have the same meaning, only the formerform is discussed below.Synopses:test EXPRESSIONtest[ EXPRESSION ][ ][ OPTIONDue to shell aliases and built-in `test' command, using an unadorned`test' interactively or in a script may get you different functionalitythan that described here. Invoke it via `env' (i.e., `env test ...')to avoid interference from the shell.If EXPRESSION is omitted, `test' returns false. If EXPRESSION is asingle argument, `test' returns false if the argument is null and trueotherwise. The argument can be any string, including strings like`-d', `-1', `--', `--help', and `--version' that most other programswould treat as options. To get help and version information, invokethe commands `[ --help' and `[ --version', without the usual closingbrackets. *Note Common options::.Exit status:0 if the expression is true,1 if the expression is false,2 if an error occurred.* Menu:* File type tests:: -[bcdfhLpSt]* Access permission tests:: -[gkruwxOG]* File characteristic tests:: -e -s -nt -ot -ef* String tests:: -z -n = !=* Numeric tests:: -eq -ne -lt -le -gt -ge* Connectives for test:: ! -a -oFile: coreutils.info, Node: File type tests, Next: Access permission tests, Up: test invocation16.3.1 File type tests----------------------These options test for particular types of files. (Everything's a file,but not all files are the same!)`-b FILE'True if FILE exists and is a block special device.`-c FILE'True if FILE exists and is a character special device.`-d FILE'True if FILE exists and is a directory.`-f FILE'True if FILE exists and is a regular file.`-h FILE'`-L FILE'True if FILE exists and is a symbolic link. Unlike all otherfile-related tests, this test does not dereference FILE if it is asymbolic link.`-p FILE'True if FILE exists and is a named pipe.`-S FILE'True if FILE exists and is a socket.`-t FD'True if FD is a file descriptor that is associated with a terminal.File: coreutils.info, Node: Access permission tests, Next: File characteristic tests, Prev: File type tests, Up: test invocation16.3.2 Access permission tests------------------------------These options test for particular access permissions.`-g FILE'True if FILE exists and has its set-group-ID bit set.`-k FILE'True if FILE exists and has its "sticky" bit set.`-r FILE'True if FILE exists and read permission is granted.`-u FILE'True if FILE exists and has its set-user-ID bit set.`-w FILE'True if FILE exists and write permission is granted.`-x FILE'True if FILE exists and execute permission is granted (or searchpermission, if it is a directory).`-O FILE'True if FILE exists and is owned by the current effective user ID.`-G FILE'True if FILE exists and is owned by the current effective group ID.File: coreutils.info, Node: File characteristic tests, Next: String tests, Prev: Access permission tests, Up: test invocation16.3.3 File characteristic tests--------------------------------These options test other file characteristics.`-e FILE'True if FILE exists.`-s FILE'True if FILE exists and has a size greater than zero.`FILE1 -nt FILE2'True if FILE1 is newer (according to modification date) thanFILE2, or if FILE1 exists and FILE2 does not.`FILE1 -ot FILE2'True if FILE1 is older (according to modification date) thanFILE2, or if FILE2 exists and FILE1 does not.`FILE1 -ef FILE2'True if FILE1 and FILE2 have the same device and inode numbers,i.e., if they are hard links to each other.File: coreutils.info, Node: String tests, Next: Numeric tests, Prev: File characteristic tests, Up: test invocation16.3.4 String tests-------------------These options test string characteristics. You may need to quoteSTRING arguments for the shell. For example:test -n "$V"The quotes here prevent the wrong arguments from being passed to`test' if `$V' is empty or contains special characters.`-z STRING'True if the length of STRING is zero.`-n STRING'`STRING'True if the length of STRING is nonzero.`STRING1 = STRING2'True if the strings are equal.`STRING1 != STRING2'True if the strings are not equal.File: coreutils.info, Node: Numeric tests, Next: Connectives for test, Prev: String tests, Up: test invocation16.3.5 Numeric tests--------------------Numeric relational operators. The arguments must be entirely numeric(possibly negative), or the special expression `-l STRING', whichevaluates to the length of STRING.`ARG1 -eq ARG2'`ARG1 -ne ARG2'`ARG1 -lt ARG2'`ARG1 -le ARG2'`ARG1 -gt ARG2'`ARG1 -ge ARG2'These arithmetic binary operators return true if ARG1 is equal,not-equal, less-than, less-than-or-equal, greater-than, orgreater-than-or-equal than ARG2, respectively.For example:test -1 -gt -2 && echo yes=> yestest -l abc -gt 1 && echo yes=> yestest 0x100 -eq 1error--> test: integer expression expected before -eqFile: coreutils.info, Node: Connectives for test, Prev: Numeric tests, Up: test invocation16.3.6 Connectives for `test'-----------------------------The usual logical connectives.`! EXPR'True if EXPR is false.`EXPR1 -a EXPR2'True if both EXPR1 and EXPR2 are true.`EXPR1 -o EXPR2'True if either EXPR1 or EXPR2 is true.File: coreutils.info, Node: expr invocation, Prev: test invocation, Up: Conditions16.4 `expr': Evaluate expressions=================================`expr' evaluates an expression and writes the result on standardoutput. Each token of the expression must be a separate argument.Operands are either integers or strings. Integers consist of one ormore decimal digits, with an optional leading `-'. `expr' convertsanything appearing in an operand position to an integer or a stringdepending on the operation being applied to it.Strings are not quoted for `expr' itself, though you may need toquote them to protect characters with special meaning to the shell,e.g., spaces. However, regardless of whether it is quoted, a stringoperand should not be a parenthesis or any of `expr''s operators like`+', so you cannot safely pass an arbitrary string `$str' to exprmerely by quoting it to the shell. One way to work around this is touse the GNU extension `+', (e.g., `+ "$str" = foo'); a more portableway is to use `" $str"' and to adjust the rest of the expression to takethe leading space into account (e.g., `" $str" = " foo"').You should not pass a negative integer or a string with leading `-'as `expr''s first argument, as it might be misinterpreted as an option;this can be avoided by parenthesization. Also, portable scripts shouldnot use a string operand that happens to take the form of an integer;this can be worked around by inserting leading spaces as mentionedabove.Operators may be given as infix symbols or prefix keywords.Parentheses may be used for grouping in the usual manner. You mustquote parentheses and many operators to avoid the shell evaluating them,however.When built with support for the GNU MP library, `expr' usesarbitrary-precision arithmetic; otherwise, it uses native arithmetictypes and may fail due to arithmetic overflow.The only options are `--help' and `--version'. *Note Commonoptions::. Options must precede operands.Exit status:0 if the expression is neither null nor 0,1 if the expression is null or 0,2 if the expression is invalid,3 if an internal error occurred (e.g., arithmetic overflow).* Menu:* String expressions:: + : match substr index length* Numeric expressions:: + - * / %* Relations for expr:: | & < <= = == != >= >* Examples of expr:: Examples.File: coreutils.info, Node: String expressions, Next: Numeric expressions, Up: expr invocation16.4.1 String expressions-------------------------`expr' supports pattern matching and other string operators. Thesehave higher precedence than both the numeric and relational operators(in the next sections).`STRING : REGEX'Perform pattern matching. The arguments are converted to stringsand the second is considered to be a (basic, a la GNU `grep')regular expression, with a `^' implicitly prepended. The firstargument is then matched against this regular expression.If the match succeeds and REGEX uses `\(' and `\)', the `:'expression returns the part of STRING that matched thesubexpression; otherwise, it returns the number of charactersmatched.If the match fails, the `:' operator returns the null string if`\(' and `\)' are used in REGEX, otherwise 0.Only the first `\( ... \)' pair is relevant to the return value;additional pairs are meaningful only for grouping the regularexpression operators.In the regular expression, `\+', `\?', and `\|' are operatorswhich respectively match one or more, zero or one, or separatealternatives. SunOS and other `expr''s treat these as regularcharacters. (POSIX allows either behavior.) *Note RegularExpression Library: (regex)Top, for details of regular expressionsyntax. Some examples are in *note Examples of expr::.`match STRING REGEX'An alternative way to do pattern matching. This is the same as`STRING : REGEX'.`substr STRING POSITION LENGTH'Returns the substring of STRING beginning at POSITION with lengthat most LENGTH. If either POSITION or LENGTH is negative, zero,or non-numeric, returns the null string.`index STRING CHARSET'Returns the first position in STRING where the first character inCHARSET was found. If no character in CHARSET is found in STRING,return 0.`length STRING'Returns the length of STRING.`+ TOKEN'Interpret TOKEN as a string, even if it is a keyword like MATCH oran operator like `/'. This makes it possible to test `expr length+ "$x"' or `expr + "$x" : '.*/\(.\)'' and have it do the rightthing even if the value of $X happens to be (for example) `/' or`index'. This operator is a GNU extension. Portable shellscripts should use `" $token" : ' \(.*\)'' instead of `+ "$token"'.To make `expr' interpret keywords as strings, you must use the`quote' operator.File: coreutils.info, Node: Numeric expressions, Next: Relations for expr, Prev: String expressions, Up: expr invocation16.4.2 Numeric expressions--------------------------`expr' supports the usual numeric operators, in order of increasingprecedence. These numeric operators have lower precedence than thestring operators described in the previous section, and higherprecedence than the connectives (next section).`+ -'Addition and subtraction. Both arguments are converted tointegers; an error occurs if this cannot be done.`* / %'Multiplication, division, remainder. Both arguments are convertedto integers; an error occurs if this cannot be done.File: coreutils.info, Node: Relations for expr, Next: Examples of expr, Prev: Numeric expressions, Up: expr invocation16.4.3 Relations for `expr'---------------------------`expr' supports the usual logical connectives and relations. Thesehave lower precedence than the string and numeric operators (previoussections). Here is the list, lowest-precedence operator first.`|'Returns its first argument if that is neither null nor zero,otherwise its second argument if it is neither null nor zero,otherwise 0. It does not evaluate its second argument if itsfirst argument is neither null nor zero.`&'Return its first argument if neither argument is null or zero,otherwise 0. It does not evaluate its second argument if itsfirst argument is null or zero.`< <= = == != >= >'Compare the arguments and return 1 if the relation is true, 0otherwise. `==' is a synonym for `='. `expr' first tries toconvert both arguments to integers and do a numeric comparison; ifeither conversion fails, it does a lexicographic comparison usingthe character collating sequence specified by the `LC_COLLATE'locale.File: coreutils.info, Node: Examples of expr, Prev: Relations for expr, Up: expr invocation16.4.4 Examples of using `expr'-------------------------------Here are a few examples, including quoting for shell metacharacters.To add 1 to the shell variable `foo', in Bourne-compatible shells:foo=`expr $foo + 1`To print the non-directory part of the file name stored in `$fname',which need not contain a `/':expr $fname : '.*/\(.*\)' '|' $fnameAn example showing that `\+' is an operator:expr aaa : 'a\+'=> 3expr abc : 'a\(.\)c'=> bexpr index abcdef cz=> 3expr index index aerror--> expr: syntax errorexpr index + index a=> 0File: coreutils.info, Node: Redirection, Next: File name manipulation, Prev: Conditions, Up: Top17 Redirection**************Unix shells commonly provide several forms of "redirection"--ways tochange the input source or output destination of a command. But oneuseful redirection is performed by a separate command, not by the shell;it's described here.* Menu:* tee invocation:: Redirect output to multiple files or processes.File: coreutils.info, Node: tee invocation, Up: Redirection17.1 `tee': Redirect output to multiple files or processes==========================================================The `tee' command copies standard input to standard output and also toany files given as arguments. This is useful when you want not only tosend some data down a pipe, but also to save a copy. Synopsis:tee [OPTION]... [FILE]...If a file being written to does not already exist, it is created.If a file being written to already exists, the data it previouslycontained is overwritten unless the `-a' option is used.A FILE of `-' causes `tee' to send another copy of input to standardoutput, but this is typically not that useful as the copies areinterleaved.The program accepts the following options. Also see *note Commonoptions::.`-a'`--append'Append standard input to the given files rather than overwritingthem.`-i'`--ignore-interrupts'Ignore interrupt signals.The `tee' command is useful when you happen to be transferring alarge amount of data and also want to summarize that data withoutreading it a second time. For example, when you are downloading a DVDimage, you often want to verify its signature or checksum right away.The inefficient way to do it is simply:wget http://example.com/some.iso && sha1sum some.isoOne problem with the above is that it makes you wait for thedownload to complete before starting the time-consuming SHA1computation. Perhaps even more importantly, the above requires readingthe DVD image a second time (the first was from the network).The efficient way to do it is to interleave the download and SHA1computation. Then, you'll get the checksum for free, because theentire process parallelizes so well:# slightly contrived, to demonstrate process substitutionwget -O - http://example.com/dvd.iso \| tee >(sha1sum > dvd.sha1) > dvd.isoThat makes `tee' write not just to the expected output file, butalso to a pipe running `sha1sum' and saving the final checksum in afile named `dvd.sha1'.Note, however, that this example relies on a feature of modern shellscalled "process substitution" (the `>(command)' syntax, above; *NoteProcess Substitution: (bashref)Process Substitution.), so it works with`zsh', `bash', and `ksh', but not with `/bin/sh'. So if you write codelike this in a shell script, be sure to start the script with`#!/bin/bash'.Since the above example writes to one file and one process, a moreconventional and portable use of `tee' is even better:wget -O - http://example.com/dvd.iso \| tee dvd.iso | sha1sum > dvd.sha1You can extend this example to make `tee' write to two processes,computing MD5 and SHA1 checksums in parallel. In this case, processsubstitution is required:wget -O - http://example.com/dvd.iso \| tee >(sha1sum > dvd.sha1) \>(md5sum > dvd.md5) \> dvd.isoThis technique is also useful when you want to make a _compressed_copy of the contents of a pipe. Consider a tool to graphicallysummarize disk usage data from `du -ak'. For a large hierarchy, `du-ak' can run for a long time, and can easily produce terabytes of data,so you won't want to rerun the command unnecessarily. Nor will youwant to save the uncompressed output.Doing it the inefficient way, you can't even start the GUI untilafter you've compressed all of the `du' output:du -ak | gzip -9 > /tmp/du.gzgzip -d /tmp/du.gz | xdiskusage -aWith `tee' and process substitution, you start the GUI right awayand eliminate the decompression completely:du -ak | tee >(gzip -9 > /tmp/du.gz) | xdiskusage -aFinally, if you regularly create more than one type of compressedtarball at once, for example when `make dist' creates both`gzip'-compressed and `bzip2'-compressed tarballs, there may be abetter way. Typical `automake'-generated `Makefile' rules create thetwo compressed tar archives with commands in sequence, like this(slightly simplified):tardir=your-pkg-M.Ntar chof - "$tardir" | gzip -9 -c > your-pkg-M.N.tar.gztar chof - "$tardir" | bzip2 -9 -c > your-pkg-M.N.tar.bz2However, if the hierarchy you are archiving and compressing is largerthan a couple megabytes, and especially if you are using amulti-processor system with plenty of memory, then you can do muchbetter by reading the directory contents only once and running thecompression programs in parallel:tardir=your-pkg-M.Ntar chof - "$tardir" \| tee >(gzip -9 -c > your-pkg-M.N.tar.gz) \| bzip2 -9 -c > your-pkg-M.N.tar.bz2An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: File name manipulation, Next: Working context, Prev: Redirection, Up: Top18 File name manipulation*************************This section describes commands that manipulate file names.* Menu:* basename invocation:: Strip directory and suffix from a file name.* dirname invocation:: Strip non-directory suffix from a file name.* pathchk invocation:: Check file name validity and portability.File: coreutils.info, Node: basename invocation, Next: dirname invocation, Up: File name manipulation18.1 `basename': Strip directory and suffix from a file name============================================================`basename' removes any leading directory components from NAME.Synopsis:basename NAME [SUFFIX]If SUFFIX is specified and is identical to the end of NAME, it isremoved from NAME as well. Note that since trailing slashes areremoved prior to suffix matching, SUFFIX will do nothing if it containsslashes. `basename' prints the result on standard output.Together, `basename' and `dirname' are designed such that if `ls"$name"' succeeds, then the command sequence `cd "$(dirname "$name")";ls "$(basename "$name")"' will, too. This works for everything exceptfile names containing a trailing newline.POSIX allows the implementation to define the results if NAME isempty or `//'. In the former case, GNU `basename' returns the emptystring. In the latter case, the result is `//' on platforms where //is distinct from /, and `/' on platforms where there is no difference.The only options are `--help' and `--version'. *Note Commonoptions::. Options must precede operands.An exit status of zero indicates success, and a nonzero valueindicates failure.Examples:# Output "sort".basename /usr/bin/sort# Output "stdio".basename include/stdio.h .hFile: coreutils.info, Node: dirname invocation, Next: pathchk invocation, Prev: basename invocation, Up: File name manipulation18.2 `dirname': Strip non-directory suffix from a file name===========================================================`dirname' prints all but the final slash-delimited component of astring (presumably a file name). Synopsis:dirname NAMEIf NAME is a single component, `dirname' prints `.' (meaning thecurrent directory).Together, `basename' and `dirname' are designed such that if `ls"$name"' succeeds, then the command sequence `cd "$(dirname "$name")";ls "$(basename "$name")"' will, too. This works for everything exceptfile names containing a trailing newline.POSIX allows the implementation to define the results if NAME is`//'. With GNU `dirname', the result is `//' on platforms where // isdistinct from /, and `/' on platforms where there is no difference.The only options are `--help' and `--version'. *Note Commonoptions::.An exit status of zero indicates success, and a nonzero valueindicates failure.Examples:# Output "/usr/bin".dirname /usr/bin/sort# Output ".".dirname stdio.hFile: coreutils.info, Node: pathchk invocation, Prev: dirname invocation, Up: File name manipulation18.3 `pathchk': Check file name validity and portability========================================================`pathchk' checks validity and portability of file names. Synopsis:pathchk [OPTION]... NAME...For each NAME, `pathchk' prints an error message if any of theseconditions is true:1. One of the existing directories in NAME does not have search(execute) permission,2. The length of NAME is larger than the maximum supported by theoperating system.3. The length of one component of NAME is longer than its filesystem's maximum.A nonexistent NAME is not an error, so long a file with that namecould be created under the above conditions.The program accepts the following options. Also see *note Commonoptions::. Options must precede operands.`-p'Instead of performing checks based on the underlying file system,print an error message if any of these conditions is true:1. A file name is empty.2. A file name contains a character outside the POSIX portablefile name character set, namely, the ASCII letters anddigits, `.', `_', `-', and `/'.3. The length of a file name or one of its components exceeds thePOSIX minimum limits for portability.`-P'Print an error message if a file name is empty, or if it containsa component that begins with `-'.`--portability'Print an error message if a file name is not portable to all POSIXhosts. This option is equivalent to `-p -P'.Exit status:0 if all specified file names passed all checks,1 otherwise.File: coreutils.info, Node: Working context, Next: User information, Prev: File name manipulation, Up: Top19 Working context******************This section describes commands that display or alter the context inwhich you are working: the current directory, the terminal settings, andso forth. See also the user-related commands in the next section.* Menu:* pwd invocation:: Print working directory.* stty invocation:: Print or change terminal characteristics.* printenv invocation:: Print environment variables.* tty invocation:: Print file name of terminal on standard input.File: coreutils.info, Node: pwd invocation, Next: stty invocation, Up: Working context19.1 `pwd': Print working directory===================================`pwd' prints the name of the current directory. Synopsis:pwd [OPTION]...The program accepts the following options. Also see *note Commonoptions::.`-L'`--logical'If the contents of the environment variable `PWD' provide anabsolute name of the current directory with no `.' or `..'components, but possibly with symbolic links, then output thosecontents. Otherwise, fall back to default `-P' handling.`-P'`--physical'Print a fully resolved name for the current directory. That is,all components of the printed name will be actual directorynames--none will be symbolic links.If `-L' and `-P' are both given, the last one takes precedence. Ifneither option is given, then this implementation uses `-P' as thedefault unless the `POSIXLY_CORRECT' environment variable is set.Due to shell aliases and built-in `pwd' command, using an unadorned`pwd' interactively or in a script may get you different functionalitythan that described here. Invoke it via `env' (i.e., `env pwd ...') toavoid interference from the shell.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: stty invocation, Next: printenv invocation, Prev: pwd invocation, Up: Working context19.2 `stty': Print or change terminal characteristics=====================================================`stty' prints or changes terminal characteristics, such as baud rate.Synopses:stty [OPTION] [SETTING]...stty [OPTION]If given no line settings, `stty' prints the baud rate, linediscipline number (on systems that support it), and line settings thathave been changed from the values set by `stty sane'. By default, modereading and setting are performed on the tty line connected to standardinput, although this can be modified by the `--file' option.`stty' accepts many non-option arguments that change aspects of theterminal line operation, as described below.The program accepts the following options. Also see *note Commonoptions::.`-a'`--all'Print all current settings in human-readable form. This optionmay not be used in combination with any line settings.`-F DEVICE'`--file=DEVICE'Set the line opened by the file name specified in DEVICE instead ofthe tty line connected to standard input. This option is necessarybecause opening a POSIX tty requires use of the `O_NONDELAY' flagto prevent a POSIX tty from blocking until the carrier detect lineis high if the `clocal' flag is not set. Hence, it is not alwayspossible to allow the shell to open the device in the traditionalmanner.`-g'`--save'Print all current settings in a form that can be used as anargument to another `stty' command to restore the currentsettings. This option may not be used in combination with anyline settings.Many settings can be turned off by preceding them with a `-'. Sucharguments are marked below with "May be negated" in their description.The descriptions themselves refer to the positive case, that is, when_not_ negated (unless stated otherwise, of course).Some settings are not available on all POSIX systems, since they useextensions. Such arguments are marked below with "Non-POSIX" in theirdescription. On non-POSIX systems, those or other settings also may notbe available, but it's not feasible to document all the variations: justtry it and see.An exit status of zero indicates success, and a nonzero valueindicates failure.* Menu:* Control:: Control settings* Input:: Input settings* Output:: Output settings* Local:: Local settings* Combination:: Combination settings* Characters:: Special characters* Special:: Special settingsFile: coreutils.info, Node: Control, Next: Input, Up: stty invocation19.2.1 Control settings-----------------------Control settings:`parenb'Generate parity bit in output and expect parity bit in input. Maybe negated.`parodd'Set odd parity (even if negated). May be negated.`cs5'`cs6'`cs7'`cs8'Set character size to 5, 6, 7, or 8 bits.`hup'`hupcl'Send a hangup signal when the last process closes the tty. May benegated.`cstopb'Use two stop bits per character (one if negated). May be negated.`cread'Allow input to be received. May be negated.`clocal'Disable modem control signals. May be negated.`crtscts'Enable RTS/CTS flow control. Non-POSIX. May be negated.File: coreutils.info, Node: Input, Next: Output, Prev: Control, Up: stty invocation19.2.2 Input settings---------------------These settings control operations on data received from the terminal.`ignbrk'Ignore break characters. May be negated.`brkint'Make breaks cause an interrupt signal. May be negated.`ignpar'Ignore characters with parity errors. May be negated.`parmrk'Mark parity errors (with a 255-0-character sequence). May benegated.`inpck'Enable input parity checking. May be negated.`istrip'Clear high (8th) bit of input characters. May be negated.`inlcr'Translate newline to carriage return. May be negated.`igncr'Ignore carriage return. May be negated.`icrnl'Translate carriage return to newline. May be negated.`iutf8'Assume input characters are UTF-8 encoded. May be negated.`ixon'Enable XON/XOFF flow control (that is, `CTRL-S'/`CTRL-Q'). May benegated.`ixoff'`tandem'Enable sending of `stop' character when the system input buffer isalmost full, and `start' character when it becomes almost emptyagain. May be negated.`iuclc'Translate uppercase characters to lowercase. Non-POSIX. May benegated. Note ilcuc is not implemented, as one would not be ableto issue almost any (lowercase) Unix command, after invoking it.`ixany'Allow any character to restart output (only the start character ifnegated). Non-POSIX. May be negated.`imaxbel'Enable beeping and not flushing input buffer if a character arriveswhen the input buffer is full. Non-POSIX. May be negated.File: coreutils.info, Node: Output, Next: Local, Prev: Input, Up: stty invocation19.2.3 Output settings----------------------These settings control operations on data sent to the terminal.`opost'Postprocess output. May be negated.`olcuc'Translate lowercase characters to uppercase. Non-POSIX. May benegated. (Note ouclc is not currently implemented.)`ocrnl'Translate carriage return to newline. Non-POSIX. May be negated.`onlcr'Translate newline to carriage return-newline. Non-POSIX. May benegated.`onocr'Do not print carriage returns in the first column. Non-POSIX.May be negated.`onlret'Newline performs a carriage return. Non-POSIX. May be negated.`ofill'Use fill (padding) characters instead of timing for delays.Non-POSIX. May be negated.`ofdel'Use ASCII DEL characters for fill instead of ASCII NUL characters.Non-POSIX. May be negated.`nl1'`nl0'Newline delay style. Non-POSIX.`cr3'`cr2'`cr1'`cr0'Carriage return delay style. Non-POSIX.`tab3'`tab2'`tab1'`tab0'Horizontal tab delay style. Non-POSIX.`bs1'`bs0'Backspace delay style. Non-POSIX.`vt1'`vt0'Vertical tab delay style. Non-POSIX.`ff1'`ff0'Form feed delay style. Non-POSIX.File: coreutils.info, Node: Local, Next: Combination, Prev: Output, Up: stty invocation19.2.4 Local settings---------------------`isig'Enable `interrupt', `quit', and `suspend' special characters. Maybe negated.`icanon'Enable `erase', `kill', `werase', and `rprnt' special characters.May be negated.`iexten'Enable non-POSIX special characters. May be negated.`echo'Echo input characters. May be negated.`echoe'`crterase'Echo `erase' characters as backspace-space-backspace. May benegated.`echok'Echo a newline after a `kill' character. May be negated.`echonl'Echo newline even if not echoing other characters. May be negated.`noflsh'Disable flushing after `interrupt' and `quit' special characters.May be negated.`xcase'Enable input and output of uppercase characters by preceding theirlowercase equivalents with `\', when `icanon' is set. Non-POSIX.May be negated.`tostop'Stop background jobs that try to write to the terminal. Non-POSIX.May be negated.`echoprt'`prterase'Echo erased characters backward, between `\' and `/'. Non-POSIX.May be negated.`echoctl'`ctlecho'Echo control characters in hat notation (`^C') instead ofliterally. Non-POSIX. May be negated.`echoke'`crtkill'Echo the `kill' special character by erasing each character on theline as indicated by the `echoprt' and `echoe' settings, insteadof by the `echoctl' and `echok' settings. Non-POSIX. May benegated.File: coreutils.info, Node: Combination, Next: Characters, Prev: Local, Up: stty invocation19.2.5 Combination settings---------------------------Combination settings:`evenp'`parity'Same as `parenb -parodd cs7'. May be negated. If negated, sameas `-parenb cs8'.`oddp'Same as `parenb parodd cs7'. May be negated. If negated, same as`-parenb cs8'.`nl'Same as `-icrnl -onlcr'. May be negated. If negated, same as`icrnl -inlcr -igncr onlcr -ocrnl -onlret'.`ek'Reset the `erase' and `kill' special characters to their defaultvalues.`sane'Same as:cread -ignbrk brkint -inlcr -igncr icrnl -ixoff-iuclc -ixany imaxbel opost -olcuc -ocrnl onlcr-onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0ff0 isig icanon iexten echo echoe echok -echonl-noflsh -xcase -tostop -echoprt echoctl echokeand also sets all special characters to their default values.`cooked'Same as `brkint ignpar istrip icrnl ixon opost isig icanon', plussets the `eof' and `eol' characters to their default values ifthey are the same as the `min' and `time' characters. May benegated. If negated, same as `raw'.`raw'Same as:-ignbrk -brkint -ignpar -parmrk -inpck -istrip-inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany-imaxbel -opost -isig -icanon -xcase min 1 time 0May be negated. If negated, same as `cooked'.`cbreak'Same as `-icanon'. May be negated. If negated, same as `icanon'.`pass8'Same as `-parenb -istrip cs8'. May be negated. If negated, sameas `parenb istrip cs7'.`litout'Same as `-parenb -istrip -opost cs8'. May be negated. Ifnegated, same as `parenb istrip opost cs7'.`decctlq'Same as `-ixany'. Non-POSIX. May be negated.`tabs'Same as `tab0'. Non-POSIX. May be negated. If negated, same as`tab3'.`lcase'`LCASE'Same as `xcase iuclc olcuc'. Non-POSIX. May be negated. (Usedfor terminals with uppercase characters only.)`crt'Same as `echoe echoctl echoke'.`dec'Same as `echoe echoctl echoke -ixany intr ^C erase ^? kill C-u'.File: coreutils.info, Node: Characters, Next: Special, Prev: Combination, Up: stty invocation19.2.6 Special characters-------------------------The special characters' default values vary from system to system.They are set with the syntax `name value', where the names are listedbelow and the value can be given either literally, in hat notation(`^C'), or as an integer which may start with `0x' to indicatehexadecimal, `0' to indicate octal, or any other digit to indicatedecimal.For GNU stty, giving a value of `^-' or `undef' disables thatspecial character. (This is incompatible with Ultrix `stty', whichuses a value of `u' to disable a special character. GNU `stty' treatsa value `u' like any other, namely to set that special character to<U>.)`intr'Send an interrupt signal.`quit'Send a quit signal.`erase'Erase the last character typed.`kill'Erase the current line.`eof'Send an end of file (terminate the input).`eol'End the line.`eol2'Alternate character to end the line. Non-POSIX.`swtch'Switch to a different shell layer. Non-POSIX.`start'Restart the output after stopping it.`stop'Stop the output.`susp'Send a terminal stop signal.`dsusp'Send a terminal stop signal after flushing the input. Non-POSIX.`rprnt'Redraw the current line. Non-POSIX.`werase'Erase the last word typed. Non-POSIX.`lnext'Enter the next character typed literally, even if it is a specialcharacter. Non-POSIX.File: coreutils.info, Node: Special, Prev: Characters, Up: stty invocation19.2.7 Special settings-----------------------`min N'Set the minimum number of characters that will satisfy a read untilthe time value has expired, when `-icanon' is set.`time N'Set the number of tenths of a second before reads time out if theminimum number of characters have not been read, when `-icanon' isset.`ispeed N'Set the input speed to N.`ospeed N'Set the output speed to N.`rows N'Tell the tty kernel driver that the terminal has N rows.Non-POSIX.`cols N'`columns N'Tell the kernel that the terminal has N columns. Non-POSIX.`size'Print the number of rows and columns that the kernel thinks theterminal has. (Systems that don't support rows and columns in thekernel typically use the environment variables `LINES' and`COLUMNS' instead; however, GNU `stty' does not know anythingabout them.) Non-POSIX.`line N'Use line discipline N. Non-POSIX.`speed'Print the terminal speed.`N'Set the input and output speeds to N. N can be one of: 0 50 75110 134 134.5 150 200 300 600 1200 1800 2400 4800 9600 19200 38400`exta' `extb'. `exta' is the same as 19200; `extb' is the same as38400. Many systems, including GNU/Linux, support higher speeds.The `stty' command includes support for speeds of 57600, 115200,230400, 460800, 500000, 576000, 921600, 1000000, 1152000, 1500000,2000000, 2500000, 3000000, 3500000, or 4000000 where the systemsupports these. 0 hangs up the line if `-clocal' is set.File: coreutils.info, Node: printenv invocation, Next: tty invocation, Prev: stty invocation, Up: Working context19.3 `printenv': Print all or some environment variables========================================================`printenv' prints environment variable values. Synopsis:printenv [OPTION] [VARIABLE]...If no VARIABLEs are specified, `printenv' prints the value of everyenvironment variable. Otherwise, it prints the value of each VARIABLEthat is set, and nothing for those that are not set.The only options are a lone `--help' or `--version'. *Note Commonoptions::.Exit status:0 if all variables specified were found1 if at least one specified variable was not found2 if a write error occurredFile: coreutils.info, Node: tty invocation, Prev: printenv invocation, Up: Working context19.4 `tty': Print file name of terminal on standard input=========================================================`tty' prints the file name of the terminal connected to its standardinput. It prints `not a tty' if standard input is not a terminal.Synopsis:tty [OPTION]...The program accepts the following option. Also see *note Commonoptions::.`-s'`--silent'`--quiet'Print nothing; only return an exit status.Exit status:0 if standard input is a terminal1 if standard input is not a terminal2 if given incorrect arguments3 if a write error occursFile: coreutils.info, Node: User information, Next: System context, Prev: Working context, Up: Top20 User information*******************This section describes commands that print user-related information:logins, groups, and so forth.* Menu:* id invocation:: Print user identity.* logname invocation:: Print current login name.* whoami invocation:: Print effective user ID.* groups invocation:: Print group names a user is in.* users invocation:: Print login names of users currently logged in.* who invocation:: Print who is currently logged in.File: coreutils.info, Node: id invocation, Next: logname invocation, Up: User information20.1 `id': Print user identity==============================`id' prints information about the given user, or the process running itif no user is specified. Synopsis:id [OPTION]... [USERNAME]By default, it prints the real user ID, real group ID, effectiveuser ID if different from the real user ID, effective group ID ifdifferent from the real group ID, and supplemental group IDs.Each of these numeric values is preceded by an identifying string andfollowed by the corresponding user or group name in parentheses.The options cause `id' to print only part of the above information.Also see *note Common options::.`-g'`--group'Print only the group ID.`-G'`--groups'Print only the group ID and the supplementary groups.`-n'`--name'Print the user or group name instead of the ID number. Requires`-u', `-g', or `-G'.`-r'`--real'Print the real, instead of effective, user or group ID. Requires`-u', `-g', or `-G'.`-u'`--user'Print only the user ID.`-Z'`--context'Print only the security context of the current user. If SELinuxis disabled then print a warning and set the exit status to 1.An exit status of zero indicates success, and a nonzero valueindicates failure.Primary and supplementary groups for a process are normally inheritedfrom its parent and are usually unchanged since login. This means thatif you change the group database after logging in, `id' will notreflect your changes within your existing login session. Running `id'with a user argument causes the user and group database to be consultedafresh, and so will give a different result.File: coreutils.info, Node: logname invocation, Next: whoami invocation, Prev: id invocation, Up: User information20.2 `logname': Print current login name========================================`logname' prints the calling user's name, as found in asystem-maintained file (often `/var/run/utmp' or `/etc/utmp'), andexits with a status of 0. If there is no entry for the callingprocess, `logname' prints an error message and exits with a status of 1.The only options are `--help' and `--version'. *Note Commonoptions::.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: whoami invocation, Next: groups invocation, Prev: logname invocation, Up: User information20.3 `whoami': Print effective user ID======================================`whoami' prints the user name associated with the current effectiveuser ID. It is equivalent to the command `id -un'.The only options are `--help' and `--version'. *Note Commonoptions::.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: groups invocation, Next: users invocation, Prev: whoami invocation, Up: User information20.4 `groups': Print group names a user is in=============================================`groups' prints the names of the primary and any supplementary groupsfor each given USERNAME, or the current process if no names are given.If more than one name is given, the name of each user is printed beforethe list of that user's groups and the user name is separated from thegroup list by a colon. Synopsis:groups [USERNAME]...The group lists are equivalent to the output of the command `id -Gn'.Primary and supplementary groups for a process are normally inheritedfrom its parent and are usually unchanged since login. This means thatif you change the group database after logging in, `groups' will notreflect your changes within your existing login session. Running`groups' with a list of users causes the user and group database to beconsulted afresh, and so will give a different result.The only options are `--help' and `--version'. *Note Commonoptions::.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: users invocation, Next: who invocation, Prev: groups invocation, Up: User information20.5 `users': Print login names of users currently logged in============================================================`users' prints on a single line a blank-separated list of user names ofusers currently logged in to the current host. Each user namecorresponds to a login session, so if a user has more than one loginsession, that user's name will appear the same number of times in theoutput. Synopsis:users [FILE]With no FILE argument, `users' extracts its information from asystem-maintained file (often `/var/run/utmp' or `/etc/utmp'). If afile argument is given, `users' uses that file instead. A commonchoice is `/var/log/wtmp'.The only options are `--help' and `--version'. *Note Commonoptions::.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: who invocation, Prev: users invocation, Up: User information20.6 `who': Print who is currently logged in============================================`who' prints information about users who are currently logged on.Synopsis:`who' [OPTION] [FILE] [am i]If given no non-option arguments, `who' prints the followinginformation for each user currently logged on: login name, terminalline, login time, and remote hostname or X display.If given one non-option argument, `who' uses that instead of adefault system-maintained file (often `/var/run/utmp' or `/etc/utmp')as the name of the file containing the record of users logged on.`/var/log/wtmp' is commonly given as an argument to `who' to look atwho has previously logged on.If given two non-option arguments, `who' prints only the entry forthe user running it (determined from its standard input), preceded bythe hostname. Traditionally, the two arguments given are `am i', as in`who am i'.Time stamps are listed according to the time zone rules specified bythe `TZ' environment variable, or by the system default rules if `TZ'is not set. *Note Specifying the Time Zone with `TZ': (libc)TZVariable.The program accepts the following options. Also see *note Commonoptions::.`-a'`--all'Same as `-b -d --login -p -r -t -T -u'.`-b'`--boot'Print the date and time of last system boot.`-d'`--dead'Print information corresponding to dead processes.`-H'`--heading'Print a line of column headings.`-l'`--login'List only the entries that correspond to processes via which thesystem is waiting for a user to login. The user name is always`LOGIN'.`--lookup'Attempt to canonicalize hostnames found in utmp through a DNSlookup. This is not the default because it can cause significantdelays on systems with automatic dial-up internet access.`-m'Same as `who am i'.`-p'`--process'List active processes spawned by init.`-q'`--count'Print only the login names and the number of users logged on.Overrides all other options.`-r'`--runlevel'Print the current (and maybe previous) run-level of the initprocess.`-s'Ignored; for compatibility with other versions of `who'.`-t'`--time'Print last system clock change.`-u'After the login time, print the number of hours and minutes thatthe user has been idle. `.' means the user was active in the lastminute. `old' means the user has been idle for more than 24 hours.`-w'`-T'`--mesg'`--message'`--writable'After each login name print a character indicating the user'smessage status:`+' allowing `write' messages`-' disallowing `write' messages`?' cannot find terminal deviceAn exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: System context, Next: SELinux context, Prev: User information, Up: Top21 System context*****************This section describes commands that print or change system-wideinformation.* Menu:* arch invocation:: Print machine hardware name.* date invocation:: Print or set system date and time.* uname invocation:: Print system information.* hostname invocation:: Print or set system name.* hostid invocation:: Print numeric host identifier.* uptime invocation:: Print system uptime and loadFile: coreutils.info, Node: SELinux context, Next: Modified command invocation, Prev: System context, Up: Top22 SELinux context******************This section describes commands for operations with SELinux contexts.* Menu:* chcon invocation:: Change SELinux context of file* runcon invocation:: Run a command in specified SELinux contextFile: coreutils.info, Node: chcon invocation, Next: runcon invocation, Up: SELinux context22.1 `chcon': Change SELinux context of file.=============================================`chcon' changes the SELinux security context of the selected files.Synopses:chcon [OPTION]... CONTEXT FILE...chcon [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...chcon [OPTION]... --reference=RFILE FILE...Change the SELinux security context of each FILE to CONTEXT. With`--reference', change the security context of each FILE to that ofRFILE.The program accepts the following options. Also see *note Commonoptions::.`-h'`--no-dereference'Affect symbolic links instead of any referenced file.`--reference=RFILE'Use RFILE's security context rather than specifying a CONTEXTvalue.`-R'`--recursive'Operate on files and directories recursively.`-H'If `--recursive' (`-R') is specified and a command line argumentis a symbolic link to a directory, traverse it. *Note Traversingsymlinks::.`-L'In a recursive traversal, traverse every symbolic link to adirectory that is encountered. *Note Traversing symlinks::.`-P'Do not traverse any symbolic links. This is the default if noneof `-H', `-L', or `-P' is specified. *Note Traversing symlinks::.`-v'`--verbose'Output a diagnostic for every file processed.`-u USER'`--user=USER'Set user USER in the target security context.`-r ROLE'`--role=ROLE'Set role ROLE in the target security context.`-t TYPE'`--type=TYPE'Set type TYPE in the target security context.`-l RANGE'`--range=RANGE'Set range RANGE in the target security context.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: runcon invocation, Prev: chcon invocation, Up: SELinux context22.2 `runcon': Run a command in specified SELinux context=========================================================`runcon' runs file in specified SELinux security context.Synopses:runcon CONTEXT COMMAND [ARGS]runcon [ -c ] [-u USER] [-r ROLE] [-t TYPE] [-l RANGE] COMMAND [ARGS]Run COMMAND with completely-specified CONTEXT, or with current ortransitioned security context modified by one or more of LEVEL, ROLE,TYPE and USER.If none of `-c', `-t', `-u', `-r', or `-l' is specified, the firstargument is used as the complete context. Any additional argumentsafter COMMAND are interpreted as arguments to the command.With neither CONTEXT nor COMMAND, print the current security context.The program accepts the following options. Also see *note Commonoptions::.`-c'`--compute'Compute process transition context before modifying.`-u USER'`--user=USER'Set user USER in the target security context.`-r ROLE'`--role=ROLE'Set role ROLE in the target security context.`-t TYPE'`--type=TYPE'Set type TYPE in the target security context.`-l RANGE'`--range=RANGE'Set range RANGE in the target security context.Exit status:126 if COMMAND is found but cannot be invoked127 if `runcon' itself fails or if COMMAND cannot be foundthe exit status of COMMAND otherwiseFile: coreutils.info, Node: date invocation, Next: uname invocation, Prev: arch invocation, Up: System context22.3 `date': Print or set system date and time==============================================Synopses:date [OPTION]... [+FORMAT]date [-u|--utc|--universal] [ MMDDhhmm[[CC]YY][.ss] ]Invoking `date' with no FORMAT argument is equivalent to invoking itwith a default format that depends on the `LC_TIME' locale category.In the default C locale, this format is `'+%a %b %e %H:%M:%S %Z %Y'',so the output looks like `Thu Mar 3 13:47:51 PST 2005'.Normally, `date' uses the time zone rules indicated by the `TZ'environment variable, or the system default rules if `TZ' is not set.*Note Specifying the Time Zone with `TZ': (libc)TZ Variable.If given an argument that starts with a `+', `date' prints thecurrent date and time (or the date and time specified by the `--date'option, see below) in the format defined by that argument, which issimilar to that of the `strftime' function. Except for conversionspecifiers, which start with `%', characters in the format string areprinted unchanged. The conversion specifiers are described below.An exit status of zero indicates success, and a nonzero valueindicates failure.* Menu:* Time conversion specifiers:: %[HIklMNpPrRsSTXzZ]* Date conversion specifiers:: %[aAbBcCdDeFgGhjmuUVwWxyY]* Literal conversion specifiers:: %[%nt]* Padding and other flags:: Pad with zeros, spaces, etc.* Setting the time:: Changing the system clock.* Options for date:: Instead of the current time.* Date input formats:: Specifying date strings.* Examples of date:: Examples.File: coreutils.info, Node: Time conversion specifiers, Next: Date conversion specifiers, Up: date invocation22.3.1 Time conversion specifiers---------------------------------`date' conversion specifiers related to times.`%H'hour (`00'...`23')`%I'hour (`01'...`12')`%k'hour (` 0'...`23'). This is a GNU extension.`%l'hour (` 1'...`12'). This is a GNU extension.`%M'minute (`00'...`59')`%N'nanoseconds (`000000000'...`999999999'). This is a GNU extension.`%p'locale's equivalent of either `AM' or `PM'; blank in many locales.Noon is treated as `PM' and midnight as `AM'.`%P'like `%p', except lower case. This is a GNU extension.`%r'locale's 12-hour clock time (e.g., `11:11:04 PM')`%R'24-hour hour and minute. Same as `%H:%M'. This is a GNUextension.`%s'seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.Leap seconds are not counted unless leap second support isavailable. *Note %s-examples::, for examples. This is a GNUextension.`%S'second (`00'...`60'). This may be `60' if leap seconds aresupported.`%T'24-hour hour, minute, and second. Same as `%H:%M:%S'.`%X'locale's time representation (e.g., `23:13:48')`%z'RFC 2822/ISO 8601 style numeric time zone (e.g., `-0600' or`+0530'), or nothing if no time zone is determinable. This valuereflects the numeric time zone appropriate for the current time,using the time zone rules specified by the `TZ' environmentvariable. The time (and optionally, the time zone rules) can beoverridden by the `--date' option. This is a GNU extension.`%:z'RFC 3339/ISO 8601 style numeric time zone with `:' (e.g., `-06:00'or `+05:30'), or nothing if no time zone is determinable. This isa GNU extension.`%::z'Numeric time zone to the nearest second with `:' (e.g.,`-06:00:00' or `+05:30:00'), or nothing if no time zone isdeterminable. This is a GNU extension.`%:::z'Numeric time zone with `:' using the minimum necessary precision(e.g., `-06', `+05:30', or `-04:56:02'), or nothing if no timezone is determinable. This is a GNU extension.`%Z'alphabetic time zone abbreviation (e.g., `EDT'), or nothing if notime zone is determinable. See `%z' for how it is determined.File: coreutils.info, Node: Date conversion specifiers, Next: Literal conversion specifiers, Prev: Time conversion specifiers, Up: date invocation22.3.2 Date conversion specifiers---------------------------------`date' conversion specifiers related to dates.`%a'locale's abbreviated weekday name (e.g., `Sun')`%A'locale's full weekday name, variable length (e.g., `Sunday')`%b'locale's abbreviated month name (e.g., `Jan')`%B'locale's full month name, variable length (e.g., `January')`%c'locale's date and time (e.g., `Thu Mar 3 23:05:25 2005')`%C'century. This is like `%Y', except the last two digits areomitted. For example, it is `20' if `%Y' is `2000', and is `-0'if `%Y' is `-001'. It is normally at least two characters, but itmay be more.`%d'day of month (e.g., `01')`%D'date; same as `%m/%d/%y'`%e'day of month, space padded; same as `%_d'`%F'full date in ISO 8601 format; same as `%Y-%m-%d'. This is a goodchoice for a date format, as it is standard and is easy to sort inthe usual case where years are in the range 0000...9999. This isa GNU extension.`%g'year corresponding to the ISO week number, but without the century(range `00' through `99'). This has the same format and value as`%y', except that if the ISO week number (see `%V') belongs to theprevious or next year, that year is used instead. This is a GNUextension.`%G'year corresponding to the ISO week number. This has the sameformat and value as `%Y', except that if the ISO week number (see`%V') belongs to the previous or next year, that year is usedinstead. It is normally useful only if `%V' is also used; forexample, the format `%G-%m-%d' is probably a mistake, since itcombines the ISO week number year with the conventional month andday. This is a GNU extension.`%h'same as `%b'`%j'day of year (`001'...`366')`%m'month (`01'...`12')`%u'day of week (`1'...`7') with `1' corresponding to Monday`%U'week number of year, with Sunday as the first day of the week(`00'...`53'). Days in a new year preceding the first Sunday arein week zero.`%V'ISO week number, that is, the week number of year, with Monday asthe first day of the week (`01'...`53'). If the week containingJanuary 1 has four or more days in the new year, then it isconsidered week 1; otherwise, it is week 53 of the previous year,and the next week is week 1. (See the ISO 8601 standard.)`%w'day of week (`0'...`6') with 0 corresponding to Sunday`%W'week number of year, with Monday as first day of week(`00'...`53'). Days in a new year preceding the first Monday arein week zero.`%x'locale's date representation (e.g., `12/31/99')`%y'last two digits of year (`00'...`99')`%Y'year. This is normally at least four characters, but it may bemore. Year `0000' precedes year `0001', and year `-001' precedesyear `0000'.File: coreutils.info, Node: Literal conversion specifiers, Next: Padding and other flags, Prev: Date conversion specifiers, Up: date invocation22.3.3 Literal conversion specifiers------------------------------------`date' conversion specifiers that produce literal strings.`%%'a literal %`%n'a newline`%t'a horizontal tabFile: coreutils.info, Node: Padding and other flags, Next: Setting the time, Prev: Literal conversion specifiers, Up: date invocation22.3.4 Padding and other flags------------------------------Unless otherwise specified, `date' normally pads numeric fields withzeros, so that, for example, numeric months are always output as twodigits. Seconds since the epoch are not padded, though, since there isno natural width for them.As a GNU extension, `date' recognizes any of the following optionalflags after the `%':`-'(hyphen) Do not pad the field; useful if the output is intended forhuman consumption.`_'(underscore) Pad with spaces; useful if you need a fixed number ofcharacters in the output, but zeros are too distracting.`0'(zero) Pad with zeros even if the conversion specifier wouldnormally pad with spaces.`^'Use upper case characters if possible.`#'Use opposite case characters if possible. A field that isnormally upper case becomes lower case, and vice versa.Here are some examples of padding:date +%d/%m -d "Feb 1"=> 01/02date +%-d/%-m -d "Feb 1"=> 1/2date +%_d/%_m -d "Feb 1"=> 1/ 2As a GNU extension, you can specify the field width (after any flag,if present) as a decimal number. If the natural size of the output ofthe field has less than the specified number of characters, the resultis written right adjusted and padded to the given size. For example,`%9B' prints the right adjusted month name in a field of width 9.An optional modifier can follow the optional flag and widthspecification. The modifiers are:`E'Use the locale's alternate representation for date and time. Thismodifier applies to the `%c', `%C', `%x', `%X', `%y' and `%Y'conversion specifiers. In a Japanese locale, for example, `%Ex'might yield a date format based on the Japanese Emperors' reigns.`O'Use the locale's alternate numeric symbols for numbers. Thismodifier applies only to numeric conversion specifiers.If the format supports the modifier but no alternate representationis available, it is ignored.File: coreutils.info, Node: Setting the time, Next: Options for date, Prev: Padding and other flags, Up: date invocation22.3.5 Setting the time-----------------------If given an argument that does not start with `+', `date' sets thesystem clock to the date and time specified by that argument (asdescribed below). You must have appropriate privileges to set thesystem clock. The `--date' and `--set' options may not be used withsuch an argument. The `--universal' option may be used with such anargument to indicate that the specified date and time are relative toCoordinated Universal Time rather than to the local time zone.The argument must consist entirely of digits, which have thefollowing meaning:`MM'month`DD'day within month`hh'hour`mm'minute`CC'first two digits of year (optional)`YY'last two digits of year (optional)`ss'second (optional)The `--set' option also sets the system clock; see the next section.File: coreutils.info, Node: Options for date, Prev: Setting the time, Up: date invocation22.3.6 Options for `date'-------------------------The program accepts the following options. Also see *note Commonoptions::.`-d DATESTR'`--date=DATESTR'Display the date and time specified in DATESTR instead of thecurrent date and time. DATESTR can be in almost any commonformat. It can contain month names, time zones, `am' and `pm',`yesterday', etc. For example, `--date="2004-02-2714:19:13.489392193 +0530"' specifies the instant of time that is489,392,193 nanoseconds after February 27, 2004 at 2:19:13 PM in atime zone that is 5 hours and 30 minutes east of UTC.Note: input currently must be in locale independent format. E.g.,the LC_TIME=C below is needed to print back the correct date inmany locales:date -d "$(LC_TIME=C date)"*Note Date input formats::.`-f DATEFILE'`--file=DATEFILE'Parse each line in DATEFILE as with `-d' and display the resultingdate and time. If DATEFILE is `-', use standard input. This isuseful when you have many dates to process, because the systemoverhead of starting up the `date' executable many times can beconsiderable.`-r FILE'`--reference=FILE'Display the date and time of the last modification of FILE,instead of the current date and time.`-R'`--rfc-822'`--rfc-2822'Display the date and time using the format `%a, %d %b %Y %H:%M:%S%z', evaluated in the C locale so abbreviations are always inEnglish. For example:Fri, 09 Sep 2005 13:51:39 -0700This format conforms to Internet RFCs 2822(ftp://ftp.rfc-editor.org/in-notes/rfc2822.txt) and 822(ftp://ftp.rfc-editor.org/in-notes/rfc822.txt), the current andprevious standards for Internet email.`--rfc-3339=TIMESPEC'Display the date using a format specified by Internet RFC 3339(ftp://ftp.rfc-editor.org/in-notes/rfc3339.txt). This is a subsetof the ISO 8601 format, except that it also permits applicationsto use a space rather than a `T' to separate dates from times.Unlike the other standard formats, RFC 3339 format is alwayssuitable as input for the `--date' (`-d') and `--file' (`-f')options, regardless of the current locale.The argument TIMESPEC specifies how much of the time to include.It can be one of the following:`date'Print just the full-date, e.g., `2005-09-14'. This isequivalent to the format `%Y-%m-%d'.`seconds'Print the full-date and full-time separated by a space, e.g.,`2005-09-14 00:56:06+05:30'. The output ends with a numerictime-offset; here the `+05:30' means that local time is fivehours and thirty minutes east of UTC. This is equivalent tothe format `%Y-%m-%d %H:%M:%S%:z'.`ns'Like `seconds', but also print nanoseconds, e.g., `2005-09-1400:56:06.998458565+05:30'. This is equivalent to the format`%Y-%m-%d %H:%M:%S.%N%:z'.`-s DATESTR'`--set=DATESTR'Set the date and time to DATESTR. See `-d' above.`-u'`--utc'`--universal'Use Coordinated Universal Time (UTC) by operating as if the `TZ'environment variable were set to the string `UTC0'. CoordinatedUniversal Time is often called "Greenwich Mean Time" (GMT) forhistorical reasons.File: coreutils.info, Node: Examples of date, Up: date invocation22.3.7 Examples of `date'-------------------------Here are a few examples. Also see the documentation for the `-d'option in the previous section.* To print the date of the day before yesterday:date --date='2 days ago'* To print the date of the day three months and one day hence:date --date='3 months 1 day'* To print the day of year of Christmas in the current year:date --date='25 Dec' +%j* To print the current full month name and the day of the month:date '+%B %d'But this may not be what you want because for the first nine daysof the month, the `%d' expands to a zero-padded two-digit field,for example `date -d 1may '+%B %d'' will print `May 01'.* To print a date without the leading zero for one-digit days of themonth, you can use the (GNU extension) `-' flag to suppress thepadding altogether:date -d 1may '+%B %-d* To print the current date and time in the format required by manynon-GNU versions of `date' when setting the system clock:date +%m%d%H%M%Y.%S* To set the system clock forward by two minutes:date --set='+2 minutes'* To print the date in RFC 2822 format, use `date --rfc-2822'. Hereis some example output:Fri, 09 Sep 2005 13:51:39 -0700* To convert a date string to the number of seconds since the epoch(which is 1970-01-01 00:00:00 UTC), use the `--date' option withthe `%s' format. That can be useful in sorting and/or graphingand/or comparing data by date. The following command outputs thenumber of the seconds since the epoch for the time two minutesafter the epoch:date --date='1970-01-01 00:02:00 +0000' +%s120If you do not specify time zone information in the date string,`date' uses your computer's idea of the time zone wheninterpreting the string. For example, if your computer's timezone is that of Cambridge, Massachusetts, which was then 5 hours(i.e., 18,000 seconds) behind UTC:# local time zone useddate --date='1970-01-01 00:02:00' +%s18120* If you're sorting or graphing dated data, your raw date values maybe represented as seconds since the epoch. But few people canlook at the date `946684800' and casually note "Oh, that's thefirst second of the year 2000 in Greenwich, England."date --date='2000-01-01 UTC' +%s946684800An alternative is to use the `--utc' (`-u') option. Then you mayomit `UTC' from the date string. Although this produces the sameresult for `%s' and many other format sequences, with a time zoneoffset different from zero, it would give a different result forzone-dependent formats like `%z'.date -u --date=2000-01-01 +%s946684800To convert such an unwieldy number of seconds back to a morereadable form, use a command like this:# local time zone useddate -d '1970-01-01 UTC 946684800 seconds' +"%Y-%m-%d %T %z"1999-12-31 19:00:00 -0500Or if you do not mind depending on the `@' feature present sincecoreutils 5.3.0, you could shorten this to:date -d @946684800 +"%F %T %z"1999-12-31 19:00:00 -0500Often it is better to output UTC-relative date and time:date -u -d '1970-01-01 946684800 seconds' +"%Y-%m-%d %T %z"2000-01-01 00:00:00 +0000File: coreutils.info, Node: arch invocation, Next: date invocation, Up: System context22.4 `arch': Print machine hardware name========================================`arch' prints the machine hardware name, and is equivalent to `uname-m'. Synopsis:arch [OPTION]The program accepts the *note Common options:: only.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: uname invocation, Next: hostname invocation, Prev: date invocation, Up: System context22.5 `uname': Print system information======================================`uname' prints information about the machine and operating system it isrun on. If no options are given, `uname' acts as if the `-s' optionwere given. Synopsis:uname [OPTION]...If multiple options or `-a' are given, the selected information isprinted in this order:KERNEL-NAME NODENAME KERNEL-RELEASE KERNEL-VERSIONMACHINE PROCESSOR HARDWARE-PLATFORM OPERATING-SYSTEMThe information may contain internal spaces, so such output cannot beparsed reliably. In the following example, RELEASE is`2.2.18ss.e820-bda652a #4 SMP Tue Jun 5 11:24:08 PDT 2001':uname -a=> Linux dum 2.2.18 #4 SMP Tue Jun 5 11:24:08 PDT 2001 i686 unknown unknown GNU/LinuxThe program accepts the following options. Also see *note Commonoptions::.`-a'`--all'Print all of the below information, except omit the processor typeand the hardware platform name if they are unknown.`-i'`--hardware-platform'Print the hardware platform name (sometimes called the hardwareimplementation). Print `unknown' if the kernel does not make thisinformation easily available, as is the case with Linux kernels.`-m'`--machine'Print the machine hardware name (sometimes called the hardwareclass or hardware type).`-n'`--nodename'Print the network node hostname.`-p'`--processor'Print the processor type (sometimes called the instruction setarchitecture or ISA). Print `unknown' if the kernel does not makethis information easily available, as is the case with Linuxkernels.`-o'`--operating-system'Print the name of the operating system.`-r'`--kernel-release'Print the kernel release.`-s'`--kernel-name'Print the kernel name. POSIX 1003.1-2001 (*note Standardsconformance::) calls this "the implementation of the operatingsystem", because the POSIX specification itself has no notion of"kernel". The kernel name might be the same as the operatingsystem name printed by the `-o' or `--operating-system' option,but it might differ. Some operating systems (e.g., FreeBSD,HP-UX) have the same name as their underlying kernels; others(e.g., GNU/Linux, Solaris) do not.`-v'`--kernel-version'Print the kernel version.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: hostname invocation, Next: hostid invocation, Prev: uname invocation, Up: System context22.6 `hostname': Print or set system name=========================================With no arguments, `hostname' prints the name of the current hostsystem. With one argument, it sets the current host name to thespecified string. You must have appropriate privileges to set the hostname. Synopsis:hostname [NAME]The only options are `--help' and `--version'. *Note Commonoptions::.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: hostid invocation, Next: uptime invocation, Prev: hostname invocation, Up: System context22.7 `hostid': Print numeric host identifier.=============================================`hostid' prints the numeric identifier of the current host inhexadecimal. This command accepts no arguments. The only options are`--help' and `--version'. *Note Common options::.For example, here's what it prints on one system I use:$ hostid1bac013dOn that system, the 32-bit quantity happens to be closely related tothe system's Internet address, but that isn't always the case.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: uptime invocation, Prev: hostid invocation, Up: System context22.8 `uptime': Print system uptime and load===========================================`uptime' prints the current time, the system's uptime, the number oflogged-in users and the current load average.If an argument is specified, it is used as the file to be read todiscover how many users are logged in. If no argument is specified, asystem default is used (`uptime --help' indicates the default setting).The only options are `--help' and `--version'. *Note Commonoptions::.For example, here's what it prints right now on one system I use:$ uptime14:07 up 3:35, 3 users, load average: 1.39, 1.15, 1.04The precise method of calculation of load average varies somewhatbetween systems. Some systems calculate it as the average number ofrunnable processes over the last 1, 5 and 15 minutes, but some systemsalso include processes in the uninterruptible sleep state (that is,those processes which are waiting for disk I/O). The Linux kernelincludes uninterruptible processes.File: coreutils.info, Node: Modified command invocation, Next: Process control, Prev: SELinux context, Up: Top23 Modified command invocation******************************This section describes commands that run other commands in some contextdifferent than the current one: a modified environment, as a differentuser, etc.* Menu:* chroot invocation:: Modify the root directory.* env invocation:: Modify environment variables.* nice invocation:: Modify niceness.* nohup invocation:: Immunize to hangups.* su invocation:: Modify user and group ID.* timeout invocation:: Run with time limit.File: coreutils.info, Node: chroot invocation, Next: env invocation, Up: Modified command invocation23.1 `chroot': Run a command with a different root directory============================================================`chroot' runs a command with a specified root directory. On manysystems, only the super-user can do this.(1) Synopses:chroot NEWROOT [COMMAND [ARGS]...]chroot OPTIONOrdinarily, file names are looked up starting at the root of thedirectory structure, i.e., `/'. `chroot' changes the root to thedirectory NEWROOT (which must exist) and then runs COMMAND withoptional ARGS. If COMMAND is not specified, the default is the valueof the `SHELL' environment variable or `/bin/sh' if not set, invokedwith the `-i' option. COMMAND must not be a special built-in utility(*note Special built-in utilities::).The only options are `--help' and `--version'. *Note Commonoptions::. Options must precede operands.Here are a few tips to help avoid common problems in using chroot.To start with a simple example, make COMMAND refer to a staticallylinked binary. If you were to use a dynamically linked executable, thenyou'd have to arrange to have the shared libraries in the right placeunder your new root directory.For example, if you create a statically linked `ls' executable, andput it in `/tmp/empty', you can run this command as root:$ chroot /tmp/empty /ls -Rl /Then you'll see output like this:/:total 1023-rwxr-xr-x 1 0 0 1041745 Aug 16 11:17 lsIf you want to use a dynamically linked executable, say `bash', thenfirst run `ldd bash' to see what shared objects it needs. Then, inaddition to copying the actual binary, also copy the listed files tothe required positions under your intended new root directory.Finally, if the executable requires any other files (e.g., data, state,device files), copy them into place, too.Exit status:1 if `chroot' itself fails126 if COMMAND is found but cannot be invoked127 if COMMAND cannot be foundthe exit status of COMMAND otherwise---------- Footnotes ----------(1) However, some systems (e.g., FreeBSD) can be configured to allowcertain regular users to use the `chroot' system call, and hence to runthis program. Also, on Cygwin, anyone can run the `chroot' command,because the underlying function is non-privileged due to lack ofsupport in MS-Windows.File: coreutils.info, Node: env invocation, Next: nice invocation, Prev: chroot invocation, Up: Modified command invocation23.2 `env': Run a command in a modified environment===================================================`env' runs a command with a modified environment. Synopses:env [OPTION]... [NAME=VALUE]... [COMMAND [ARGS]...]envOperands of the form `VARIABLE=VALUE' set the environment variableVARIABLE to value VALUE. VALUE may be empty (`VARIABLE='). Setting avariable to an empty value is different from unsetting it. Theseoperands are evaluated left-to-right, so if two operands mention thesame variable the earlier is ignored.Environment variable names can be empty, and can contain anycharacters other than `=' and ASCII NUL. However, it is wise to limityourself to names that consist solely of underscores, digits, and ASCIIletters, and that begin with a non-digit, as applications like theshell do not work well with other names.The first operand that does not contain the character `=' specifiesthe program to invoke; it is searched for according to the `PATH'environment variable. Any remaining arguments are passed as argumentsto that program. The program should not be a special built-in utility(*note Special built-in utilities::).If no command name is specified following the environmentspecifications, the resulting environment is printed. This is likespecifying the `printenv' program.The program accepts the following options. Also see *note Commonoptions::. Options must precede operands.`-u NAME'`--unset=NAME'Remove variable NAME from the environment, if it was in theenvironment.`-'`-i'`--ignore-environment'Start with an empty environment, ignoring the inheritedenvironment.Exit status:0 if no COMMAND is specified and the environment is output1 if `env' itself fails126 if COMMAND is found but cannot be invoked127 if COMMAND cannot be foundthe exit status of COMMAND otherwiseFile: coreutils.info, Node: nice invocation, Next: nohup invocation, Prev: env invocation, Up: Modified command invocation23.3 `nice': Run a command with modified niceness=================================================`nice' prints or modifies a process's "niceness", a parameter thataffects whether the process is scheduled favorably. Synopsis:nice [OPTION]... [COMMAND [ARG]...]If no arguments are given, `nice' prints the current niceness.Otherwise, `nice' runs the given COMMAND with its niceness adjusted.By default, its niceness is incremented by 10.Niceness values range at least from -20 (process has high priorityand gets more resources, thus slowing down other processes) through 19(process has lower priority and runs slowly itself, but has less impacton the speed of other running processes). Some systems may have awider range of nicenesses; conversely, other systems may enforce morerestrictive limits. An attempt to set the niceness outside thesupported range is treated as an attempt to use the minimum or maximumsupported value.A niceness should not be confused with a scheduling priority, whichlets applications determine the order in which threads are scheduled torun. Unlike a priority, a niceness is merely advice to the scheduler,which the scheduler is free to ignore. Also, as a point ofterminology, POSIX defines the behavior of `nice' in terms of a "nicevalue", which is the nonnegative difference between a niceness and theminimum niceness. Though `nice' conforms to POSIX, its documentationand diagnostics use the term "niceness" for compatibility withhistorical practice.COMMAND must not be a special built-in utility (*note Specialbuilt-in utilities::).Due to shell aliases and built-in `nice' command, using an unadorned`nice' interactively or in a script may get you different functionalitythan that described here. Invoke it via `env' (i.e., `env nice ...')to avoid interference from the shell.The program accepts the following option. Also see *note Commonoptions::. Options must precede operands.`-n ADJUSTMENT'`--adjustment=ADJUSTMENT'Add ADJUSTMENT instead of 10 to the command's niceness. IfADJUSTMENT is negative and you lack appropriate privileges, `nice'issues a warning but otherwise acts as if you specified a zeroadjustment.For compatibility `nice' also supports an obsolete option syntax`-ADJUSTMENT'. New scripts should use `-n ADJUSTMENT' instead.Exit status:0 if no COMMAND is specified and the niceness is output1 if `nice' itself fails126 if COMMAND is found but cannot be invoked127 if COMMAND cannot be foundthe exit status of COMMAND otherwiseIt is sometimes useful to run a non-interactive program with reducedniceness.$ nice factor 4611686018427387903Since `nice' prints the current niceness, you can invoke it throughitself to demonstrate how it works.The default behavior is to increase the niceness by `10':$ nice0$ nice nice10$ nice -n 10 nice10The ADJUSTMENT is relative to the current niceness. In the nextexample, the first `nice' invocation runs the second one with niceness10, and it in turn runs the final one with a niceness that is 3 more:$ nice nice -n 3 nice13Specifying a niceness larger than the supported range is the same asspecifying the maximum supported value:$ nice -n 10000000000 nice19Only a privileged user may run a process with lower niceness:$ nice -n -1 nicenice: cannot set niceness: Permission denied0$ sudo nice -n -1 nice-1File: coreutils.info, Node: nohup invocation, Next: su invocation, Prev: nice invocation, Up: Modified command invocation23.4 `nohup': Run a command immune to hangups=============================================`nohup' runs the given COMMAND with hangup signals ignored, so that thecommand can continue running in the background after you log out.Synopsis:nohup COMMAND [ARG]...If standard input is a terminal, it is redirected from `/dev/null'so that terminal sessions do not mistakenly consider the terminal to beused by the command. This is a GNU extension; programs intended to beportable to non-GNU hosts should use `nohup COMMAND [ARG]... </dev/null'instead.If standard output is a terminal, the command's standard output isappended to the file `nohup.out'; if that cannot be written to, it isappended to the file `$HOME/nohup.out'; and if that cannot be writtento, the command is not run. Any `nohup.out' or `$HOME/nohup.out' filecreated by `nohup' is made readable and writable only to the user,regardless of the current umask settings.If standard error is a terminal, it is normally redirected to thesame file descriptor as the (possibly-redirected) standard output.However, if standard output is closed, standard error terminal outputis instead appended to the file `nohup.out' or `$HOME/nohup.out' asabove.To capture the command's output to a file other than `nohup.out' youcan redirect it. For example, to capture the output of `make':nohup make > make.log`nohup' does not automatically put the command it runs in thebackground; you must do that explicitly, by ending the command linewith an `&'. Also, `nohup' does not alter the niceness of COMMAND; use`nice' for that, e.g., `nohup nice COMMAND'.COMMAND must not be a special built-in utility (*note Specialbuilt-in utilities::).The only options are `--help' and `--version'. *Note Commonoptions::. Options must precede operands.Exit status:126 if COMMAND is found but cannot be invoked127 if `nohup' itself fails or if COMMAND cannot be foundthe exit status of COMMAND otherwiseFile: coreutils.info, Node: su invocation, Next: timeout invocation, Prev: nohup invocation, Up: Modified command invocation23.5 `su': Run a command with substitute user and group ID==========================================================`su' allows one user to temporarily become another user. It runs acommand (often an interactive shell) with the real and effective userID, group ID, and supplemental groups of a given USER. Synopsis:su [OPTION]... [USER [ARG]...]If no USER is given, the default is `root', the super-user. Theshell to use is taken from USER's `passwd' entry, or `/bin/sh' if noneis specified there. If USER has a password, `su' prompts for thepassword unless run by a user with effective user ID of zero (thesuper-user).By default, `su' does not change the current directory. It sets theenvironment variables `HOME' and `SHELL' from the password entry forUSER, and if USER is not the super-user, sets `USER' and `LOGNAME' toUSER. By default, the shell is not a login shell.Any additional ARGs are passed as additional arguments to the shell.GNU `su' does not treat `/bin/sh' or any other shells specially(e.g., by setting `argv[0]' to `-su', passing `-c' only to certainshells, etc.).`su' can optionally be compiled to use `syslog' to report failed,and optionally successful, `su' attempts. (If the system supports`syslog'.) However, GNU `su' does not check if the user is a member ofthe `wheel' group; see below.The program accepts the following options. Also see *note Commonoptions::.`-c COMMAND'`--command=COMMAND'Pass COMMAND, a single command line to run, to the shell with a`-c' option instead of starting an interactive shell.`-f'`--fast'Pass the `-f' option to the shell. This probably only makes senseif the shell run is `csh' or `tcsh', for which the `-f' optionprevents reading the startup file (`.cshrc'). With Bourne-likeshells, the `-f' option disables file name pattern expansion(globbing), which is not likely to be useful.`-'`-l'`--login'Make the shell a login shell. This means the following. Unset allenvironment variables except `TERM', `HOME', and `SHELL' (whichare set as described above), and `USER' and `LOGNAME' (which areset, even for the super-user, as described above), and set `PATH'to a compiled-in default value. Change to USER's home directory.Prepend `-' to the shell's name, intended to make it read itslogin startup file(s).`-m'`-p'`--preserve-environment'Do not change the environment variables `HOME', `USER', `LOGNAME',or `SHELL'. Run the shell given in the environment variable`SHELL' instead of the shell from USER's passwd entry, unless theuser running `su' is not the super-user and USER's shell isrestricted. A "restricted shell" is one that is not listed in thefile `/etc/shells', or in a compiled-in list if that file does notexist. Parts of what this option does can be overridden by`--login' and `--shell'.`-s SHELL'`--shell=SHELL'Run SHELL instead of the shell from USER's passwd entry, unlessthe user running `su' is not the super-user and USER's shell isrestricted (see `-m' just above).Exit status:1 if `su' itself fails126 if subshell is found but cannot be invoked127 if subshell cannot be foundthe exit status of the subshell otherwise23.5.1 Why GNU `su' does not support the `wheel' group------------------------------------------------------(This section is by Richard Stallman.)Sometimes a few of the users try to hold total power over all therest. For example, in 1984, a few users at the MIT AI lab decided toseize power by changing the operator password on the Twenex system andkeeping it secret from everyone else. (I was able to thwart this coupand give power back to the users by patching the kernel, but I wouldn'tknow how to do that in Unix.)However, occasionally the rulers do tell someone. Under the usual`su' mechanism, once someone learns the root password who sympathizeswith the ordinary users, he or she can tell the rest. The "wheelgroup" feature would make this impossible, and thus cement the power ofthe rulers.I'm on the side of the masses, not that of the rulers. If you areused to supporting the bosses and sysadmins in whatever they do, youmight find this idea strange at first.File: coreutils.info, Node: timeout invocation, Prev: su invocation, Up: Modified command invocation23.6 `timeout': Run a command with a time limit===============================================`timeout' runs the given COMMAND and kills it if it is still runningafter the specified time interval. Synopsis:timeout [OPTION] NUMBER[smhd] COMMAND [ARG]...NUMBER is an integer followed by an optional unit; the default isseconds. The units are:`s'seconds`m'minutes`h'hours`d'daysCOMMAND must not be a special built-in utility (*note Specialbuilt-in utilities::).The program accepts the following option. Also see *note Commonoptions::. Options must precede operands.`-s SIGNAL'`--signal=SIGNAL'Send this SIGNAL to COMMAND on timeout, rather than the default`TERM' signal. SIGNAL may be a name like `HUP' or a number. Alsosee *Note Signal specifications::.Exit status:124 if COMMAND times out125 if `timeout' itself fails126 if COMMAND is found but cannot be invoked127 if COMMAND cannot be foundthe exit status of COMMAND otherwiseFile: coreutils.info, Node: Process control, Next: Delaying, Prev: Modified command invocation, Up: Top24 Process control******************* Menu:* kill invocation:: Sending a signal to processes.File: coreutils.info, Node: kill invocation, Up: Process control24.1 `kill': Send a signal to processes=======================================The `kill' command sends a signal to processes, causing them toterminate or otherwise act upon receiving the signal in some way.Alternatively, it lists information about signals. Synopses:kill [-s SIGNAL | --signal SIGNAL | -SIGNAL] PID...kill [-l | --list | -t | --table] [SIGNAL]...Due to shell aliases and built-in `kill' command, using an unadorned`kill' interactively or in a script may get you different functionalitythan that described here. Invoke it via `env' (i.e., `env kill ...')to avoid interference from the shell.The first form of the `kill' command sends a signal to all PIDarguments. The default signal to send if none is specified is `TERM'.The special signal number `0' does not denote a valid signal, but canbe used to test whether the PID arguments specify processes to which asignal could be sent.If PID is positive, the signal is sent to the process with theprocess ID PID. If PID is zero, the signal is sent to all processes inthe process group of the current process. If PID is -1, the signal issent to all processes for which the user has permission to send asignal. If PID is less than -1, the signal is sent to all processes inthe process group that equals the absolute value of PID.If PID is not positive, a system-dependent set of system processesis excluded from the list of processes to which the signal is sent.If a negative PID argument is desired as the first one, it should bepreceded by `--'. However, as a common extension to POSIX, `--' is notrequired with `kill -SIGNAL -PID'. The following commands areequivalent:kill -15 -1kill -TERM -1kill -s TERM -- -1kill -- -1The first form of the `kill' command succeeds if every PID argumentspecifies at least one process that the signal was sent to.The second form of the `kill' command lists signal information.Either the `-l' or `--list' option, or the `-t' or `--table' optionmust be specified. Without any SIGNAL argument, all supported signalsare listed. The output of `-l' or `--list' is a list of the signalnames, one per line; if SIGNAL is already a name, the signal number isprinted instead. The output of `-t' or `--table' is a table of signalnumbers, names, and descriptions. This form of the `kill' commandsucceeds if all SIGNAL arguments are valid and if there is no outputerror.The `kill' command also supports the `--help' and `--version'options. *Note Common options::.A SIGNAL may be a signal name like `HUP', or a signal number like`1', or an exit status of a process terminated by the signal. A signalname can be given in canonical form or prefixed by `SIG'. The case ofthe letters is ignored, except for the `-SIGNAL' option which must useupper case to avoid ambiguity with lower case option letters. For alist of supported signal names and numbers see *Note Signalspecifications::.File: coreutils.info, Node: Delaying, Next: Numeric operations, Prev: Process control, Up: Top25 Delaying************ Menu:* sleep invocation:: Delay for a specified time.File: coreutils.info, Node: sleep invocation, Up: Delaying25.1 `sleep': Delay for a specified time========================================`sleep' pauses for an amount of time specified by the sum of the valuesof the command line arguments. Synopsis:sleep NUMBER[smhd]...Each argument is a number followed by an optional unit; the defaultis seconds. The units are:`s'seconds`m'minutes`h'hours`d'daysHistorical implementations of `sleep' have required that NUMBER bean integer, and only accepted a single argument without a suffix.However, GNU `sleep' accepts arbitrary floating point numbers (using aperiod before any fractional digits).The only options are `--help' and `--version'. *Note Commonoptions::.Due to shell aliases and built-in `sleep' command, using anunadorned `sleep' interactively or in a script may get you differentfunctionality than that described here. Invoke it via `env' (i.e.,`env sleep ...') to avoid interference from the shell.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: Numeric operations, Next: File permissions, Prev: Delaying, Up: Top26 Numeric operations*********************These programs do numerically-related operations.* Menu:* factor invocation:: Show factors of numbers.* seq invocation:: Print sequences of numbers.File: coreutils.info, Node: factor invocation, Next: seq invocation, Up: Numeric operations26.1 `factor': Print prime factors==================================`factor' prints prime factors. Synopses:factor [NUMBER]...factor OPTIONIf no NUMBER is specified on the command line, `factor' readsnumbers from standard input, delimited by newlines, tabs, or spaces.The `factor' command supports only a small number of options:`--help'Print a short help on standard output, then exit without furtherprocessing.`--version'Print the program version on standard output, then exit withoutfurther processing.Factoring the product of the eighth and ninth Mersenne primes takesabout 30 milliseconds of CPU time on a 2.2 GHz Athlon.M8=`echo 2^31-1|bc` ; M9=`echo 2^61-1|bc`/usr/bin/time -f '%U' factor $(echo "$M8 * $M9" | bc)4951760154835678088235319297: 2147483647 23058430092136939510.03Similarly, factoring the eighth Fermat number 2^256+1 takes about 20seconds on the same machine.Factoring large prime numbers is, in general, hard. The Pollard Rhoalgorithm used by `factor' is particularly effective for numbers withrelatively small factors. If you wish to factor large numbers which donot have small factors (for example, numbers which are the product oftwo large primes), other methods are far better.If `factor' is built without using GNU MP, only single-precisionarithmetic is available, and so large numbers (typically 2^64 andabove) will not be supported. The single-precision code uses analgorithm which is designed for factoring smaller numbers.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: seq invocation, Prev: factor invocation, Up: Numeric operations26.2 `seq': Print numeric sequences===================================`seq' prints a sequence of numbers to standard output. Synopses:seq [OPTION]... LASTseq [OPTION]... FIRST LASTseq [OPTION]... FIRST INCREMENT LAST`seq' prints the numbers from FIRST to LAST by INCREMENT. Bydefault, each number is printed on a separate line. When INCREMENT isnot specified, it defaults to `1', even when FIRST is larger than LAST.FIRST also defaults to `1'. So `seq 1' prints `1', but `seq 0' and`seq 10 5' produce no output. Floating-point numbers may be specified(using a period before any fractional digits).The program accepts the following options. Also see *note Commonoptions::. Options must precede operands.`-f FORMAT'`--format=FORMAT'Print all numbers using FORMAT. FORMAT must contain exactly oneof the `printf'-style floating point conversion specifications`%a', `%e', `%f', `%g', `%A', `%E', `%F', `%G'. The `%' may befollowed by zero or more flags taken from the set `-+#0 '', thenan optional width containing one or more digits, then an optionalprecision consisting of a `.' followed by zero or more digits.FORMAT may also contain any number of `%%' conversionspecifications. All conversion specifications have the samemeaning as with `printf'.The default format is derived from FIRST, STEP, and LAST. Ifthese all use a fixed point decimal representation, the defaultformat is `%.Pf', where P is the minimum precision that canrepresent the output numbers exactly. Otherwise, the defaultformat is `%g'.`-s STRING'`--separator=STRING'Separate numbers with STRING; default is a newline. The outputalways terminates with a newline.`-w'`--equal-width'Print all numbers with the same width, by padding with leadingzeros. FIRST, STEP, and LAST should all use a fixed point decimalrepresentation. (To have other kinds of padding, use `--format').You can get finer-grained control over output with `-f':$ seq -f '(%9.2E)' -9e5 1.1e6 1.3e6(-9.00E+05)( 2.00E+05)( 1.30E+06)If you want hexadecimal integer output, you can use `printf' toperform the conversion:$ printf '%x\n' `seq 1048575 1024 1050623`fffff1003ff1007ffFor very long lists of numbers, use xargs to avoid systemlimitations on the length of an argument list:$ seq 1000000 | xargs printf '%x\n' | tail -n 3f423ef423ff4240To generate octal output, use the printf `%o' format instead of `%x'.On most systems, seq can produce whole-number output for values up toat least 2^53. Larger integers are approximated. The details differdepending on your floating-point implementation, but a common case isthat `seq' works with integers through 2^64, and larger integers maynot be numerically correct:$ seq 18446744073709551616 1 18446744073709551618184467440737095516161844674407370955161618446744073709551618Be careful when using `seq' with outlandish values: otherwise youmay see surprising results, as `seq' uses floating point internally.For example, on the x86 platform, where the internal representationuses a 64-bit fraction, the command:seq 1 0.0000000000000000001 1.0000000000000000009outputs 1.0000000000000000007 twice and skips 1.0000000000000000008.An exit status of zero indicates success, and a nonzero valueindicates failure.File: coreutils.info, Node: File permissions, Next: Date input formats, Prev: Numeric operations, Up: Top27 File permissions*******************Each file has a set of "file mode bits" that control the kinds ofaccess that users have to that file. They can be represented either insymbolic form or as an octal number.* Menu:* Mode Structure:: Structure of file mode bits.* Symbolic Modes:: Mnemonic representation of file mode bits.* Numeric Modes:: File mode bits as octal numbers.* Directory Setuid and Setgid:: Set-user-ID and set-group-ID on directories.File: coreutils.info, Node: Mode Structure, Next: Symbolic Modes, Up: File permissions27.1 Structure of File Mode Bits================================The file mode bits have two parts: the "file permission bits", whichcontrol ordinary access to the file, and "special mode bits", whichaffect only some files.There are three kinds of permissions that a user can have for a file:1. permission to read the file. For directories, this meanspermission to list the contents of the directory.2. permission to write to (change) the file. For directories, thismeans permission to create and remove files in the directory.3. permission to execute the file (run it as a program). Fordirectories, this means permission to access files in thedirectory.There are three categories of users who may have differentpermissions to perform any of the above operations on a file:1. the file's owner;2. other users who are in the file's group;3. everyone else.Files are given an owner and group when they are created. Usuallythe owner is the current user and the group is the group of thedirectory the file is in, but this varies with the operating system, thefile system the file is created on, and the way the file is created.You can change the owner and group of a file by using the `chown' and`chgrp' commands.In addition to the three sets of three permissions listed above, thefile mode bits have three special components, which affect onlyexecutable files (programs) and, on most systems, directories:1. Set the process's effective user ID to that of the file uponexecution (called the "set-user-ID bit", or sometimes the "setuidbit"). For directories on a few systems, give files created inthe directory the same owner as the directory, no matter whocreates them, and set the set-user-ID bit of newly-createdsubdirectories.2. Set the process's effective group ID to that of the file uponexecution (called the "set-group-ID bit", or sometimes the "setgidbit"). For directories on most systems, give files created in thedirectory the same group as the directory, no matter what groupthe user who creates them is in, and set the set-group-ID bit ofnewly-created subdirectories.3. Prevent unprivileged users from removing or renaming a file in adirectory unless they own the file or the directory; this iscalled the "restricted deletion flag" for the directory, and iscommonly found on world-writable directories like `/tmp'.For regular files on some older systems, save the program's textimage on the swap device so it will load more quickly when run;this is called the "sticky bit".In addition to the file mode bits listed above, there may be fileattributes specific to the file system, e.g., access control lists(ACLs), whether a file is compressed, whether a file can be modified(immutability), and whether a file can be dumped. These are usuallyset using programs specific to the file system. For example:ext2On GNU and GNU/Linux the file attributes specific to the ext2 filesystem are set using `chattr'.FFSOn FreeBSD the file flags specific to the FFS file system are setusing `chflags'.Even if a file's mode bits allow an operation on that file, thatoperation may still fail, because:* the file-system-specific attributes or flags do not permit it; or* the file system is mounted as read-only.For example, if the immutable attribute is set on a file, it cannotbe modified, regardless of the fact that you may have just run `chmoda+w FILE'.File: coreutils.info, Node: Symbolic Modes, Next: Numeric Modes, Prev: Mode Structure, Up: File permissions27.2 Symbolic Modes==================="Symbolic modes" represent changes to files' mode bits as operations onsingle-character symbols. They allow you to modify either all orselected parts of files' mode bits, optionally based on their previousvalues, and perhaps on the current `umask' as well (*note Umask andProtection::).The format of symbolic modes is:[ugoa...][+-=]PERMS...[,...]where PERMS is either zero or more letters from the set `rwxXst', or asingle letter from the set `ugo'.The following sections describe the operators and other details ofsymbolic modes.* Menu:* Setting Permissions:: Basic operations on permissions.* Copying Permissions:: Copying existing permissions.* Changing Special Mode Bits:: Special mode bits.* Conditional Executability:: Conditionally affecting executability.* Multiple Changes:: Making multiple changes.* Umask and Protection:: The effect of the umask.File: coreutils.info, Node: Setting Permissions, Next: Copying Permissions, Up: Symbolic Modes27.2.1 Setting Permissions--------------------------The basic symbolic operations on a file's permissions are adding,removing, and setting the permission that certain users have to read,write, and execute or search the file. These operations have thefollowing format:USERS OPERATION PERMISSIONSThe spaces between the three parts above are shown for readability only;symbolic modes cannot contain spaces.The USERS part tells which users' access to the file is changed. Itconsists of one or more of the following letters (or it can be empty;*note Umask and Protection::, for a description of what happens then).When more than one of these letters is given, the order that they arein does not matter.`u'the user who owns the file;`g'other users who are in the file's group;`o'all other users;`a'all users; the same as `ugo'.The OPERATION part tells how to change the affected users' access tothe file, and is one of the following symbols:`+'to add the PERMISSIONS to whatever permissions the USERS alreadyhave for the file;`-'to remove the PERMISSIONS from whatever permissions the USERSalready have for the file;`='to make the PERMISSIONS the only permissions that the USERS havefor the file.The PERMISSIONS part tells what kind of access to the file should bechanged; it is normally zero or more of the following letters. As withthe USERS part, the order does not matter when more than one letter isgiven. Omitting the PERMISSIONS part is useful only with the `='operation, where it gives the specified USERS no access at all to thefile.`r'the permission the USERS have to read the file;`w'the permission the USERS have to write to the file;`x'the permission the USERS have to execute the file, or search it ifit is a directory.For example, to give everyone permission to read and write a regularfile, but not to execute it, use:a=rwTo remove write permission for all users other than the file'sowner, use:go-wThe above command does not affect the access that the owner of the filehas to it, nor does it affect whether other users can read or executethe file.To give everyone except a file's owner no permission to do anythingwith that file, use the mode below. Other users could still remove thefile, if they have write permission on the directory it is in.go=Another way to specify the same thing is:og-rwxFile: coreutils.info, Node: Copying Permissions, Next: Changing Special Mode Bits, Prev: Setting Permissions, Up: Symbolic Modes27.2.2 Copying Existing Permissions-----------------------------------You can base a file's permissions on its existing permissions. To dothis, instead of using a series of `r', `w', or `x' letters after theoperator, you use the letter `u', `g', or `o'. For example, the modeo+gadds the permissions for users who are in a file's group to thepermissions that other users have for the file. Thus, if the filestarted out as mode 664 (`rw-rw-r--'), the above mode would change itto mode 666 (`rw-rw-rw-'). If the file had started out as mode 741(`rwxr----x'), the above mode would change it to mode 745(`rwxr--r-x'). The `-' and `=' operations work analogously.File: coreutils.info, Node: Changing Special Mode Bits, Next: Conditional Executability, Prev: Copying Permissions, Up: Symbolic Modes27.2.3 Changing Special Mode Bits---------------------------------In addition to changing a file's read, write, and execute/searchpermissions, you can change its special mode bits. *Note ModeStructure::, for a summary of these special mode bits.To change the file mode bits to set the user ID on execution, use`u' in the USERS part of the symbolic mode and `s' in the PERMISSIONSpart.To change the file mode bits to set the group ID on execution, use`g' in the USERS part of the symbolic mode and `s' in the PERMISSIONSpart.To set both user and group ID on execution, omit the USERS part ofthe symbolic mode (or use `a') and use `s' in the PERMISSIONS part.To change the file mode bits to set the restricted deletion flag orsticky bit, omit the USERS part of the symbolic mode (or use `a') anduse `t' in the PERMISSIONS part.For example, to set the set-user-ID mode bit of a program, you canuse the mode:u+sTo remove both set-user-ID and set-group-ID mode bits from it, youcan use the mode:a-sTo set the restricted deletion flag or sticky bit, you can use themode:+tThe combination `o+s' has no effect. On GNU systems thecombinations `u+t' and `g+t' have no effect, and `o+t' acts like plain`+t'.The `=' operator is not very useful with special mode bits. Forexample, the mode:o=tdoes set the restricted deletion flag or sticky bit, but it alsoremoves all read, write, and execute/search permissions that users notin the file's group might have had for it.*Note Directory Setuid and Setgid::, for additional rules concerningset-user-ID and set-group-ID bits and directories.File: coreutils.info, Node: Conditional Executability, Next: Multiple Changes, Prev: Changing Special Mode Bits, Up: Symbolic Modes27.2.4 Conditional Executability--------------------------------There is one more special type of symbolic permission: if you use `X'instead of `x', execute/search permission is affected only if the fileis a directory or already had execute permission.For example, this mode:a+Xgives all users permission to search directories, or to execute files ifanyone could execute them before.File: coreutils.info, Node: Multiple Changes, Next: Umask and Protection, Prev: Conditional Executability, Up: Symbolic Modes27.2.5 Making Multiple Changes------------------------------The format of symbolic modes is actually more complex than describedabove (*note Setting Permissions::). It provides two ways to makemultiple changes to files' mode bits.The first way is to specify multiple OPERATION and PERMISSIONS partsafter a USERS part in the symbolic mode.For example, the mode:og+rX-wgives users other than the owner of the file read permission and, if itis a directory or if someone already had execute permission to it,gives them execute/search permission; and it also denies them writepermission to the file. It does not affect the permission that theowner of the file has for it. The above mode is equivalent to the twomodes:og+rXog-wThe second way to make multiple changes is to specify more than onesimple symbolic mode, separated by commas. For example, the mode:a+r,go-wgives everyone permission to read the file and removes write permissionon it for all users except its owner. Another example:u=rwx,g=rx,o=sets all of the permission bits for the file explicitly. (It givesusers who are not in the file's group no permission at all for it.)The two methods can be combined. The mode:a+r,g+x-wgives all users permission to read the file, and gives users who are inthe file's group permission to execute/search it as well, but notpermission to write to it. The above mode could be written in severaldifferent ways; another is:u+r,g+rx,o+r,g-wFile: coreutils.info, Node: Umask and Protection, Prev: Multiple Changes, Up: Symbolic Modes27.2.6 The Umask and Protection-------------------------------If the USERS part of a symbolic mode is omitted, it defaults to `a'(affect all users), except that any permissions that are _set_ in thesystem variable `umask' are _not affected_. The value of `umask' canbe set using the `umask' command. Its default value varies from systemto system.Omitting the USERS part of a symbolic mode is generally not usefulwith operations other than `+'. It is useful with `+' because itallows you to use `umask' as an easily customizable protection againstgiving away more permission to files than you intended to.As an example, if `umask' has the value 2, which removes writepermission for users who are not in the file's group, then the mode:+wadds permission to write to the file to its owner and to other users whoare in the file's group, but _not_ to other users. In contrast, themode:a+wignores `umask', and _does_ give write permission for the file to allusers.File: coreutils.info, Node: Numeric Modes, Next: Directory Setuid and Setgid, Prev: Symbolic Modes, Up: File permissions27.3 Numeric Modes==================As an alternative to giving a symbolic mode, you can give an octal(base 8) number that represents the mode. This number is alwaysinterpreted in octal; you do not have to add a leading `0', as you doin C. Mode `0055' is the same as mode `55'.A numeric mode is usually shorter than the corresponding symbolicmode, but it is limited in that normally it cannot take into account theprevious file mode bits; it can only set them absolutely. (Asdiscussed in the next section, the set-user-ID and set-group-ID bits ofdirectories are an exception to this general limitation.)The permissions granted to the user, to other users in the file'sgroup, and to other users not in the file's group each require threebits, which are represented as one octal digit. The three special modebits also require one bit each, and they are as a group represented asanother octal digit. Here is how the bits are arranged, starting withthe lowest valued bit:Value in CorrespondingMode Mode BitOther users not in the file's group:1 Execute/search2 Write4 ReadOther users in the file's group:10 Execute/search20 Write40 ReadThe file's owner:100 Execute/search200 Write400 ReadSpecial mode bits:1000 Restricted deletion flag or sticky bit2000 Set group ID on execution4000 Set user ID on executionFor example, numeric mode `4755' corresponds to symbolic mode`u=rwxs,go=rx', and numeric mode `664' corresponds to symbolic mode`ug=rw,o=r'. Numeric mode `0' corresponds to symbolic mode `a='.File: coreutils.info, Node: Directory Setuid and Setgid, Prev: Numeric Modes, Up: File permissions27.4 Directories and the Set-User-ID and Set-Group-ID Bits==========================================================On most systems, if a directory's set-group-ID bit is set, newlycreated subfiles inherit the same group as the directory, and newlycreated subdirectories inherit the set-group-ID bit of the parentdirectory. On a few systems, a directory's set-user-ID bit has asimilar effect on the ownership of new subfiles and the set-user-IDbits of new subdirectories. These mechanisms let users share filesmore easily, by lessening the need to use `chmod' or `chown' to sharenew files.These convenience mechanisms rely on the set-user-ID and set-group-IDbits of directories. If commands like `chmod' and `mkdir' routinelycleared these bits on directories, the mechanisms would be lessconvenient and it would be harder to share files. Therefore, a commandlike `chmod' does not affect the set-user-ID or set-group-ID bits of adirectory unless the user specifically mentions them in a symbolicmode, or sets them in a numeric mode. For example, on systems thatsupport set-group-ID inheritance:# These commands leave the set-user-ID and# set-group-ID bits of the subdirectories alone,# so that they retain their default values.mkdir A B Cchmod 755 Achmod 0755 Bchmod u=rwx,go=rx Cmkdir -m 755 Dmkdir -m 0755 Emkdir -m u=rwx,go=rx FIf you want to try to set these bits, you must mention themexplicitly in the symbolic or numeric modes, e.g.:# These commands try to set the set-user-ID# and set-group-ID bits of the subdirectories.mkdir G Hchmod 6755 Gchmod u=rwx,go=rx,a+s Hmkdir -m 6755 Imkdir -m u=rwx,go=rx,a+s JIf you want to try to clear these bits, you must mention themexplicitly in a symbolic mode, e.g.:# This command tries to clear the set-user-ID# and set-group-ID bits of the directory D.chmod a-s DThis behavior is a GNU extension. Portable scripts should not relyon requests to set or clear these bits on directories, as POSIX allowsimplementations to ignore these requests.File: coreutils.info, Node: Date input formats, Next: Opening the software toolbox, Prev: File permissions, Up: Top28 Date input formats*********************First, a quote:Our units of temporal measurement, from seconds on up to months,are so complicated, asymmetrical and disjunctive so as to makecoherent mental reckoning in time all but impossible. Indeed, hadsome tyrannical god contrived to enslave our minds to time, tomake it all but impossible for us to escape subjection to soddenroutines and unpleasant surprises, he could hardly have donebetter than handing down our present system. It is like a set oftrapezoidal building blocks, with no vertical or horizontalsurfaces, like a language in which the simplest thought demandsornate constructions, useless particles and lengthycircumlocutions. Unlike the more successful patterns of languageand science, which enable us to face experience boldly or at leastlevel-headedly, our system of temporal calculation silently andpersistently encourages our terror of time.... It is as though architects had to measure length in feet,width in meters and height in ells; as though basic instructionmanuals demanded a knowledge of five different languages. It isno wonder then that we often look into our own immediate past orfuture, last Tuesday or a week from Sunday, with feelings ofhelpless confusion. ...-- Robert Grudin, `Time and the Art of Living'.This section describes the textual date representations that GNUprograms accept. These are the strings you, as a user, can supply asarguments to the various programs. The C interface (via the `get_date'function) is not described here.* Menu:* General date syntax:: Common rules.* Calendar date items:: 19 Dec 1994.* Time of day items:: 9:20pm.* Time zone items:: EST, PDT, GMT.* Day of week items:: Monday and others.* Relative items in date strings:: next tuesday, 2 years ago.* Pure numbers in date strings:: 19931219, 1440.* Seconds since the Epoch:: @1078100502.* Specifying time zone rules:: TZ="America/New_York", TZ="UTC0".* Authors of get_date:: Bellovin, Eggert, Salz, Berets, et al.File: coreutils.info, Node: General date syntax, Next: Calendar date items, Up: Date input formats28.1 General date syntax========================A "date" is a string, possibly empty, containing many items separatedby whitespace. The whitespace may be omitted when no ambiguity arises.The empty string means the beginning of today (i.e., midnight). Orderof the items is immaterial. A date string may contain many flavors ofitems:* calendar date items* time of day items* time zone items* day of the week items* relative items* pure numbers.We describe each of these item types in turn, below.A few ordinal numbers may be written out in words in some contexts.This is most useful for specifying day of the week items or relativeitems (see below). Among the most commonly used ordinal numbers, theword `last' stands for -1, `this' stands for 0, and `first' and `next'both stand for 1. Because the word `second' stands for the unit oftime there is no way to write the ordinal number 2, but for convenience`third' stands for 3, `fourth' for 4, `fifth' for 5, `sixth' for 6,`seventh' for 7, `eighth' for 8, `ninth' for 9, `tenth' for 10,`eleventh' for 11 and `twelfth' for 12.When a month is written this way, it is still considered to bewritten numerically, instead of being "spelled in full"; this changesthe allowed strings.In the current implementation, only English is supported for wordsand abbreviations like `AM', `DST', `EST', `first', `January',`Sunday', `tomorrow', and `year'.The output of the `date' command is not always acceptable as a datestring, not only because of the language problem, but also becausethere is no standard meaning for time zone items like `IST'. When using`date' to generate a date string intended to be parsed later, specify adate format that is independent of language and that does not use timezone items other than `UTC' and `Z'. Here are some ways to do this:$ LC_ALL=C TZ=UTC0 dateMon Mar 1 00:21:42 UTC 2004$ TZ=UTC0 date +'%Y-%m-%d %H:%M:%SZ'2004-03-01 00:21:42Z$ date --iso-8601=ns | tr T ' ' # --iso-8601 is a GNU extension.2004-02-29 16:21:42,692722128-0800$ date --rfc-2822 # a GNU extensionSun, 29 Feb 2004 16:21:42 -0800$ date +'%Y-%m-%d %H:%M:%S %z' # %z is a GNU extension.2004-02-29 16:21:42 -0800$ date +'@%s.%N' # %s and %N are GNU extensions.@1078100502.692722128Alphabetic case is completely ignored in dates. Comments may beintroduced between round parentheses, as long as included parenthesesare properly nested. Hyphens not followed by a digit are currentlyignored. Leading zeros on numbers are ignored.Invalid dates like `2005-02-29' or times like `24:00' are rejected.In the typical case of a host that does not support leap seconds, atime like `23:59:60' is rejected even if it corresponds to a valid leapsecond.File: coreutils.info, Node: Calendar date items, Next: Time of day items, Prev: General date syntax, Up: Date input formats28.2 Calendar date items========================A "calendar date item" specifies a day of the year. It is specifieddifferently, depending on whether the month is specified numerically orliterally. All these strings specify the same calendar date:1972-09-24 # ISO 8601.72-9-24 # Assume 19xx for 69 through 99,# 20xx for 00 through 68.72-09-24 # Leading zeros are ignored.9/24/72 # Common U.S. writing.24 September 197224 Sept 72 # September has a special abbreviation.24 Sep 72 # Three-letter abbreviations always allowed.Sep 24, 197224-sep-7224sep72The year can also be omitted. In this case, the last specified yearis used, or the current year if none. For example:9/24sep 24Here are the rules.For numeric months, the ISO 8601 format `YEAR-MONTH-DAY' is allowed,where YEAR is any positive number, MONTH is a number between 01 and 12,and DAY is a number between 01 and 31. A leading zero must be presentif a number is less than ten. If YEAR is 68 or smaller, then 2000 isadded to it; otherwise, if YEAR is less than 100, then 1900 is added toit. The construct `MONTH/DAY/YEAR', popular in the United States, isaccepted. Also `MONTH/DAY', omitting the year.Literal months may be spelled out in full: `January', `February',`March', `April', `May', `June', `July', `August', `September',`October', `November' or `December'. Literal months may be abbreviatedto their first three letters, possibly followed by an abbreviating dot.It is also permitted to write `Sept' instead of `September'.When months are written literally, the calendar date may be given asany of the following:DAY MONTH YEARDAY MONTHMONTH DAY YEARDAY-MONTH-YEAROr, omitting the year:MONTH DAYFile: coreutils.info, Node: Time of day items, Next: Time zone items, Prev: Calendar date items, Up: Date input formats28.3 Time of day items======================A "time of day item" in date strings specifies the time on a given day.Here are some examples, all of which represent the same time:20:02:00.00000020:028:02pm20:02-0500 # In EST (U.S. Eastern Standard Time).More generally, the time of day may be given as`HOUR:MINUTE:SECOND', where HOUR is a number between 0 and 23, MINUTEis a number between 0 and 59, and SECOND is a number between 0 and 59possibly followed by `.' or `,' and a fraction containing one or moredigits. Alternatively, `:SECOND' can be omitted, in which case it istaken to be zero. On the rare hosts that support leap seconds, SECONDmay be 60.If the time is followed by `am' or `pm' (or `a.m.' or `p.m.'), HOURis restricted to run from 1 to 12, and `:MINUTE' may be omitted (takento be zero). `am' indicates the first half of the day, `pm' indicatesthe second half of the day. In this notation, 12 is the predecessor of1: midnight is `12am' while noon is `12pm'. (This is the zero-orientedinterpretation of `12am' and `12pm', as opposed to the old traditionderived from Latin which uses `12m' for noon and `12pm' for midnight.)The time may alternatively be followed by a time zone correction,expressed as `SHHMM', where S is `+' or `-', HH is a number of zonehours and MM is a number of zone minutes. The zone minutes term, MM,may be omitted, in which case the one- or two-digit correction isinterpreted as a number of hours. You can also separate HH from MMwith a colon. When a time zone correction is given this way, it forcesinterpretation of the time relative to Coordinated Universal Time(UTC), overriding any previous specification for the time zone or thelocal time zone. For example, `+0530' and `+05:30' both stand for thetime zone 5.5 hours ahead of UTC (e.g., India). This is the best way tospecify a time zone correction by fractional parts of an hour. Themaximum zone correction is 24 hours.Either `am'/`pm' or a time zone correction may be specified, but notboth.File: coreutils.info, Node: Time zone items, Next: Day of week items, Prev: Time of day items, Up: Date input formats28.4 Time zone items====================A "time zone item" specifies an international time zone, indicated by asmall set of letters, e.g., `UTC' or `Z' for Coordinated UniversalTime. Any included periods are ignored. By following anon-daylight-saving time zone by the string `DST' in a separate word(that is, separated by some white space), the corresponding daylightsaving time zone may be specified. Alternatively, anon-daylight-saving time zone can be followed by a time zonecorrection, to add the two values. This is normally done only for`UTC'; for example, `UTC+05:30' is equivalent to `+05:30'.Time zone items other than `UTC' and `Z' are obsolescent and are notrecommended, because they are ambiguous; for example, `EST' has adifferent meaning in Australia than in the United States. Instead,it's better to use unambiguous numeric time zone corrections like`-0500', as described in the previous section.If neither a time zone item nor a time zone correction is supplied,time stamps are interpreted using the rules of the default time zone(*note Specifying time zone rules::).File: coreutils.info, Node: Day of week items, Next: Relative items in date strings, Prev: Time zone items, Up: Date input formats28.5 Day of week items======================The explicit mention of a day of the week will forward the date (onlyif necessary) to reach that day of the week in the future.Days of the week may be spelled out in full: `Sunday', `Monday',`Tuesday', `Wednesday', `Thursday', `Friday' or `Saturday'. Days maybe abbreviated to their first three letters, optionally followed by aperiod. The special abbreviations `Tues' for `Tuesday', `Wednes' for`Wednesday' and `Thur' or `Thurs' for `Thursday' are also allowed.A number may precede a day of the week item to move forwardsupplementary weeks. It is best used in expression like `thirdmonday'. In this context, `last DAY' or `next DAY' is also acceptable;they move one week before or after the day that DAY by itself wouldrepresent.A comma following a day of the week item is ignored.File: coreutils.info, Node: Relative items in date strings, Next: Pure numbers in date strings, Prev: Day of week items, Up: Date input formats28.6 Relative items in date strings==================================="Relative items" adjust a date (or the current date if none) forward orbackward. The effects of relative items accumulate. Here are someexamples:1 year1 year ago3 years2 daysThe unit of time displacement may be selected by the string `year'or `month' for moving by whole years or months. These are fuzzy units,as years and months are not all of equal duration. More precise unitsare `fortnight' which is worth 14 days, `week' worth 7 days, `day'worth 24 hours, `hour' worth 60 minutes, `minute' or `min' worth 60seconds, and `second' or `sec' worth one second. An `s' suffix onthese units is accepted and ignored.The unit of time may be preceded by a multiplier, given as anoptionally signed number. Unsigned numbers are taken as positivelysigned. No number at all implies 1 for a multiplier. Following arelative item by the string `ago' is equivalent to preceding the unitby a multiplier with value -1.The string `tomorrow' is worth one day in the future (equivalent to`day'), the string `yesterday' is worth one day in the past (equivalentto `day ago').The strings `now' or `today' are relative items corresponding tozero-valued time displacement, these strings come from the fact azero-valued time displacement represents the current time when nototherwise changed by previous items. They may be used to stress otheritems, like in `12:00 today'. The string `this' also has the meaningof a zero-valued time displacement, but is preferred in date stringslike `this thursday'.When a relative item causes the resulting date to cross a boundarywhere the clocks were adjusted, typically for daylight saving time, theresulting date and time are adjusted accordingly.The fuzz in units can cause problems with relative items. Forexample, `2003-07-31 -1 month' might evaluate to 2003-07-01, because2003-06-31 is an invalid date. To determine the previous month morereliably, you can ask for the month before the 15th of the currentmonth. For example:$ date -RThu, 31 Jul 2003 13:02:39 -0700$ date --date='-1 month' +'Last month was %B?'Last month was July?$ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'Last month was June!Also, take care when manipulating dates around clock changes such asdaylight saving leaps. In a few cases these have added or subtractedas much as 24 hours from the clock, so it is often wise to adoptuniversal time by setting the `TZ' environment variable to `UTC0'before embarking on calendrical calculations.File: coreutils.info, Node: Pure numbers in date strings, Next: Seconds since the Epoch, Prev: Relative items in date strings, Up: Date input formats28.7 Pure numbers in date strings=================================The precise interpretation of a pure decimal number depends on thecontext in the date string.If the decimal number is of the form YYYYMMDD and no other calendardate item (*note Calendar date items::) appears before it in the datestring, then YYYY is read as the year, MM as the month number and DD asthe day of the month, for the specified calendar date.If the decimal number is of the form HHMM and no other time of dayitem appears before it in the date string, then HH is read as the hourof the day and MM as the minute of the hour, for the specified time ofday. MM can also be omitted.If both a calendar date and a time of day appear to the left of anumber in the date string, but no relative item, then the numberoverrides the year.File: coreutils.info, Node: Seconds since the Epoch, Next: Specifying time zone rules, Prev: Pure numbers in date strings, Up: Date input formats28.8 Seconds since the Epoch============================If you precede a number with `@', it represents an internal time stampas a count of seconds. The number can contain an internal decimalpoint (either `.' or `,'); any excess precision not supported by theinternal representation is truncated toward minus infinity. Such anumber cannot be combined with any other date item, as it specifies acomplete time stamp.Internally, computer times are represented as a count of secondssince an epoch--a well-defined point of time. On GNU and POSIXsystems, the epoch is 1970-01-01 00:00:00 UTC, so `@0' represents thistime, `@1' represents 1970-01-01 00:00:01 UTC, and so forth. GNU andmost other POSIX-compliant systems support such times as an extensionto POSIX, using negative counts, so that `@-1' represents 1969-12-3123:59:59 UTC.Traditional Unix systems count seconds with 32-bit two's-complementintegers and can represent times from 1901-12-13 20:45:52 through2038-01-19 03:14:07 UTC. More modern systems use 64-bit counts ofseconds with nanosecond subcounts, and can represent all the times inthe known lifetime of the universe to a resolution of 1 nanosecond.On most hosts, these counts ignore the presence of leap seconds.For example, on most hosts `@915148799' represents 1998-12-31 23:59:59UTC, `@915148800' represents 1999-01-01 00:00:00 UTC, and there is noway to represent the intervening leap second 1998-12-31 23:59:60 UTC.File: coreutils.info, Node: Specifying time zone rules, Next: Authors of get_date, Prev: Seconds since the Epoch, Up: Date input formats28.9 Specifying time zone rules===============================Normally, dates are interpreted using the rules of the current timezone, which in turn are specified by the `TZ' environment variable, orby a system default if `TZ' is not set. To specify a different set ofdefault time zone rules that apply just to one date, start the datewith a string of the form `TZ="RULE"'. The two quote characters (`"')must be present in the date, and any quotes or backslashes within RULEmust be escaped by a backslash.For example, with the GNU `date' command you can answer the question"What time is it in New York when a Paris clock shows 6:30am on October31, 2004?" by using a date beginning with `TZ="Europe/Paris"' as shownin the following shell transcript:$ export TZ="America/New_York"$ date --date='TZ="Europe/Paris" 2004-10-31 06:30'Sun Oct 31 01:30:00 EDT 2004In this example, the `--date' operand begins with its own `TZ'setting, so the rest of that operand is processed according to`Europe/Paris' rules, treating the string `2004-10-31 06:30' as if itwere in Paris. However, since the output of the `date' command isprocessed according to the overall time zone rules, it uses New Yorktime. (Paris was normally six hours ahead of New York in 2004, butthis example refers to a brief Halloween period when the gap was fivehours.)A `TZ' value is a rule that typically names a location in the `tz'database (http://www.twinsun.com/tz/tz-link.htm). A recent catalog oflocation names appears in the TWiki Date and Time Gateway(http://twiki.org/cgi-bin/xtra/tzdate). A few non-GNU hosts require acolon before a location name in a `TZ' setting, e.g.,`TZ=":America/New_York"'.The `tz' database includes a wide variety of locations ranging from`Arctic/Longyearbyen' to `Antarctica/South_Pole', but if you are at seaand have your own private time zone, or if you are using a non-GNU hostthat does not support the `tz' database, you may need to use a POSIXrule instead. Simple POSIX rules like `UTC0' specify a time zonewithout daylight saving time; other rules can specify simple daylightsaving regimes. *Note Specifying the Time Zone with `TZ': (libc)TZVariable.File: coreutils.info, Node: Authors of get_date, Prev: Specifying time zone rules, Up: Date input formats28.10 Authors of `get_date'===========================`get_date' was originally implemented by Steven M. Bellovin(<smb@research.att.com>) while at the University of North Carolina atChapel Hill. The code was later tweaked by a couple of people onUsenet, then completely overhauled by Rich $alz (<rsalz@bbn.com>) andJim Berets (<jberets@bbn.com>) in August, 1990. Various revisions forthe GNU system were made by David MacKenzie, Jim Meyering, Paul Eggertand others.This chapter was originally produced by Franc,ois Pinard(<pinard@iro.umontreal.ca>) from the `getdate.y' source code, and thenedited by K. Berry (<kb@cs.umb.edu>).File: coreutils.info, Node: Opening the software toolbox, Next: GNU Free Documentation License, Prev: Date input formats, Up: Top29 Opening the Software Toolbox*******************************An earlier version of this chapter appeared in 2 (June 1994). It waswritten by Arnold Robbins.* Menu:* Toolbox introduction:: Toolbox introduction* I/O redirection:: I/O redirection* The who command:: The `who' command* The cut command:: The `cut' command* The sort command:: The `sort' command* The uniq command:: The `uniq' command* Putting the tools together:: Putting the tools togetherFile: coreutils.info, Node: Toolbox introduction, Next: I/O redirection, Up: Opening the software toolboxToolbox Introduction====================This month's column is only peripherally related to the GNU Project, inthat it describes a number of the GNU tools on your GNU/Linux systemand how they might be used. What it's really about is the "SoftwareTools" philosophy of program development and usage.The software tools philosophy was an important and integral conceptin the initial design and development of Unix (of which Linux and GNUare essentially clones). Unfortunately, in the modern day press ofInternetworking and flashy GUIs, it seems to have fallen by thewayside. This is a shame, since it provides a powerful mental modelfor solving many kinds of problems.Many people carry a Swiss Army knife around in their pants pockets(or purse). A Swiss Army knife is a handy tool to have: it has severalknife blades, a screwdriver, tweezers, toothpick, nail file, corkscrew,and perhaps a number of other things on it. For the everyday, smallmiscellaneous jobs where you need a simple, general purpose tool, it'sjust the thing.On the other hand, an experienced carpenter doesn't build a houseusing a Swiss Army knife. Instead, he has a toolbox chock full ofspecialized tools--a saw, a hammer, a screwdriver, a plane, and so on.And he knows exactly when and where to use each tool; you won't catchhim hammering nails with the handle of his screwdriver.The Unix developers at Bell Labs were all professional programmersand trained computer scientists. They had found that while aone-size-fits-all program might appeal to a user because there's onlyone program to use, in practice such programs area. difficult to write,b. difficult to maintain and debug, andc. difficult to extend to meet new situations.Instead, they felt that programs should be specialized tools. Inshort, each program "should do one thing well." No more and no less.Such programs are simpler to design, write, and get right--they only doone thing.Furthermore, they found that with the right machinery for hookingprograms together, that the whole was greater than the sum of theparts. By combining several special purpose programs, you couldaccomplish a specific task that none of the programs was designed for,and accomplish it much more quickly and easily than if you had to writea special purpose program. We will see some (classic) examples of thisfurther on in the column. (An important additional point was that, ifnecessary, take a detour and build any software tools you may needfirst, if you don't already have something appropriate in the toolbox.)File: coreutils.info, Node: I/O redirection, Next: The who command, Prev: Toolbox introduction, Up: Opening the software toolboxI/O Redirection===============Hopefully, you are familiar with the basics of I/O redirection in theshell, in particular the concepts of "standard input," "standardoutput," and "standard error". Briefly, "standard input" is a datasource, where data comes from. A program should not need to eitherknow or care if the data source is a disk file, a keyboard, a magnetictape, or even a punched card reader. Similarly, "standard output" is adata sink, where data goes to. The program should neither know norcare where this might be. Programs that only read their standardinput, do something to the data, and then send it on, are called"filters", by analogy to filters in a water pipeline.With the Unix shell, it's very easy to set up data pipelines:program_to_create_data | filter1 | ... | filterN > final.pretty.dataWe start out by creating the raw data; each filter applies somesuccessive transformation to the data, until by the time it comes outof the pipeline, it is in the desired form.This is fine and good for standard input and standard output. Wheredoes the standard error come in to play? Well, think about `filter1' inthe pipeline above. What happens if it encounters an error in the datait sees? If it writes an error message to standard output, it will justdisappear down the pipeline into `filter2''s input, and the user willprobably never see it. So programs need a place where they can senderror messages so that the user will notice them. This is standarderror, and it is usually connected to your console or window, even ifyou have redirected standard output of your program away from yourscreen.For filter programs to work together, the format of the data has tobe agreed upon. The most straightforward and easiest format to use issimply lines of text. Unix data files are generally just streams ofbytes, with lines delimited by the ASCII LF (Line Feed) character,conventionally called a "newline" in the Unix literature. (This is`'\n'' if you're a C programmer.) This is the format used by all thetraditional filtering programs. (Many earlier operating systems hadelaborate facilities and special purpose programs for managing binarydata. Unix has always shied away from such things, under thephilosophy that it's easiest to simply be able to view and edit yourdata with a text editor.)OK, enough introduction. Let's take a look at some of the tools,and then we'll see how to hook them together in interesting ways. Inthe following discussion, we will only present those command lineoptions that interest us. As you should always do, double check yoursystem documentation for the full story.File: coreutils.info, Node: The who command, Next: The cut command, Prev: I/O redirection, Up: Opening the software toolboxThe `who' Command=================The first program is the `who' command. By itself, it generates a listof the users who are currently logged in. Although I'm writing this ona single-user system, we'll pretend that several people are logged in:$ who-| arnold console Jan 22 19:57-| miriam ttyp0 Jan 23 14:19(:0.0)-| bill ttyp1 Jan 21 09:32(:0.0)-| arnold ttyp2 Jan 23 20:48(:0.0)Here, the `$' is the usual shell prompt, at which I typed `who'.There are three people logged in, and I am logged in twice. Ontraditional Unix systems, user names are never more than eightcharacters long. This little bit of trivia will be useful later. Theoutput of `who' is nice, but the data is not all that exciting.File: coreutils.info, Node: The cut command, Next: The sort command, Prev: The who command, Up: Opening the software toolboxThe `cut' Command=================The next program we'll look at is the `cut' command. This program cutsout columns or fields of input data. For example, we can tell it toprint just the login name and full name from the `/etc/passwd' file.The `/etc/passwd' file has seven fields, separated by colons:arnold:xyzzy:2076:10:Arnold D. Robbins:/home/arnold:/bin/bashTo get the first and fifth fields, we would use `cut' like this:$ cut -d: -f1,5 /etc/passwd-| root:Operator...-| arnold:Arnold D. Robbins-| miriam:Miriam A. Robbins...With the `-c' option, `cut' will cut out specific characters (i.e.,columns) in the input lines. This is useful for input data that hasfixed width fields, and does not have a field separator. For example,list the Monday dates for the current month:$ cal | cut -c 3-5-|Mo-|-| 6-| 13-| 20-| 27File: coreutils.info, Node: The sort command, Next: The uniq command, Prev: The cut command, Up: Opening the software toolboxThe `sort' Command==================Next we'll look at the `sort' command. This is one of the mostpowerful commands on a Unix-style system; one that you will often findyourself using when setting up fancy data plumbing.The `sort' command reads and sorts each file named on the commandline. It then merges the sorted data and writes it to standard output.It will read standard input if no files are given on the command line(thus making it into a filter). The sort is based on the charactercollating sequence or based on user-supplied ordering criteria.File: coreutils.info, Node: The uniq command, Next: Putting the tools together, Prev: The sort command, Up: Opening the software toolboxThe `uniq' Command==================Finally (at least for now), we'll look at the `uniq' program. Whensorting data, you will often end up with duplicate lines, lines thatare identical. Usually, all you need is one instance of each line.This is where `uniq' comes in. The `uniq' program reads its standardinput. It prints only one copy of each repeated line. It does haveseveral options. Later on, we'll use the `-c' option, which printseach unique line, preceded by a count of the number of times that lineoccurred in the input.File: coreutils.info, Node: Putting the tools together, Prev: The uniq command, Up: Opening the software toolboxPutting the Tools Together==========================Now, let's suppose this is a large ISP server system with dozens ofusers logged in. The management wants the system administrator towrite a program that will generate a sorted list of logged in users.Furthermore, even if a user is logged in multiple times, his or hername should only show up in the output once.The administrator could sit down with the system documentation andwrite a C program that did this. It would take perhaps a couple ofhundred lines of code and about two hours to write it, test it, anddebug it. However, knowing the software toolbox, the administrator caninstead start out by generating just a list of logged on users:$ who | cut -c1-8-| arnold-| miriam-| bill-| arnoldNext, sort the list:$ who | cut -c1-8 | sort-| arnold-| arnold-| bill-| miriamFinally, run the sorted list through `uniq', to weed out duplicates:$ who | cut -c1-8 | sort | uniq-| arnold-| bill-| miriamThe `sort' command actually has a `-u' option that does what `uniq'does. However, `uniq' has other uses for which one cannot substitute`sort -u'.The administrator puts this pipeline into a shell script, and makesit available for all the users on the system (`#' is the systemadministrator, or `root', prompt):# cat > /usr/local/bin/listuserswho | cut -c1-8 | sort | uniq^D# chmod +x /usr/local/bin/listusersThere are four major points to note here. First, with just fourprograms, on one command line, the administrator was able to save abouttwo hours worth of work. Furthermore, the shell pipeline is just aboutas efficient as the C program would be, and it is much more efficient interms of programmer time. People time is much more expensive thancomputer time, and in our modern "there's never enough time to doeverything" society, saving two hours of programmer time is no meanfeat.Second, it is also important to emphasize that with the_combination_ of the tools, it is possible to do a special purpose jobnever imagined by the authors of the individual programs.Third, it is also valuable to build up your pipeline in stages, aswe did here. This allows you to view the data at each stage in thepipeline, which helps you acquire the confidence that you are indeedusing these tools correctly.Finally, by bundling the pipeline in a shell script, other users canuse your command, without having to remember the fancy plumbing you setup for them. In terms of how you run them, shell scripts and compiledprograms are indistinguishable.After the previous warm-up exercise, we'll look at two additional,more complicated pipelines. For them, we need to introduce two moretools.The first is the `tr' command, which stands for "transliterate."The `tr' command works on a character-by-character basis, changingcharacters. Normally it is used for things like mapping upper case tolower case:$ echo ThIs ExAmPlE HaS MIXED case! | tr '[:upper:]' '[:lower:]'-| this example has mixed case!There are several options of interest:`-c'work on the complement of the listed characters, i.e., operationsapply to characters not in the given set`-d'delete characters in the first set from the output`-s'squeeze repeated characters in the output into just one character.We will be using all three options in a moment.The other command we'll look at is `comm'. The `comm' command takestwo sorted input files as input data, and prints out the files' linesin three columns. The output columns are the data lines unique to thefirst file, the data lines unique to the second file, and the datalines that are common to both. The `-1', `-2', and `-3' command lineoptions _omit_ the respective columns. (This is non-intuitive andtakes a little getting used to.) For example:$ cat f1-| 11111-| 22222-| 33333-| 44444$ cat f2-| 00000-| 22222-| 33333-| 55555$ comm f1 f2-| 00000-| 11111-| 22222-| 33333-| 44444-| 55555The file name `-' tells `comm' to read standard input instead of aregular file.Now we're ready to build a fancy pipeline. The first application isa word frequency counter. This helps an author determine if he or sheis over-using certain words.The first step is to change the case of all the letters in our inputfile to one case. "The" and "the" are the same word when doingcounting.$ tr '[:upper:]' '[:lower:]' < whats.gnu | ...The next step is to get rid of punctuation. Quoted words andunquoted words should be treated identically; it's easiest to just getthe punctuation out of the way.$ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | ...The second `tr' command operates on the complement of the listedcharacters, which are all the letters, the digits, the underscore, andthe blank. The `\n' represents the newline character; it has to beleft alone. (The ASCII tab character should also be included for goodmeasure in a production script.)At this point, we have data consisting of words separated by blankspace. The words only contain alphanumeric characters (and theunderscore). The next step is break the data apart so that we have oneword per line. This makes the counting operation much easier, as wewill see shortly.$ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |> tr -s ' ' '\n' | ...This command turns blanks into newlines. The `-s' option squeezesmultiple newline characters in the output into just one. This helps usavoid blank lines. (The `>' is the shell's "secondary prompt." Thisis what the shell prints when it notices you haven't finished typing inall of a command.)We now have data consisting of one word per line, no punctuation,all one case. We're ready to count each word:$ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |> tr -s ' ' '\n' | sort | uniq -c | ...At this point, the data might look something like this:60 a2 able6 about1 above2 accomplish1 acquire1 actually2 additionalThe output is sorted by word, not by count! What we want is the mostfrequently used words first. Fortunately, this is easy to accomplish,with the help of two more `sort' options:`-n'do a numeric sort, not a textual one`-r'reverse the order of the sortThe final pipeline looks like this:$ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |> tr -s ' ' '\n' | sort | uniq -c | sort -n -r-| 156 the-| 60 a-| 58 to-| 51 of-| 51 and...Whew! That's a lot to digest. Yet, the same principles apply.With six commands, on two lines (really one long one split forconvenience), we've created a program that does something interestingand useful, in much less time than we could have written a C program todo the same thing.A minor modification to the above pipeline can give us a simplespelling checker! To determine if you've spelled a word correctly, allyou have to do is look it up in a dictionary. If it is not there, thenchances are that your spelling is incorrect. So, we need a dictionary.The conventional location for a dictionary is `/usr/dict/words'. On myGNU/Linux system,(1) this is a sorted, 45,402 word dictionary.Now, how to compare our file with the dictionary? As before, wegenerate a sorted list of words, one per line:$ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |> tr -s ' ' '\n' | sort -u | ...Now, all we need is a list of words that are _not_ in thedictionary. Here is where the `comm' command comes in.$ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |> tr -s ' ' '\n' | sort -u |> comm -23 - /usr/dict/wordsThe `-2' and `-3' options eliminate lines that are only in thedictionary (the second file), and lines that are in both files. Linesonly in the first file (standard input, our stream of words), are wordsthat are not in the dictionary. These are likely candidates forspelling errors. This pipeline was the first cut at a productionspelling checker on Unix.There are some other tools that deserve brief mention.`grep'search files for text that matches a regular expression`wc'count lines, words, characters`tee'a T-fitting for data pipes, copies data to files and to standardoutput`sed'the stream editor, an advanced tool`awk'a data manipulation language, another advanced toolThe software tools philosophy also espoused the following bit ofadvice: "Let someone else do the hard part." This means, takesomething that gives you most of what you need, and then massage it therest of the way until it's in the form that you want.To summarize:1. Each program should do one thing well. No more, no less.2. Combining programs with appropriate plumbing leads to results wherethe whole is greater than the sum of the parts. It also leads tonovel uses of programs that the authors might never have imagined.3. Programs should never print extraneous header or trailer data,since these could get sent on down a pipeline. (A point we didn'tmention earlier.)4. Let someone else do the hard part.5. Know your toolbox! Use each program appropriately. If you don'thave an appropriate tool, build one.As of this writing, all the programs we've discussed are availablevia anonymous `ftp' from:`ftp://gnudist.gnu.org/textutils/textutils-1.22.tar.gz'. (There may bemore recent versions available now.)None of what I have presented in this column is new. The SoftwareTools philosophy was first introduced in the book `Software Tools', byBrian Kernighan and P.J. Plauger (Addison-Wesley, ISBN 0-201-03669-X).This book showed how to write and use software tools. It was written in1976, using a preprocessor for FORTRAN named `ratfor' (RATionalFORtran). At the time, C was not as ubiquitous as it is now; FORTRANwas. The last chapter presented a `ratfor' to FORTRAN processor,written in `ratfor'. `ratfor' looks an awful lot like C; if you knowC, you won't have any problem following the code.In 1981, the book was updated and made available as `Software Toolsin Pascal' (Addison-Wesley, ISBN 0-201-10342-7). Both books are stillin print and are well worth reading if you're a programmer. Theycertainly made a major change in how I view programming.The programs in both books are available from Brian Kernighan's homepage (http://cm.bell-labs.com/who/bwk). For a number of years, therewas an active Software Tools Users Group, whose members had ported theoriginal `ratfor' programs to essentially every computer system with aFORTRAN compiler. The popularity of the group waned in the middle 1980sas Unix began to spread beyond universities.With the current proliferation of GNU code and other clones of Unixprograms, these programs now receive little attention; modern Cversions are much more efficient and do more than these programs do.Nevertheless, as exposition of good programming style, and evangelismfor a still-valuable philosophy, these books are unparalleled, and Irecommend them highly.Acknowledgment: I would like to express my gratitude to BrianKernighan of Bell Labs, the original Software Toolsmith, for reviewingthis column.---------- Footnotes ----------(1) Redhat Linux 6.1, for the November 2000 revision of this article.File: coreutils.info, Node: GNU Free Documentation License, Next: Concept index, Prev: Opening the software toolbox, Up: TopAppendix A GNU Free Documentation License*****************************************Version 1.3, 3 November 2008Copyright (C) 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc.`http://fsf.org/'Everyone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.0. PREAMBLEThe purpose of this License is to make a manual, textbook, or otherfunctional and useful document "free" in the sense of freedom: toassure everyone the effective freedom to copy and redistribute it,with or without modifying it, either commercially ornoncommercially. Secondarily, this License preserves for theauthor and publisher a way to get credit for their work, while notbeing considered responsible for modifications made by others.This License is a kind of "copyleft", which means that derivativeworks of the document must themselves be free in the same sense.It complements the GNU General Public License, which is a copyleftlicense designed for free software.We have designed this License in order to use it for manuals forfree software, because free software needs free documentation: afree program should come with manuals providing the same freedomsthat the software does. But this License is not limited tosoftware manuals; it can be used for any textual work, regardlessof subject matter or whether it is published as a printed book.We recommend this License principally for works whose purpose isinstruction or reference.1. APPLICABILITY AND DEFINITIONSThis License applies to any manual or other work, in any medium,that contains a notice placed by the copyright holder saying itcan be distributed under the terms of this License. Such a noticegrants a world-wide, royalty-free license, unlimited in duration,to use that work under the conditions stated herein. The"Document", below, refers to any such manual or work. Any memberof the public is a licensee, and is addressed as "you". Youaccept the license if you copy, modify or distribute the work in away requiring permission under copyright law.A "Modified Version" of the Document means any work containing theDocument or a portion of it, either copied verbatim, or withmodifications and/or translated into another language.A "Secondary Section" is a named appendix or a front-matter sectionof the Document that deals exclusively with the relationship of thepublishers or authors of the Document to the Document's overallsubject (or to related matters) and contains nothing that couldfall directly within that overall subject. (Thus, if the Documentis in part a textbook of mathematics, a Secondary Section may notexplain any mathematics.) The relationship could be a matter ofhistorical connection with the subject or with related matters, orof legal, commercial, philosophical, ethical or political positionregarding them.The "Invariant Sections" are certain Secondary Sections whosetitles are designated, as being those of Invariant Sections, inthe notice that says that the Document is released under thisLicense. If a section does not fit the above definition ofSecondary then it is not allowed to be designated as Invariant.The Document may contain zero Invariant Sections. If the Documentdoes not identify any Invariant Sections then there are none.The "Cover Texts" are certain short passages of text that arelisted, as Front-Cover Texts or Back-Cover Texts, in the noticethat says that the Document is released under this License. AFront-Cover Text may be at most 5 words, and a Back-Cover Text maybe at most 25 words.A "Transparent" copy of the Document means a machine-readable copy,represented in a format whose specification is available to thegeneral public, that is suitable for revising the documentstraightforwardly with generic text editors or (for imagescomposed of pixels) generic paint programs or (for drawings) somewidely available drawing editor, and that is suitable for input totext formatters or for automatic translation to a variety offormats suitable for input to text formatters. A copy made in anotherwise Transparent file format whose markup, or absence ofmarkup, has been arranged to thwart or discourage subsequentmodification by readers is not Transparent. An image format isnot Transparent if used for any substantial amount of text. Acopy that is not "Transparent" is called "Opaque".Examples of suitable formats for Transparent copies include plainASCII without markup, Texinfo input format, LaTeX input format,SGML or XML using a publicly available DTD, andstandard-conforming simple HTML, PostScript or PDF designed forhuman modification. Examples of transparent image formats includePNG, XCF and JPG. Opaque formats include proprietary formats thatcan be read and edited only by proprietary word processors, SGML orXML for which the DTD and/or processing tools are not generallyavailable, and the machine-generated HTML, PostScript or PDFproduced by some word processors for output purposes only.The "Title Page" means, for a printed book, the title page itself,plus such following pages as are needed to hold, legibly, thematerial this License requires to appear in the title page. Forworks in formats which do not have any title page as such, "TitlePage" means the text near the most prominent appearance of thework's title, preceding the beginning of the body of the text.The "publisher" means any person or entity that distributes copiesof the Document to the public.A section "Entitled XYZ" means a named subunit of the Documentwhose title either is precisely XYZ or contains XYZ in parenthesesfollowing text that translates XYZ in another language. (Here XYZstands for a specific section name mentioned below, such as"Acknowledgements", "Dedications", "Endorsements", or "History".)To "Preserve the Title" of such a section when you modify theDocument means that it remains a section "Entitled XYZ" accordingto this definition.The Document may include Warranty Disclaimers next to the noticewhich states that this License applies to the Document. TheseWarranty Disclaimers are considered to be included by reference inthis License, but only as regards disclaiming warranties: any otherimplication that these Warranty Disclaimers may have is void andhas no effect on the meaning of this License.2. VERBATIM COPYINGYou may copy and distribute the Document in any medium, eithercommercially or noncommercially, provided that this License, thecopyright notices, and the license notice saying this Licenseapplies to the Document are reproduced in all copies, and that youadd no other conditions whatsoever to those of this License. Youmay not use technical measures to obstruct or control the readingor further copying of the copies you make or distribute. However,you may accept compensation in exchange for copies. If youdistribute a large enough number of copies you must also followthe conditions in section 3.You may also lend copies, under the same conditions stated above,and you may publicly display copies.3. COPYING IN QUANTITYIf you publish printed copies (or copies in media that commonlyhave printed covers) of the Document, numbering more than 100, andthe Document's license notice requires Cover Texts, you mustenclose the copies in covers that carry, clearly and legibly, allthese Cover Texts: Front-Cover Texts on the front cover, andBack-Cover Texts on the back cover. Both covers must also clearlyand legibly identify you as the publisher of these copies. Thefront cover must present the full title with all words of thetitle equally prominent and visible. You may add other materialon the covers in addition. Copying with changes limited to thecovers, as long as they preserve the title of the Document andsatisfy these conditions, can be treated as verbatim copying inother respects.If the required texts for either cover are too voluminous to fitlegibly, you should put the first ones listed (as many as fitreasonably) on the actual cover, and continue the rest ontoadjacent pages.If you publish or distribute Opaque copies of the Documentnumbering more than 100, you must either include amachine-readable Transparent copy along with each Opaque copy, orstate in or with each Opaque copy a computer-network location fromwhich the general network-using public has access to downloadusing public-standard network protocols a complete Transparentcopy of the Document, free of added material. If you use thelatter option, you must take reasonably prudent steps, when youbegin distribution of Opaque copies in quantity, to ensure thatthis Transparent copy will remain thus accessible at the statedlocation until at least one year after the last time youdistribute an Opaque copy (directly or through your agents orretailers) of that edition to the public.It is requested, but not required, that you contact the authors ofthe Document well before redistributing any large number ofcopies, to give them a chance to provide you with an updatedversion of the Document.4. MODIFICATIONSYou may copy and distribute a Modified Version of the Documentunder the conditions of sections 2 and 3 above, provided that yourelease the Modified Version under precisely this License, withthe Modified Version filling the role of the Document, thuslicensing distribution and modification of the Modified Version towhoever possesses a copy of it. In addition, you must do thesethings in the Modified Version:A. Use in the Title Page (and on the covers, if any) a titledistinct from that of the Document, and from those ofprevious versions (which should, if there were any, be listedin the History section of the Document). You may use thesame title as a previous version if the original publisher ofthat version gives permission.B. List on the Title Page, as authors, one or more persons orentities responsible for authorship of the modifications inthe Modified Version, together with at least five of theprincipal authors of the Document (all of its principalauthors, if it has fewer than five), unless they release youfrom this requirement.C. State on the Title page the name of the publisher of theModified Version, as the publisher.D. Preserve all the copyright notices of the Document.E. Add an appropriate copyright notice for your modificationsadjacent to the other copyright notices.F. Include, immediately after the copyright notices, a licensenotice giving the public permission to use the ModifiedVersion under the terms of this License, in the form shown inthe Addendum below.G. Preserve in that license notice the full lists of InvariantSections and required Cover Texts given in the Document'slicense notice.H. Include an unaltered copy of this License.I. Preserve the section Entitled "History", Preserve its Title,and add to it an item stating at least the title, year, newauthors, and publisher of the Modified Version as given onthe Title Page. If there is no section Entitled "History" inthe Document, create one stating the title, year, authors,and publisher of the Document as given on its Title Page,then add an item describing the Modified Version as stated inthe previous sentence.J. Preserve the network location, if any, given in the Documentfor public access to a Transparent copy of the Document, andlikewise the network locations given in the Document forprevious versions it was based on. These may be placed inthe "History" section. You may omit a network location for awork that was published at least four years before theDocument itself, or if the original publisher of the versionit refers to gives permission.K. For any section Entitled "Acknowledgements" or "Dedications",Preserve the Title of the section, and preserve in thesection all the substance and tone of each of the contributoracknowledgements and/or dedications given therein.L. Preserve all the Invariant Sections of the Document,unaltered in their text and in their titles. Section numbersor the equivalent are not considered part of the sectiontitles.M. Delete any section Entitled "Endorsements". Such a sectionmay not be included in the Modified Version.N. Do not retitle any existing section to be Entitled"Endorsements" or to conflict in title with any InvariantSection.O. Preserve any Warranty Disclaimers.If the Modified Version includes new front-matter sections orappendices that qualify as Secondary Sections and contain nomaterial copied from the Document, you may at your optiondesignate some or all of these sections as invariant. To do this,add their titles to the list of Invariant Sections in the ModifiedVersion's license notice. These titles must be distinct from anyother section titles.You may add a section Entitled "Endorsements", provided it containsnothing but endorsements of your Modified Version by variousparties--for example, statements of peer review or that the texthas been approved by an organization as the authoritativedefinition of a standard.You may add a passage of up to five words as a Front-Cover Text,and a passage of up to 25 words as a Back-Cover Text, to the endof the list of Cover Texts in the Modified Version. Only onepassage of Front-Cover Text and one of Back-Cover Text may beadded by (or through arrangements made by) any one entity. If theDocument already includes a cover text for the same cover,previously added by you or by arrangement made by the same entityyou are acting on behalf of, you may not add another; but you mayreplace the old one, on explicit permission from the previouspublisher that added the old one.The author(s) and publisher(s) of the Document do not by thisLicense give permission to use their names for publicity for or toassert or imply endorsement of any Modified Version.5. COMBINING DOCUMENTSYou may combine the Document with other documents released underthis License, under the terms defined in section 4 above formodified versions, provided that you include in the combinationall of the Invariant Sections of all of the original documents,unmodified, and list them all as Invariant Sections of yourcombined work in its license notice, and that you preserve alltheir Warranty Disclaimers.The combined work need only contain one copy of this License, andmultiple identical Invariant Sections may be replaced with a singlecopy. If there are multiple Invariant Sections with the same namebut different contents, make the title of each such section uniqueby adding at the end of it, in parentheses, the name of theoriginal author or publisher of that section if known, or else aunique number. Make the same adjustment to the section titles inthe list of Invariant Sections in the license notice of thecombined work.In the combination, you must combine any sections Entitled"History" in the various original documents, forming one sectionEntitled "History"; likewise combine any sections Entitled"Acknowledgements", and any sections Entitled "Dedications". Youmust delete all sections Entitled "Endorsements."6. COLLECTIONS OF DOCUMENTSYou may make a collection consisting of the Document and otherdocuments released under this License, and replace the individualcopies of this License in the various documents with a single copythat is included in the collection, provided that you follow therules of this License for verbatim copying of each of thedocuments in all other respects.You may extract a single document from such a collection, anddistribute it individually under this License, provided you inserta copy of this License into the extracted document, and followthis License in all other respects regarding verbatim copying ofthat document.7. AGGREGATION WITH INDEPENDENT WORKSA compilation of the Document or its derivatives with otherseparate and independent documents or works, in or on a volume ofa storage or distribution medium, is called an "aggregate" if thecopyright resulting from the compilation is not used to limit thelegal rights of the compilation's users beyond what the individualworks permit. When the Document is included in an aggregate, thisLicense does not apply to the other works in the aggregate whichare not themselves derivative works of the Document.If the Cover Text requirement of section 3 is applicable to thesecopies of the Document, then if the Document is less than one halfof the entire aggregate, the Document's Cover Texts may be placedon covers that bracket the Document within the aggregate, or theelectronic equivalent of covers if the Document is in electronicform. Otherwise they must appear on printed covers that bracketthe whole aggregate.8. TRANSLATIONTranslation is considered a kind of modification, so you maydistribute translations of the Document under the terms of section4. Replacing Invariant Sections with translations requires specialpermission from their copyright holders, but you may includetranslations of some or all Invariant Sections in addition to theoriginal versions of these Invariant Sections. You may include atranslation of this License, and all the license notices in theDocument, and any Warranty Disclaimers, provided that you alsoinclude the original English version of this License and theoriginal versions of those notices and disclaimers. In case of adisagreement between the translation and the original version ofthis License or a notice or disclaimer, the original version willprevail.If a section in the Document is Entitled "Acknowledgements","Dedications", or "History", the requirement (section 4) toPreserve its Title (section 1) will typically require changing theactual title.9. TERMINATIONYou may not copy, modify, sublicense, or distribute the Documentexcept as expressly provided under this License. Any attemptotherwise to copy, modify, sublicense, or distribute it is void,and will automatically terminate your rights under this License.However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitlyand finally terminates your license, and (b) permanently, if thecopyright holder fails to notify you of the violation by somereasonable means prior to 60 days after the cessation.Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) fromthat copyright holder, and you cure the violation prior to 30 daysafter your receipt of the notice.Termination of your rights under this section does not terminatethe licenses of parties who have received copies or rights fromyou under this License. If your rights have been terminated andnot permanently reinstated, receipt of a copy of some or all ofthe same material does not give you any rights to use it.10. FUTURE REVISIONS OF THIS LICENSEThe Free Software Foundation may publish new, revised versions ofthe GNU Free Documentation License from time to time. Such newversions will be similar in spirit to the present version, but maydiffer in detail to address new problems or concerns. See`http://www.gnu.org/copyleft/'.Each version of the License is given a distinguishing versionnumber. If the Document specifies that a particular numberedversion of this License "or any later version" applies to it, youhave the option of following the terms and conditions either ofthat specified version or of any later version that has beenpublished (not as a draft) by the Free Software Foundation. Ifthe Document does not specify a version number of this License,you may choose any version ever published (not as a draft) by theFree Software Foundation. If the Document specifies that a proxycan decide which future versions of this License can be used, thatproxy's public statement of acceptance of a version permanentlyauthorizes you to choose that version for the Document.11. RELICENSING"Massive Multiauthor Collaboration Site" (or "MMC Site") means anyWorld Wide Web server that publishes copyrightable works and alsoprovides prominent facilities for anybody to edit those works. Apublic wiki that anybody can edit is an example of such a server.A "Massive Multiauthor Collaboration" (or "MMC") contained in thesite means any set of copyrightable works thus published on the MMCsite."CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0license published by Creative Commons Corporation, a not-for-profitcorporation with a principal place of business in San Francisco,California, as well as future copyleft versions of that licensepublished by that same organization."Incorporate" means to publish or republish a Document, in whole orin part, as part of another Document.An MMC is "eligible for relicensing" if it is licensed under thisLicense, and if all works that were first published under thisLicense somewhere other than this MMC, and subsequentlyincorporated in whole or in part into the MMC, (1) had no covertexts or invariant sections, and (2) were thus incorporated priorto November 1, 2008.The operator of an MMC Site may republish an MMC contained in thesite under CC-BY-SA on the same site at any time before August 1,2009, provided the MMC is eligible for relicensing.ADDENDUM: How to use this License for your documents====================================================To use this License in a document you have written, include a copy ofthe License in the document and put the following copyright and licensenotices just after the title page:Copyright (C) YEAR YOUR NAME.Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.3or any later version published by the Free Software Foundation;with no Invariant Sections, no Front-Cover Texts, and no Back-CoverTexts. A copy of the license is included in the section entitled ``GNUFree Documentation License''.If you have Invariant Sections, Front-Cover Texts and Back-CoverTexts, replace the "with...Texts." line with this:with the Invariant Sections being LIST THEIR TITLES, withthe Front-Cover Texts being LIST, and with the Back-Cover Textsbeing LIST.If you have Invariant Sections without Cover Texts, or some othercombination of the three, merge those two alternatives to suit thesituation.If your document contains nontrivial examples of program code, werecommend releasing these examples in parallel under your choice offree software license, such as the GNU General Public License, topermit their use in free software.File: coreutils.info, Node: Concept index, Prev: GNU Free Documentation License, Up: TopIndex*****