\input texinfo @c %**start of header @setfilename coreutils.info @settitle @sc{gnu} Coreutils @c %**end of header @include version.texi @include constants.texi @c Define new indices. @defcodeindex op @defcodeindex fl @c Put everything in one index (arbitrarily chosen to be the concept index). @syncodeindex fl cp @syncodeindex fn cp @syncodeindex ky cp @syncodeindex op cp @syncodeindex pg cp @syncodeindex vr cp @dircategory Basics @direntry * 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 direntry @c FIXME: the following need documentation @c * [: (coreutils)[ invocation. File/string tests. @c * pinky: (coreutils)pinky invocation. FIXME. @c * uptime: (coreutils)uptime invocation. FIXME. @dircategory Individual utilities @direntry * base64: (coreutils)base64 invocation. Base64 encode/decode data. * basename: (coreutils)basename invocation. Strip directory and suffix. * cat: (coreutils)cat invocation. Concatenate and write 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. * 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. * 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. * touch: (coreutils)touch invocation. Change file timestamps. * tr: (coreutils)tr invocation. Translate characters. * true: (coreutils)true invocation. Do nothing, successfully. * 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). * 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 direntry @copying This manual documents version @value{VERSION} of the @sc{gnu} core utilities, including the standard programs for text and file manipulation. Copyright @copyright{} 1994, 1995, 1996, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. @quotation Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. @end quotation @end copying @titlepage @title @sc{gnu} @code{Coreutils} @subtitle Core GNU utilities @subtitle for version @value{VERSION}, @value{UPDATED} @author David MacKenzie et al. @page @vskip 0pt plus 1filll @insertcopying @end titlepage @ifnottex @node Top @top GNU Coreutils @insertcopying @end ifnottex @cindex core utilities @cindex text utilities @cindex shell utilities @cindex file utilities @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 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 * 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 * Modified command invocation:: chroot env nice nohup su * 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:: The license for this documentation. * Index:: General index. @detailmenu --- The Detailed Node Listing --- Common Options * Exit status:: Indicating program success or failure. * Backup options:: Backup options * Block size:: Block size * Target directory:: Target directory * Trailing slashes:: Trailing slashes * Traversing symlinks:: Traversing symlinks to directories * Treating / specially:: Treating / specially * Standards conformance:: Standards conformance Output 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. * 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. @command{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 @command{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. @command{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 @command{ls} @command{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 names Basic 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 securely Special 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 syscall Changing file attributes * chown invocation:: Change file owner and group * chgrp invocation:: Change group ownership * chmod invocation:: Change access permissions * touch invocation:: Change file timestamps Disk 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 Printing text * echo invocation:: Print a line of text * printf invocation:: Format and print data * yes invocation:: Print a string until interrupted Conditions * false invocation:: Do nothing, unsuccessfully * true invocation:: Do nothing, successfully * test invocation:: Check file types and compare values * expr invocation:: Evaluate expressions @command{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 @command{expr}: Evaluate expression * String expressions:: + : match substr index length * Numeric expressions:: + - * / % * Relations for expr:: | & < <= = == != >= > * Examples of expr:: Examples of using @command{expr} Redirection * tee invocation:: Redirect output to multiple files File 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 portability Working 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 @command{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 settings User 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 in System context * 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. @command{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. * Examples of date:: Examples. Modified 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 Process control * kill invocation:: Sending a signal to processes. Delaying * sleep invocation:: Delay for a specified time Numeric operations * factor invocation:: Print prime factors * seq invocation:: Print numeric sequences File permissions * Mode Structure:: Structure of File Permissions * Symbolic Modes:: Mnemonic permissions representation * Numeric Modes:: Permissions as octal numbers Date input formats * General date syntax:: Common rules. * Calendar date items:: 19 Dec 1994. * Time of day items:: 9:20pm. * Time zone items:: @sc{est}, @sc{pdt}, @sc{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 @command{who} command * The cut command:: The @command{cut} command * The sort command:: The @command{sort} command * The uniq command:: The @command{uniq} command * Putting the tools together:: Putting the tools together GNU Free Documentation License * How to use this License for your documents:: @end detailmenu @end menu @node Introduction @chapter Introduction This manual is a work in progress: many sections make no attempt to explain basic concepts in a way suitable for novices. Thus, if you are interested, please get involved in improving this manual. The entire @sc{gnu} community will benefit. @cindex @acronym{POSIX} The @sc{gnu} utilities documented here are mostly compatible with the @acronym{POSIX} standard. @cindex bugs, reporting Please report bugs to @email{bug-coreutils@@gnu.org}. Remember to include the version number, machine architecture, input files, and any other information needed to reproduce the bug: your input, what you expected, what you got, and why it is wrong. Diffs are welcome, but please include a description of the problem as well, since this is sometimes difficult to infer. @xref{Bugs, , , gcc, Using and Porting GNU CC}. @cindex Berry, K. @cindex Paterson, R. @cindex Stallman, R. @cindex Pinard, F. @cindex MacKenzie, D. @cindex Meyering, J. @cindex Youmans, B. This manual was originally derived from the Unix man pages in the distributions, which were written by David MacKenzie and updated by Jim Meyering. What you are reading now is the authoritative documentation for these utilities; the man pages are no longer being maintained. The original @command{fmt} man page was written by Ross Paterson. Fran@,{c}ois Pinard did the initial conversion to Texinfo format. Karl Berry did the indexing, some reorganization, and editing of the results. Brian Youmans of the Free Software Foundation office staff combined the manuals for textutils, fileutils, and sh-utils to produce the present omnibus manual. Richard Stallman contributed his usual invaluable insights to the overall process. @node Common options @chapter Common options @macro optBackup @item -b @itemx @w{@kbd{--backup}[=@var{method}]} @opindex -b @opindex --backup @vindex VERSION_CONTROL @cindex backups, making @xref{Backup options}. Make a backup of each file that would otherwise be overwritten or removed. @end macro @macro optBackupSuffix @item -S @var{suffix} @itemx --suffix=@var{suffix} @opindex -S @opindex --suffix Append @var{suffix} to each backup file made with @option{-b}. @xref{Backup options}. @end macro @macro optTargetDirectory @item -t @var{directory} @itemx @w{@kbd{--target-directory}=@var{directory}} @opindex -t @opindex --target-directory @cindex target directory @cindex destination directory Specify the destination @var{directory}. @xref{Target directory}. @end macro @macro optNoTargetDirectory @item -T @itemx --no-target-directory @opindex -T @opindex --no-target-directory @cindex target directory @cindex destination directory Do not treat the last operand specially when it is a directory or a symbolic link to a directory. @xref{Target directory}. @end macro @macro optSi @itemx --si @opindex --si @cindex SI output Append an SI-style abbreviation to each size, such as @samp{MB} for megabytes. Powers of 1000 are used, not 1024; @samp{MB} stands for 1,000,000 bytes. This option is equivalent to @option{--block-size=si}. Use the @option{-h} or @option{--human-readable} option if you prefer powers of 1024. @end macro @macro optHumanReadable @item -h @itemx --human-readable @opindex -h @opindex --human-readable @cindex human-readable output Append a size letter to each size, such as @samp{M} for mebibytes. Powers of 1024 are used, not 1000; @samp{M} stands for 1,048,576 bytes. Use the @option{--si} option if you prefer powers of 1000. @end macro @macro optStripTrailingSlashes @itemx @w{@kbd{--strip-trailing-slashes}} @opindex --strip-trailing-slashes @cindex stripping trailing slashes Remove any trailing slashes from each @var{source} argument. @xref{Trailing slashes}. @end macro @cindex common options Certain options are available in all of these programs. Rather than writing identical descriptions for each of the programs, they are described here. (In fact, every @sc{gnu} program accepts (or should accept) these options.) @vindex POSIXLY_CORRECT Normally options and operands can appear in any order, and programs act as if all the options appear before any operands. For example, @samp{sort -r passwd -t :} acts like @samp{sort -r -t : passwd}, since @samp{:} is an option-argument of @option{-t}. However, if the @env{POSIXLY_CORRECT} environment variable is set, options must appear before operands, unless otherwise specified for a particular command. A few programs can usefully have trailing operands with leading @samp{-}. With such a program, options must precede operands even if @env{POSIXLY_CORRECT} is not set, and this fact is noted in the program description. For example, the @command{env} command's options must appear before its operands, since in some cases the operands specify a command that itself contains options. Some of these programs recognize the @option{--help} and @option{--version} options only when one of them is the sole command line argument. @table @samp @item --help @opindex --help @cindex help, online Print a usage message listing all available options, then exit successfully. @item --version @opindex --version @cindex version number, finding Print the version number, then exit successfully. @item -- @opindex -- @cindex option delimiter Delimit the option list. Later arguments, if any, are treated as operands even if they begin with @samp{-}. For example, @samp{sort -- -r} reads from the file named @file{-r}. @end table @cindex standard input @cindex standard output A single @samp{-} operand is not really an option, though it looks like one. It stands for standard input, or for standard output if that is clear from the context. For example, @samp{sort -} reads from standard input, and is equivalent to plain @samp{sort}, and @samp{tee -} writes an extra copy of its input to standard output. Unless otherwise specified, @samp{-} 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. * 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:: @command{break}, @command{:}, @command{eval}, @dots{} * Standards conformance:: Conformance to the @acronym{POSIX} standard. @end menu @node Exit status @section Exit status @macro exitstatus An exit status of zero indicates success, and a nonzero value indicates failure. @end macro Nearly every command invocation yields an integral @dfn{exit status} that can be used to change how other commands work. For the vast majority of commands, an exit status of zero indicates success. Failure is indicated by a nonzero value---typically @samp{1}, though it may differ on unusual platforms as @acronym{POSIX} requires only that it be nonzero. However, some of the programs documented here do produce other exit status values and a few associate different meanings with the values @samp{0} and @samp{1}. Here are some of the exceptions: @command{chroot}, @command{env}, @command{expr}, @command{nice}, @command{nohup}, @command{printenv}, @command{sort}, @command{su}, @command{test}, @command{tty}. @node Backup options @section Backup options @cindex backup options Some @sc{gnu} programs (at least @command{cp}, @command{install}, @command{ln}, and @command{mv}) optionally make backups of files before writing new versions. These options control the details of these backups. The options are also briefly mentioned in the descriptions of the particular programs. @table @samp @item -b @itemx @w{@kbd{--backup}[=@var{method}]} @opindex -b @opindex --backup @vindex VERSION_CONTROL @cindex backups, making Make a backup of each file that would otherwise be overwritten or removed. Without this option, the original versions are destroyed. Use @var{method} to determine the type of backups to make. When this option is used but @var{method} is not specified, then the value of the @env{VERSION_CONTROL} environment variable is used. And if @env{VERSION_CONTROL} is not set, the default backup type is @samp{existing}. Note that the short form of this option, @option{-b} does not accept any argument. Using @option{-b} is equivalent to using @option{--backup=existing}. @vindex version-control @r{Emacs variable} This option corresponds to the Emacs variable @samp{version-control}; the values for @var{method} are the same as those used in Emacs. This option also accepts more descriptive names. The valid @var{method}s are (unique abbreviations are accepted): @table @samp @item none @itemx off @opindex none @r{backup method} Never make backups. @item numbered @itemx t @opindex numbered @r{backup method} Always make numbered backups. @item existing @itemx nil @opindex existing @r{backup method} Make numbered backups of files that already have them, simple backups of the others. @item simple @itemx never @opindex simple @r{backup method} Always make simple backups. Please note @samp{never} is not to be confused with @samp{none}. @end table @item -S @var{suffix} @itemx --suffix=@var{suffix} @opindex -S @opindex --suffix @cindex backup suffix @vindex SIMPLE_BACKUP_SUFFIX Append @var{suffix} to each backup file made with @option{-b}. If this option is not specified, the value of the @env{SIMPLE_BACKUP_SUFFIX} environment variable is used. And if @env{SIMPLE_BACKUP_SUFFIX} is not set, the default is @samp{~}, just as in Emacs. @end table @node Block size @section Block size @cindex block size Some @sc{gnu} programs (at least @command{df}, @command{du}, and @command{ls}) display sizes in ``blocks''. You can adjust the block size and method of display to make sizes easier to read. The block size used for display is independent of any file system block size. Fractional block counts are rounded up to the nearest integer. @opindex --block-size=@var{size} @vindex BLOCKSIZE @vindex BLOCK_SIZE @vindex DF_BLOCK_SIZE @vindex DU_BLOCK_SIZE @vindex LS_BLOCK_SIZE @vindex POSIXLY_CORRECT@r{, and block size} The default block size is chosen by examining the following environment variables in turn; the first one that is set determines the block size. @table @code @item DF_BLOCK_SIZE This specifies the default block size for the @command{df} command. Similarly, @env{DU_BLOCK_SIZE} specifies the default for @command{du} and @env{LS_BLOCK_SIZE} for @command{ls}. @item BLOCK_SIZE This specifies the default block size for all three commands, if the above command-specific environment variables are not set. @item BLOCKSIZE This specifies the default block size for all values that are normally printed as blocks, if neither @env{BLOCK_SIZE} nor the above command-specific environment variables are set. Unlike the other environment variables, @env{BLOCKSIZE} does not affect values that are normally printed as byte counts, e.g., the file sizes contained in @code{ls -l} output. @item POSIXLY_CORRECT If neither @env{@var{command}_BLOCK_SIZE}, nor @env{BLOCK_SIZE}, nor @env{BLOCKSIZE} is set, but this variable is set, the block size defaults to 512. @end table If none of the above environment variables are set, the block size currently defaults to 1024 bytes in most contexts, but this number may change in the future. For @command{ls} file sizes, the block size defaults to 1 byte. @cindex human-readable output @cindex SI output A block size specification can be a positive integer specifying the number of bytes per block, or it can be @code{human-readable} or @code{si} to select a human-readable format. Integers may be followed by suffixes that are upward compatible with the @uref{http://www.bipm.fr/enus/3_SI/si-prefixes.html, SI prefixes} for decimal multiples and with the @uref{http://physics.nist.gov/cuu/Units/binary.html, IEC 60027-2 prefixes for binary multiples}. With human-readable formats, output sizes are followed by a size letter such as @samp{M} for megabytes. @code{BLOCK_SIZE=human-readable} uses powers of 1024; @samp{M} stands for 1,048,576 bytes. @code{BLOCK_SIZE=si} is similar, but uses powers of 1000 and appends @samp{B}; @samp{MB} stands for 1,000,000 bytes. @vindex LC_NUMERIC A block size specification preceded by @samp{'} causes output sizes to be displayed with thousands separators. The @env{LC_NUMERIC} locale specifies the thousands separator and grouping. For example, in an American English locale, @samp{--block-size="'1kB"} would cause a size of 1234000 bytes to be displayed as @samp{1,234}. In the default C locale, there is no thousands separator so a leading @samp{'} has no effect. An integer block size can be followed by a suffix to specify a multiple of that size. A bare size letter, or one followed by @samp{iB}, specifies a multiple using powers of 1024. A size letter followed by @samp{B} specifies powers of 1000 instead. For example, @samp{1M} and @samp{1MiB} are equivalent to @samp{1048576}, whereas @samp{1MB} is equivalent to @samp{1000000}. A plain suffix without a preceding integer acts as if @samp{1} were prepended, except that it causes a size indication to be appended to the output. For example, @samp{--block-size="kB"} displays 3000 as @samp{3kB}. The following suffixes are defined. Large sizes like @code{1Y} may be rejected by your computer due to limitations of its arithmetic. @table @samp @item kB @cindex kilobyte, definition of kilobyte: @math{10^3 = 1000}. @item k @itemx K @itemx KiB @cindex kibibyte, definition of kibibyte: @math{2^10 = 1024}. @samp{K} is special: the SI prefix is @samp{k} and the IEC 60027-2 prefix is @samp{Ki}, but tradition and @acronym{POSIX} use @samp{k} to mean @samp{KiB}. @item MB @cindex megabyte, definition of megabyte: @math{10^6 = 1,000,000}. @item M @itemx MiB @cindex mebibyte, definition of mebibyte: @math{2^20 = 1,048,576}. @item GB @cindex gigabyte, definition of gigabyte: @math{10^9 = 1,000,000,000}. @item G @itemx GiB @cindex gibibyte, definition of gibibyte: @math{2^30 = 1,073,741,824}. @item TB @cindex terabyte, definition of terabyte: @math{10^12 = 1,000,000,000,000}. @item T @itemx TiB @cindex tebibyte, definition of tebibyte: @math{2^40 = 1,099,511,627,776}. @item PB @cindex petabyte, definition of petabyte: @math{10^15 = 1,000,000,000,000,000}. @item P @itemx PiB @cindex pebibyte, definition of pebibyte: @math{2^50 = 1,125,899,906,842,624}. @item EB @cindex exabyte, definition of exabyte: @math{10^18 = 1,000,000,000,000,000,000}. @item E @itemx EiB @cindex exbibyte, definition of exbibyte: @math{2^60 = 1,152,921,504,606,846,976}. @item ZB @cindex zettabyte, definition of zettabyte: @math{10^21 = 1,000,000,000,000,000,000,000} @item Z @itemx ZiB @math{2^70 = 1,180,591,620,717,411,303,424}. (@samp{Zi} is a GNU extension to IEC 60027-2.) @item YB @cindex yottabyte, definition of yottabyte: @math{10^24 = 1,000,000,000,000,000,000,000,000}. @item Y @itemx YiB @math{2^80 = 1,208,925,819,614,629,174,706,176}. (@samp{Yi} is a GNU extension to IEC 60027-2.) @end table @opindex -k @opindex -h @opindex --block-size @opindex --human-readable @opindex --si Block size defaults can be overridden by an explicit @option{--block-size=@var{size}} option. The @option{-k} option is equivalent to @option{--block-size=1K}, which is the default unless the @env{POSIXLY_CORRECT} environment variable is set. The @option{-h} or @option{--human-readable} option is equivalent to @option{--block-size=human-readable}. The @option{--si} option is equivalent to @option{--block-size=si}. @node Target directory @section Target directory @cindex target directory The @command{cp}, @command{install}, @command{ln}, and @command{mv} commands normally treat the last operand specially when it is a directory or a symbolic link to a directory. For example, @samp{cp source dest} is equivalent to @samp{cp source dest/source} if @file{dest} is a directory. Sometimes this behavior is not exactly what is wanted, so these commands support the following options to allow more fine-grained control: @table @samp @item -T @itemx --no-target-directory @opindex --no-target-directory @cindex target directory @cindex destination directory Do not treat the last operand specially when it is a directory or a symbolic link to a directory. This can help avoid race conditions in programs that operate in a shared area. For example, when the command @samp{mv /tmp/source /tmp/dest} succeeds, there is no guarantee that @file{/tmp/source} was renamed to @file{/tmp/dest}: it could have been renamed to @file{/tmp/dest/source} instead, if some other process created @file{/tmp/dest} as a directory. However, if @file{mv -T /tmp/source /tmp/dest} succeeds, there is no question that @file{/tmp/source} was renamed to @file{/tmp/dest}. In the opposite situation, where you want the last operand to be treated as a directory and want a diagnostic otherwise, you can use the @option{--target-directory} (@option{-t}) option. @item -t @var{directory} @itemx @w{@kbd{--target-directory}=@var{directory}} @opindex --target-directory @cindex target directory @cindex destination directory Use @var{directory} as the directory component of each destination file name. The interface for most programs is that after processing options and a finite (possibly zero) number of fixed-position arguments, the remaining argument list is either expected to be empty, or is a list of items (usually files) that will all be handled identically. The @command{xargs} program is designed to work well with this convention. The commands in the @command{mv}-family are unusual in that they take a variable number of arguments with a special case at the @emph{end} (namely, the target directory). This makes it nontrivial to perform some operations, e.g., ``move all files from here to ../d/'', because @code{mv * ../d/} might exhaust the argument space, and @code{ls | xargs ...} doesn't have a clean way to specify an extra final argument for each invocation of the subject command. (It can be done by going through a shell command, but that requires more human labor and brain power than it should.) The @w{@kbd{--target-directory}} (@option{-t}) option allows the @command{cp}, @command{install}, @command{ln}, and @command{mv} programs to be used conveniently with @command{xargs}. For example, you can move the files from the current directory to a sibling directory, @code{d} like this: @smallexample ls | xargs mv -t ../d -- @end smallexample However, this doesn't move files whose names begin with @samp{.}. If you use the @sc{gnu} @command{find} program, you can move those files too, with this command: @example find . -mindepth 1 -maxdepth 1 \ | xargs mv -t ../d @end example But both of the above approaches fail if there are no files in the current directory, or if any file has a name containing a blank or some other special characters. The following example removes those limitations and requires both @sc{gnu} @command{find} and @sc{gnu} @command{xargs}: @example find . -mindepth 1 -maxdepth 1 -print0 \ | xargs --null --no-run-if-empty \ mv -t ../d @end example @end table @noindent The @option{--target-directory} (@option{-t}) and @option{--no-target-directory} (@option{-T}) options cannot be combined. @node Trailing slashes @section Trailing slashes @cindex trailing slashes Some @sc{gnu} programs (at least @command{cp} and @command{mv}) allow you to remove any trailing slashes from each @var{source} argument before operating on it. The @w{@kbd{--strip-trailing-slashes}} option enables this behavior. This is useful when a @var{source} argument may have a trailing slash and @c FIXME: mv's behavior in this case is system-dependent specify a symbolic link to a directory. This scenario is in fact rather common because some shells can automatically append a trailing slash when performing file name completion on such symbolic links. Without this option, @command{mv}, for example, (via the system's rename function) must interpret a trailing slash as a request to dereference the symbolic link and so must rename the indirectly referenced @emph{directory} and not the symbolic link. Although it may seem surprising that such behavior be the default, it is required by @acronym{POSIX} and is consistent with other parts of that standard. @node Traversing symlinks @section Traversing symlinks @cindex symbolic link to directory, controlling traversal of The following options modify how @command{chown} and @command{chgrp} @c FIXME: note that `du' has these options, too, but they have slightly @c different meaning. traverse a hierarchy when the @option{--recursive} (@option{-R}) option is also specified. If more than one of the following options is specified, only the final one takes effect. These options specify whether processing a symbolic link to a directory entails operating on just the symbolic link or on all files in the hierarchy rooted at that directory. These options are independent of @option{--dereference} and @option{--no-dereference} (@option{-h}), which control whether to modify a symlink or its referent. @table @samp @macro choptH @item -H @opindex -H @cindex symbolic link to directory, traverse each that is specified on the command line If @option{--recursive} (@option{-R}) is specified and a command line argument is a symbolic link to a directory, traverse it. @end macro @choptH @macro choptL @item -L @opindex -L @cindex symbolic link to directory, traverse each that is encountered In a recursive traversal, traverse every symbolic link to a directory that is encountered. @end macro @choptL @macro choptP @item -P @opindex -P @cindex symbolic link to directory, never traverse Do not traverse any symbolic links. This is the default if none of @option{-H}, @option{-L}, or @option{-P} is specified. @end macro @choptP @end table @node Treating / specially @section Treating / specially Certain commands can operate destructively on entire hierarchies. For example, if a user with appropriate privileges mistakenly runs @samp{rm -rf / tmp/junk} or @samp{cd /bin; rm -rf ../}, that may remove all files on the entire system. Since there are so few @footnote{If you know of one, please write to @email{bug-coreutils@@gnu.org}.} legitimate uses for such a command, @sc{gnu} @command{rm} provides the @option{--preserve-root} option to make it so @command{rm} declines to operate on any directory that resolves to @file{/}. The default is still to allow @samp{rm -rf /} to operate unimpeded. Another new option, @option{--no-preserve-root}, cancels the effect of any preceding @option{--preserve-root} option. Note that the @option{--preserve-root} behavior may become the default for @command{rm}. The commands @command{chgrp}, @command{chmod} and @command{chown} can also operate destructively on entire hierarchies, so they too support these options. Although, unlike @command{rm}, they don't actually unlink files, these commands are arguably more dangerous when operating recursively on @file{/}, since they often work much more quickly, and hence damage more files before an alert user can interrupt them. @node Special built-in utilities @section Special built-in utilities Some programs like @command{nice} can invoke other programs; for example, the command @samp{nice cat file} invokes the program @command{cat} by executing the command @samp{cat file}. However, @dfn{special built-in utilities} like @command{exit} cannot be invoked this way. For example, the command @samp{nice exit} does not have a well-defined behavior: it may generate an error message instead of exiting. Here is a list of the special built-in utilities that are standardized by @acronym{POSIX} 1003.1-2004. @quotation @t{.@: : break continue eval exec exit export readonly return set shift times trap unset} @end quotation For example, because @samp{.}, @samp{:}, and @samp{exec} are special, the commands @samp{nice . foo.sh}, @samp{nice :}, and @samp{nice exec pwd} do not work as you might expect. Many shells extend this list. For example, Bash has several extra special built-in utilities like @command{history}, and @command{suspend}, and with Bash the command @samp{nice suspend} generates an error message instead of suspending. @node Standards conformance @section Standards conformance @vindex POSIXLY_CORRECT In a few cases, the @sc{gnu} utilities' default behavior is incompatible with the @acronym{POSIX} standard. To suppress these incompatibilities, define the @env{POSIXLY_CORRECT} environment variable. Unless you are checking for @acronym{POSIX} conformance, you probably do not need to define @env{POSIXLY_CORRECT}. Newer versions of @acronym{POSIX} are occasionally incompatible with older versions. For example, older versions of @acronym{POSIX} required the command @samp{sort +1} to sort based on the second and succeeding fields in each input line, but starting with @acronym{POSIX} 1003.1-2001 the same command is required to sort the file named @file{+1}, and you must instead use the command @samp{sort -k 2} to get the field-based sort. @vindex _POSIX2_VERSION The @sc{gnu} utilities normally conform to the version of @acronym{POSIX} that is standard for your system. To cause them to conform to a different version of @acronym{POSIX}, define the @env{_POSIX2_VERSION} environment variable to a value of the form @var{yyyymm} specifying the year and month the standard was adopted. Two values are currently supported for @env{_POSIX2_VERSION}: @samp{199209} stands for @acronym{POSIX} 1003.2-1992, and @samp{200112} stands for @acronym{POSIX} 1003.1-2001. For example, if you have a newer system but are running software that assumes an older version of @acronym{POSIX} and uses @samp{sort +1} or @samp{tail +10}, you can work around any compatibility problems by setting @samp{_POSIX2_VERSION=199209} in your environment. @node Output of entire files @chapter Output of entire files @cindex output of entire files @cindex entire files, output of These commands read and write entire files, possibly transforming them in 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. @end menu @node cat invocation @section @command{cat}: Concatenate and write files @pindex cat @cindex concatenate and write files @cindex copying files @command{cat} copies each @var{file} (@samp{-} means standard input), or standard input if none are given, to standard output. Synopsis: @example cat [@var{option}] [@var{file}]@dots{} @end example The program accepts the following options. Also see @ref{Common options}. @table @samp @item -A @itemx --show-all @opindex -A @opindex --show-all Equivalent to @option{-vET}. @item -b @itemx --number-nonblank @opindex -b @opindex --number-nonblank Number all nonblank output lines, starting with 1. @item -e @opindex -e Equivalent to @option{-vE}. @item -E @itemx --show-ends @opindex -E @opindex --show-ends Display a @samp{$} after the end of each line. @item -n @itemx --number @opindex -n @opindex --number Number all output lines, starting with 1. @item -s @itemx --squeeze-blank @opindex -s @opindex --squeeze-blank @cindex squeezing blank lines Replace multiple adjacent blank lines with a single blank line. @item -t @opindex -t Equivalent to @option{-vT}. @item -T @itemx --show-tabs @opindex -T @opindex --show-tabs Display TAB characters as @samp{^I}. @item -u @opindex -u Ignored; for @acronym{POSIX} compatibility. @item -v @itemx --show-nonprinting @opindex -v @opindex --show-nonprinting Display control characters except for LFD and TAB using @samp{^} notation and precede characters that have the high bit set with @samp{M-}. @end table On systems like MS-DOS that distinguish between text and binary files, @command{cat} normally reads and writes in binary mode. However, @command{cat} reads in text mode if one of the options @option{-bensAE} is used or if @command{cat} is reading from standard input and standard input is a terminal. Similarly, @command{cat} writes in text mode if one of the options @option{-bensAE} is used or if standard output is a terminal. @exitstatus Examples: @smallexample # Output f's contents, then standard input, then g's contents. cat f - g # Copy standard input to standard output. cat @end smallexample @node tac invocation @section @command{tac}: Concatenate and write files in reverse @pindex tac @cindex reversing files @command{tac} copies each @var{file} (@samp{-} means standard input), or standard input if none are given, to standard output, reversing the records (lines by default) in each separately. Synopsis: @example tac [@var{option}]@dots{} [@var{file}]@dots{} @end example @dfn{Records} are separated by instances of a string (newline by default). By default, this separator string is attached to the end of the record that it follows in the file. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -b @itemx --before @opindex -b @opindex --before The separator is attached to the beginning of the record that it precedes in the file. @item -r @itemx --regex @opindex -r @opindex --regex Treat the separator string as a regular expression. Users of @command{tac} on MS-DOS/MS-Windows should note that, since @command{tac} reads files in binary mode, each line of a text file might end with a CR/LF pair instead of the Unix-style LF. @item -s @var{separator} @itemx --separator=@var{separator} @opindex -s @opindex --separator Use @var{separator} as the record separator, instead of newline. @end table @exitstatus @node nl invocation @section @command{nl}: Number lines and write files @pindex nl @cindex numbering lines @cindex line numbering @command{nl} writes each @var{file} (@samp{-} means standard input), or standard input if none are given, to standard output, with line numbers added to some or all of the lines. Synopsis: @example nl [@var{option}]@dots{} [@var{file}]@dots{} @end example @cindex logical pages, numbering on @command{nl} decomposes its input into (logical) pages; by default, the line number is reset to 1 at the top of each logical page. @command{nl} treats all of the input files as a single document; it does not reset line numbers or logical pages between files. @cindex headers, numbering @cindex body, numbering @cindex footers, numbering A logical page consists of three sections: header, body, and footer. Any of the sections can be empty. Each can be numbered in a different style from the others. The beginnings of the sections of logical pages are indicated in the input file by a line containing exactly one of these delimiter strings: @table @samp @item \:\:\: start of header; @item \:\: start of body; @item \: start of footer. @end table The two characters from which these strings are made can be changed from @samp{\} and @samp{:} via options (see below), but the pattern and length of each string cannot be changed. A section delimiter is replaced by an empty line on output. Any text that comes before the first section delimiter string in the input file is considered to be part of a body section, so @command{nl} treats a file that contains no section delimiters as a single body section. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -b @var{style} @itemx --body-numbering=@var{style} @opindex -b @opindex --body-numbering Select the numbering style for lines in the body section of each logical page. When a line is not numbered, the current line number is not incremented, but the line number separator character is still prepended to the line. The styles are: @table @samp @item a number all lines, @item t number only nonempty lines (default for body), @item n do not number lines (default for header and footer), @item p@var{bre} number only lines that contain a match for the basic regular expression @var{bre}. @xref{Regular Expressions, , Regular Expressions, grep, The GNU Grep Manual}. @end table @item -d @var{cd} @itemx --section-delimiter=@var{cd} @opindex -d @opindex --section-delimiter @cindex section delimiters of pages Set the section delimiter characters to @var{cd}; default is @samp{\:}. If only @var{c} is given, the second remains @samp{:}. (Remember to protect @samp{\} or other metacharacters from shell expansion with quotes or extra backslashes.) @item -f @var{style} @itemx --footer-numbering=@var{style} @opindex -f @opindex --footer-numbering Analogous to @option{--body-numbering}. @item -h @var{style} @itemx --header-numbering=@var{style} @opindex -h @opindex --header-numbering Analogous to @option{--body-numbering}. @item -i @var{number} @itemx --page-increment=@var{number} @opindex -i @opindex --page-increment Increment line numbers by @var{number} (default 1). @item -l @var{number} @itemx --join-blank-lines=@var{number} @opindex -l @opindex --join-blank-lines @cindex empty lines, numbering @cindex blank lines, numbering Consider @var{number} (default 1) consecutive empty lines to be one logical line for numbering, and only number the last one. Where fewer than @var{number} consecutive empty lines occur, do not number them. An empty line is one that contains no characters, not even spaces or tabs. @item -n @var{format} @itemx --number-format=@var{format} @opindex -n @opindex --number-format Select the line numbering format (default is @code{rn}): @table @samp @item ln @opindex ln @r{format for @command{nl}} left justified, no leading zeros; @item rn @opindex rn @r{format for @command{nl}} right justified, no leading zeros; @item rz @opindex rz @r{format for @command{nl}} right justified, leading zeros. @end table @item -p @itemx --no-renumber @opindex -p @opindex --no-renumber Do not reset the line number at the start of a logical page. @item -s @var{string} @itemx --number-separator=@var{string} @opindex -s @opindex --number-separator Separate the line number from the text line in the output with @var{string} (default is the TAB character). @item -v @var{number} @itemx --starting-line-number=@var{number} @opindex -v @opindex --starting-line-number Set the initial line number on each logical page to @var{number} (default 1). @item -w @var{number} @itemx --number-width=@var{number} @opindex -w @opindex --number-width Use @var{number} characters for line numbers (default 6). @end table @exitstatus @node od invocation @section @command{od}: Write files in octal or other formats @pindex od @cindex octal dump of files @cindex hex dump of files @cindex ASCII dump of files @cindex file contents, dumping unambiguously @command{od} writes an unambiguous representation of each @var{file} (@samp{-} means standard input), or standard input if none are given. Synopses: @smallexample od [@var{option}]@dots{} [@var{file}]@dots{} od [-abcdfilosx]@dots{} [@var{file}] [[+]@var{offset}[.][b]] od [@var{option}]@dots{} --traditional [@var{file}] [[+]@var{offset}[.][b] [[+]@var{label}[.][b]]] @end smallexample Each line of output consists of the offset in the input, followed by groups of data from the file. By default, @command{od} prints the offset in octal, and each group of file data is a C @code{short int}'s worth of input printed as a single octal number. If @var{offset} is given, it specifies how many input bytes to skip before formatting and writing. By default, it is interpreted as an octal number, but the optional trailing decimal point causes it to be interpreted as decimal. If no decimal is specified and the offset begins with @samp{0x} or @samp{0X} it is interpreted as a hexadecimal number. If there is a trailing @samp{b}, the number of bytes skipped will be @var{offset} multiplied by 512. If a command is of both the first and second forms, the second form is assumed if the last operand begins with @samp{+} or (if there are two operands) a digit. For example, in @samp{od foo 10} and @samp{od +10} the @samp{10} is an offset, whereas in @samp{od 10} the @samp{10} is a file name. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -A @var{radix} @itemx --address-radix=@var{radix} @opindex -A @opindex --address-radix @cindex radix for file offsets @cindex file offset radix Select the base in which file offsets are printed. @var{radix} can be one of the following: @table @samp @item d decimal; @item o octal; @item x hexadecimal; @item n none (do not print offsets). @end table The default is octal. @item -j @var{bytes} @itemx --skip-bytes=@var{bytes} @opindex -j @opindex --skip-bytes Skip @var{bytes} input bytes before formatting and writing. If @var{bytes} begins with @samp{0x} or @samp{0X}, it is interpreted in hexadecimal; otherwise, if it begins with @samp{0}, in octal; otherwise, in decimal. Appending @samp{b} multiplies @var{bytes} by 512, @samp{k} by 1024, and @samp{m} by 1048576. @item -N @var{bytes} @itemx --read-bytes=@var{bytes} @opindex -N @opindex --read-bytes Output at most @var{bytes} bytes of the input. Prefixes and suffixes on @code{bytes} are interpreted as for the @option{-j} option. @item -S @var{n} @itemx --strings[=@var{n}] @opindex -S @opindex --strings @cindex string constants, outputting Instead of the normal output, output only @dfn{string constants}: at least @var{n} consecutive @acronym{ASCII} graphic characters, followed by a null (zero) byte. If @var{n} is omitted with @option{--strings}, the default is 3. @item -t @var{type} @itemx --format=@var{type} @opindex -t @opindex --format Select the format in which to output the file data. @var{type} is a string of one or more of the below type indicator characters. If you include more than one type indicator character in a single @var{type} string, or use this option more than once, @command{od} writes one copy of each 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 display of the @acronym{ASCII} character representation of the printable characters to the output line generated by the type specification. @table @samp @item a named character, ignoring high-order bit @item c @acronym{ASCII} character or backslash escape, @item d signed decimal @item f floating point @item o octal @item u unsigned decimal @item x hexadecimal @end table The type @code{a} outputs things like @samp{sp} for space, @samp{nl} for newline, and @samp{nul} for a null (zero) byte. Only the least significant seven bits of each byte is used; the high-order bit is ignored. Type @code{c} outputs @samp{ }, @samp{\n}, and @code{\0}, respectively. @cindex type size Except for types @samp{a} and @samp{c}, you can specify the number of bytes to use in interpreting each number in the given data type by following the type indicator character with a decimal integer. Alternately, you can specify the size of one of the C compiler's built-in data types by following the type indicator character with one of the following characters. For integers (@samp{d}, @samp{o}, @samp{u}, @samp{x}): @table @samp @item C char @item S short @item I int @item L long @end table For floating point (@code{f}): @table @asis @item F float @item D double @item L long double @end table @item -v @itemx --output-duplicates @opindex -v @opindex --output-duplicates Output consecutive lines that are identical. By default, when two or more consecutive output lines would be identical, @command{od} outputs only the first line, and puts just an asterisk on the following line to indicate the elision. @item -w[@var{n}] @itemx --width[=@var{n}] @opindex -w @opindex --width Dump @code{n} input bytes per output line. This must be a multiple of the least common multiple of the sizes associated with the specified output types. If this option is not given at all, the default is 16. If @var{n} is omitted, the default is 32. @end table The next several options are shorthands for format specifications. @sc{gnu} @command{od} accepts any combination of shorthands and format specification options. These options accumulate. @table @samp @item -a @opindex -a Output as named characters. Equivalent to @samp{-t a}. @item -b @opindex -b Output as octal bytes. Equivalent to @samp{-t o1}. @item -c @opindex -c Output as @acronym{ASCII} characters or backslash escapes. Equivalent to @samp{-t c}. @item -d @opindex -d Output as unsigned decimal two-byte units. Equivalent to @samp{-t u2}. @item -f @opindex -f Output as floats. Equivalent to @samp{-t fF}. @item -i @opindex -i Output as decimal ints. Equivalent to @samp{-t dI}. @item -l @opindex -l Output as decimal long ints. Equivalent to @samp{-t dL}. @item -o @opindex -o Output as octal two-byte units. Equivalent to @option{-t o2}. @item -s @opindex -s Output as decimal two-byte units. Equivalent to @option{-t d2}. @item -x @opindex -x Output as hexadecimal two-byte units. Equivalent to @samp{-t x2}. @item --traditional @opindex --traditional Recognize the non-option label argument that traditional @command{od} accepted. The following syntax: @smallexample od --traditional [@var{file}] [[+]@var{offset}[.][b] [[+]@var{label}[.][b]]] @end smallexample @noindent can be used to specify at most one file and optional arguments specifying an offset and a pseudo-start address, @var{label}. The @var{label} argument is interpreted just like @var{offset}, but it specifies an initial pseudo-address. The pseudo-addresses are displayed in parentheses following any normal address. @end table @exitstatus @node base64 invocation @section @command{base64}: Transform data into printable data. @pindex base64 @cindex base64 encoding @command{base64} transforms data read from a file, or standard input, into (or from) base64 encoded form. The base64 encoded form uses printable @acronym{ASCII} characters to represent binary data, see @uref{ftp://ftp.rfc-editor.org/in-notes/rfc3548.txt, RFC 3548}. Synopses: @smallexample base64 [@var{option}]@dots{} [@var{file}] base64 --decode [@var{option}]@dots{} [@var{file}] @end smallexample The base64 encoding expands data to roughly 133% of the original. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -w @var{COLS} @itemx --wrap=@var{COLS} @opindex -w @opindex --wrap @cindex wrap data @cindex column to wrap data after During encoding, wrap lines after @var{COLS} characters. This must be a positive number. The default is to wrap after 76 characters. Use the value 0 to disable line wrapping altogether. @item -d @itemx --decode @opindex -d @opindex --decode @cindex Decode base64 data @cindex Base64 decoding Change the mode of operation, from the default of encoding data, to decoding data. Input is expected to be base64 encoded data, and the output will be the original data. @item -i @itemx --ignore-garbage @opindex -i @opindex --ignore-garbage @cindex Ignore garbage in base64 stream During decoding, ignore unrecognized characters (including newline), to permit distorted data to be decoded. @end table @exitstatus @node Formatting file contents @chapter Formatting file contents @cindex 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. @end menu @node fmt invocation @section @command{fmt}: Reformat paragraph text @pindex fmt @cindex reformatting paragraph text @cindex paragraphs, reformatting @cindex text, reformatting @command{fmt} fills and joins lines to produce output lines of (at most) a given number of characters (75 by default). Synopsis: @example fmt [@var{option}]@dots{} [@var{file}]@dots{} @end example @command{fmt} reads from the specified @var{file} arguments (or standard input if none are given), and writes to standard output. By default, blank lines, spaces between words, and indentation are preserved in the output; successive input lines with different indentation are not joined; tabs are expanded on input and introduced on output. @cindex line-breaking @cindex sentences and line-breaking @cindex Knuth, Donald E. @cindex Plass, Michael F. @command{fmt} prefers breaking lines at the end of a sentence, and tries to avoid line breaks after the first word of a sentence or before the last word of a sentence. A @dfn{sentence break} is defined as either the end of a paragraph or a word ending in any of @samp{.?!}, followed by two spaces or end of line, ignoring any intervening parentheses or quotes. Like @TeX{}, @command{fmt} reads entire ``paragraphs'' before choosing line breaks; the algorithm is a variant of that given by Donald E. Knuth and Michael F. Plass in ``Breaking Paragraphs Into Lines'', @cite{Software---Practice & Experience} @b{11}, 11 (November 1981), 1119--1184. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -c @itemx --crown-margin @opindex -c @opindex --crown-margin @cindex crown margin @dfn{Crown margin} mode: preserve the indentation of the first two lines within a paragraph, and align the left margin of each subsequent line with that of the second line. @item -t @itemx --tagged-paragraph @opindex -t @opindex --tagged-paragraph @cindex tagged paragraphs @dfn{Tagged paragraph} mode: like crown margin mode, except that if indentation of the first line of a paragraph is the same as the indentation of the second, the first line is treated as a one-line paragraph. @item -s @itemx --split-only @opindex -s @opindex --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. @item -u @itemx --uniform-spacing @opindex -u @opindex --uniform-spacing Uniform spacing. Reduce spacing between words to one space, and spacing between sentences to two spaces. @item -@var{width} @itemx -w @var{width} @itemx --width=@var{width} @opindex -@var{width} @opindex -w @opindex --width Fill output lines up to @var{width} characters (default 75). @command{fmt} initially tries to make lines about 7% shorter than this, to give it room to balance line lengths. @item -p @var{prefix} @itemx --prefix=@var{prefix} Only lines beginning with @var{prefix} (possibly preceded by whitespace) are subject to formatting. The prefix and any preceding whitespace are stripped for the formatting and then re-attached to each formatted output line. One use is to format certain kinds of program comments, while leaving the code unchanged. @end table @exitstatus @node pr invocation @section @command{pr}: Paginate or columnate files for printing @pindex pr @cindex printing, preparing files for @cindex multicolumn output, generating @cindex merging files in parallel @command{pr} writes each @var{file} (@samp{-} means standard input), or standard input if none are given, to standard output, paginating and optionally outputting in multicolumn format; optionally merges all @var{file}s, printing all in parallel, one per column. Synopsis: @example pr [@var{option}]@dots{} [@var{file}]@dots{} @end example @vindex LC_MESSAGES 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 more blank lines. A footer of five blank lines is also printed. With the @option{-F} option, a 3-line header is printed: the leading two blank lines are omitted; no footer is used. The default @var{page_length} in both cases is 66 lines. The default number of text lines changes from 56 (without @option{-F}) to 63 (with @option{-F}). The text line of the header takes the form @samp{@var{date} @var{string} @var{page}}, with spaces inserted around @var{string} so that the line takes up the full @var{page_width}. Here, @var{date} is the date (see the @option{-D} or @option{--date-format} option for details), @var{string} is the centered header string, and @var{page} identifies the page number. The @env{LC_MESSAGES} locale category affects the spelling of @var{page}; in the default C locale, it is @samp{Page @var{number}} where @var{number} is the decimal page number. Form feeds in the input cause page breaks in the output. Multiple form feeds produce empty pages. Columns are of equal width, separated by an optional string (default is @samp{space}). For multicolumn output, lines will always be truncated to @var{page_width} (default 72), unless you use the @option{-J} option. For single column output no line truncation occurs by default. Use @option{-W} option to truncate lines in that case. The following changes were made in version 1.22i and apply to later versions of @command{pr}: @c FIXME: this whole section here sounds very awkward to me. I @c made a few small changes, but really it all needs to be redone. - Brian @c OK, I fixed another sentence or two, but some of it I just don't understand. @ - Brian @itemize @bullet @item Some small @var{letter options} (@option{-s}, @option{-w}) have been redefined for better @acronym{POSIX} compliance. The output of some further cases has been adapted to other Unix systems. These changes are not compatible with earlier versions of the program. @item Some @var{new capital letter} options (@option{-J}, @option{-S}, @option{-W}) have been introduced to turn off unexpected interferences of small letter options. The @option{-N} option and the second argument @var{last_page} of @samp{+FIRST_PAGE} offer more flexibility. The detailed handling of form feeds set in the input files requires the @option{-T} option. @item Capital letter options override small letter ones. @item Some of the option-arguments (compare @option{-s}, @option{-e}, @option{-i}, @option{-n}) cannot be specified as separate arguments from the preceding option letter (already stated in the @acronym{POSIX} specification). @end itemize The program accepts the following options. Also see @ref{Common options}. @table @samp @item +@var{first_page}[:@var{last_page}] @itemx --pages=@var{first_page}[:@var{last_page}] @c The two following @opindex lines evoke warnings because they contain `:' @c The `info' spec does not permit that. If we use those lines, we end @c up with truncated index entries that don't work. @c @opindex +@var{first_page}[:@var{last_page}] @c @opindex --pages=@var{first_page}[:@var{last_page}] @opindex +@var{page_range} @opindex --pages=@var{page_range} Begin printing with page @var{first_page} and stop with @var{last_page}. Missing @samp{:@var{last_page}} implies end of file. While estimating the number of skipped pages each form feed in the input file results in a new page. Page counting with and without @samp{+@var{first_page}} is identical. By default, counting starts with the first page of input file (not first page printed). Line numbering may be altered by @option{-N} option. @item -@var{column} @itemx --columns=@var{column} @opindex -@var{column} @opindex --columns @cindex down columns With each single @var{file}, produce @var{column} columns of output (default is 1) and print columns down, unless @option{-a} is used. The column width is automatically decreased as @var{column} increases; unless you use the @option{-W/-w} option to increase @var{page_width} as well. This option might well cause some lines to be truncated. The number of lines in the columns on each page are balanced. The options @option{-e} and @option{-i} are on for multiple text-column output. Together with @option{-J} option column alignment and line truncation is turned off. Lines of full length are joined in a free field format and @option{-S} option may set field separators. @option{-@var{column}} may not be used with @option{-m} option. @item -a @itemx --across @opindex -a @opindex --across @cindex across columns With each single @var{file}, print columns across rather than down. The @option{-@var{column}} option must be given with @var{column} greater than one. If a line is too long to fit in a column, it is truncated. @item -c @itemx --show-control-chars @opindex -c @opindex --show-control-chars Print control characters using hat notation (e.g., @samp{^G}); print other nonprinting characters in octal backslash notation. By default, nonprinting characters are not changed. @item -d @itemx --double-space @opindex -d @opindex --double-space @cindex double spacing Double space the output. @item -D @var{format} @itemx --date-format=@var{format} @cindex time formats @cindex formatting times Format header dates using @var{format}, using the same conventions as for the command @samp{date +@var{format}}; @xref{date invocation}. Except for directives, which start with @samp{%}, characters in @var{format} are printed unchanged. You can use this option to specify an arbitrary string in place of the header date, e.g., @option{--date-format="Monday morning"}. @vindex POSIXLY_CORRECT @vindex LC_TIME Normally the date format defaults to @samp{%Y-%m-%d %H:%M} (for example, @samp{2001-12-04 23:59}); but if the @env{POSIXLY_CORRECT} environment variable is set and the @env{LC_TIME} locale category specifies the @acronym{POSIX} locale, the default is @samp{%b %e %H:%M %Y} (for example, @samp{Dec@ @ 4 23:59 2001}. @vindex TZ Time stamps are listed according to the time zone rules specified by the @env{TZ} environment variable, or by the system default rules if @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone with @env{TZ}, libc, The GNU C Library}. @item -e[@var{in-tabchar}[@var{in-tabwidth}]] @itemx --expand-tabs[=@var{in-tabchar}[@var{in-tabwidth}]] @opindex -e @opindex --expand-tabs @cindex input tabs Expand @var{tab}s to spaces on input. Optional argument @var{in-tabchar} is the input tab character (default is the TAB character). Second optional argument @var{in-tabwidth} is the input tab character's width (default is 8). @item -f @itemx -F @itemx --form-feed @opindex -F @opindex -f @opindex --form-feed Use a form feed instead of newlines to separate output pages. The default page length of 66 lines is not altered. But the number of lines of text per page changes from default 56 to 63 lines. @item -h @var{HEADER} @itemx --header=@var{HEADER} @opindex -h @opindex --header Replace the file name in the header with the centered string @var{header}. When using the shell, @var{header} should be quoted and should be separated from @option{-h} by a space. @item -i[@var{out-tabchar}[@var{out-tabwidth}]] @itemx --output-tabs[=@var{out-tabchar}[@var{out-tabwidth}]] @opindex -i @opindex --output-tabs @cindex output tabs Replace spaces with @var{tab}s on output. Optional argument @var{out-tabchar} is the output tab character (default is the TAB character). Second optional argument @var{out-tabwidth} is the output tab character's width (default is 8). @item -J @itemx --join-lines @opindex -J @opindex --join-lines Merge lines of full length. Used together with the column options @option{-@var{column}}, @option{-a -@var{column}} or @option{-m}. Turns off @option{-W/-w} line truncation; no column alignment used; may be used with @option{--sep-string[=@var{string}]}. @option{-J} has been introduced (together with @option{-W} and @option{--sep-string}) to disentangle the old (@acronym{POSIX}-compliant) options @option{-w} and @option{-s} along with the three column options. @item -l @var{page_length} @itemx --length=@var{page_length} @opindex -l @opindex --length Set the page length to @var{page_length} (default 66) lines, including the lines of the header [and the footer]. If @var{page_length} is less than or equal to 10 (or <= 3 with @option{-F}), the header and footer are omitted, and all form feeds set in input files are eliminated, as if the @option{-T} option had been given. @item -m @itemx --merge @opindex -m @opindex --merge Merge and print all @var{file}s in parallel, one in each column. If a line is too long to fit in a column, it is truncated, unless the @option{-J} option is used. @option{--sep-string[=@var{string}]} may be used. Empty pages in some @var{file}s (form feeds set) produce empty columns, still marked by @var{string}. The result is a continuous line numbering and column marking throughout the whole merged file. Completely empty merged pages show no separators or line numbers. The default header becomes @samp{@var{date} @var{page}} with spaces inserted in the middle; this may be used with the @option{-h} or @option{--header} option to fill up the middle blank part. @item -n[@var{number-separator}[@var{digits}]] @itemx --number-lines[=@var{number-separator}[@var{digits}]] @opindex -n @opindex --number-lines Provide @var{digits} digit line numbering (default for @var{digits} is 5). With multicolumn output the number occupies the first @var{digits} column positions of each text column or only each line of @option{-m} output. With single column output the number precedes each line just as @option{-m} does. Default counting of the line numbers starts with the first line of the input file (not the first line printed, compare the @option{--page} option and @option{-N} option). Optional argument @var{number-separator} is the character appended to the line number to separate it from the text followed. The default separator is the TAB character. In a strict sense a TAB is always printed with single column output only. The @var{TAB}-width varies with the @var{TAB}-position, e.g., with the left @var{margin} specified by @option{-o} option. With multicolumn output priority is given to @samp{equal width of output columns} (a @acronym{POSIX} specification). The @var{TAB}-width is fixed to the value of the first column and does not change with different values of left @var{margin}. That means a fixed number of spaces is always printed in the place of the @var{number-separator tab}. The tabification depends upon the output position. @item -N @var{line_number} @itemx --first-line-number=@var{line_number} @opindex -N @opindex --first-line-number Start line counting with the number @var{line_number} at first line of first page printed (in most cases not the first line of the input file). @item -o @var{margin} @itemx --indent=@var{margin} @opindex -o @opindex --indent @cindex indenting lines @cindex left margin Indent each line with a margin @var{margin} spaces wide (default is zero). The total page width is the size of the margin plus the @var{page_width} set with the @option{-W/-w} option. A limited overflow may occur with numbered single column output (compare @option{-n} option). @item -r @itemx --no-file-warnings @opindex -r @opindex --no-file-warnings Do not print a warning message when an argument @var{file} cannot be opened. (The exit status will still be nonzero, however.) @item -s[@var{char}] @itemx --separator[=@var{char}] @opindex -s @opindex --separator Separate columns by a single character @var{char}. The default for @var{char} is the TAB character without @option{-w} and @samp{no character} with @option{-w}. Without @option{-s} the default separator @samp{space} is set. @option{-s[char]} turns off line truncation of all three column options (@option{-COLUMN}|@option{-a -COLUMN}|@option{-m}) unless @option{-w} is set. This is a @acronym{POSIX}-compliant formulation. @item -S@var{string} @itemx --sep-string[=@var{string}] @opindex -S @opindex --sep-string Use @var{string} to separate output columns. The @option{-S} option doesn't affect the @option{-W/-w} option, unlike the @option{-s} option which does. It does not affect line truncation or column alignment. Without @option{-S}, and with @option{-J}, @command{pr} uses the default output separator, TAB@. Without @option{-S} or @option{-J}, @command{pr} uses a @samp{space} (same as @option{-S"@w{ }"}). @option{--sep-string} with no @samp{=@var{string}} is equivalent to @option{--sep-string=""}. @item -t @itemx --omit-header @opindex -t @opindex --omit-header Do not print the usual header [and footer] on each page, and do not fill out the bottom of pages (with blank lines or a form feed). No page structure is produced, but form feeds set in the input files are retained. The predefined pagination is not changed. @option{-t} or @option{-T} may be useful together with other options; e.g.: @option{-t -e4}, expand TAB characters in the input file to 4 spaces but don't make any other changes. Use of @option{-t} overrides @option{-h}. @item -T @itemx --omit-pagination @opindex -T @opindex --omit-pagination Do not print header [and footer]. In addition eliminate all form feeds set in the input files. @item -v @itemx --show-nonprinting @opindex -v @opindex --show-nonprinting Print nonprinting characters in octal backslash notation. @item -w @var{page_width} @itemx --width=@var{page_width} @opindex -w @opindex --width Set page width to @var{page_width} characters for multiple text-column output only (default for @var{page_width} is 72). @option{-s[CHAR]} turns off the default page width and any line truncation and column alignment. Lines of full length are merged, regardless of the column options set. No @var{page_width} setting is possible with single column output. A @acronym{POSIX}-compliant formulation. @item -W @var{page_width} @itemx --page_width=@var{page_width} @opindex -W @opindex --page_width Set the page width to @var{page_width} characters. That's valid with and without a column option. Text lines are truncated, unless @option{-J} is used. Together with one of the three column options (@option{-@var{column}}, @option{-a -@var{column}} or @option{-m}) column alignment is always used. The separator options @option{-S} or @option{-s} don't affect the @option{-W} option. Default is 72 characters. Without @option{-W @var{page_width}} and without any of the column options NO line truncation is used (defined to keep downward compatibility and to meet most frequent tasks). That's equivalent to @option{-W 72 -J}. The header line is never truncated. @end table @exitstatus @node fold invocation @section @command{fold}: Wrap input lines to fit in specified width @pindex fold @cindex wrapping long input lines @cindex folding long input lines @command{fold} writes each @var{file} (@option{-} means standard input), or standard input if none are given, to standard output, breaking long lines. Synopsis: @example fold [@var{option}]@dots{} [@var{file}]@dots{} @end example By default, @command{fold} breaks lines wider than 80 columns. The output is split into as many lines as necessary. @cindex screen columns @command{fold} counts screen columns by default; thus, a tab may count more than one column, backspace decreases the column count, and carriage return sets the column to zero. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -b @itemx --bytes @opindex -b @opindex --bytes Count bytes rather than columns, so that tabs, backspaces, and carriage returns are each counted as taking up one column, just like other characters. @item -s @itemx --spaces @opindex -s @opindex --spaces Break at word boundaries: the line is broken after the last blank before the maximum line length. If the line contains no such blanks, the line is broken at the maximum line length as usual. @item -w @var{width} @itemx --width=@var{width} @opindex -w @opindex --width Use a maximum line length of @var{width} columns instead of 80. For compatibility @command{fold} supports an obsolete option syntax @option{-@var{width}}. New scripts should use @option{-w @var{width}} instead. @end table @exitstatus @node Output of parts of files @chapter Output of parts of files @cindex output of parts of files @cindex parts of files, output of 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. @end menu @node head invocation @section @command{head}: Output the first part of files @pindex head @cindex initial part of files, outputting @cindex first part of files, outputting @command{head} prints the first part (10 lines by default) of each @var{file}; it reads from standard input if no files are given or when given a @var{file} of @option{-}. Synopsis: @example head [@var{option}]@dots{} [@var{file}]@dots{} @end example If more than one @var{file} is specified, @command{head} prints a one-line header consisting of: @example ==> @var{file name} <== @end example @noindent before the output for each @var{file}. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -c @var{n} @itemx --bytes=@var{n} @opindex -c @opindex --bytes Print the first @var{n} bytes, instead of initial lines. Appending @samp{b} multiplies @var{n} by 512, @samp{k} by 1024, and @samp{m} by 1048576. However, if @var{n} starts with a @samp{-}, print all but the last @var{n} bytes of each file. @itemx -n @var{n} @itemx --lines=@var{n} @opindex -n @opindex --lines Output the first @var{n} lines. However, if @var{n} starts with a @samp{-}, print all but the last @var{n} lines of each file. @item -q @itemx --quiet @itemx --silent @opindex -q @opindex --quiet @opindex --silent Never print file name headers. @item -v @itemx --verbose @opindex -v @opindex --verbose Always print file name headers. @end table For compatibility @command{head} also supports an obsolete option syntax @option{-@var{count}@var{options}}, which is recognized only if it is specified first. @var{count} is a decimal number optionally followed by a size letter (@samp{b}, @samp{k}, @samp{m}) as in @option{-c}, or @samp{l} to mean count by lines, or other option letters (@samp{cqv}). Scripts intended for standard hosts should use @option{-c @var{count}} or @option{-n @var{count}} instead. If your script must also run on hosts that support only the obsolete syntax, it is usually simpler to avoid @command{head}, e.g., by using @samp{sed 5q} instead of @samp{head -5}. @exitstatus @node tail invocation @section @command{tail}: Output the last part of files @pindex tail @cindex last part of files, outputting @command{tail} prints the last part (10 lines by default) of each @var{file}; it reads from standard input if no files are given or when given a @var{file} of @samp{-}. Synopsis: @example tail [@var{option}]@dots{} [@var{file}]@dots{} @end example If more than one @var{file} is specified, @command{tail} prints a one-line header consisting of: @example ==> @var{file name} <== @end example @noindent before the output for each @var{file}. @cindex BSD @command{tail} @sc{gnu} @command{tail} can output any amount of data (some other versions of @command{tail} cannot). It also has no @option{-r} option (print in reverse), since reversing a file is really a different job from printing the end of a file; BSD @command{tail} (which is the one with @option{-r}) can only reverse files that are at most as large as its buffer, which is typically 32 KiB@. A more reliable and versatile way to reverse files is the @sc{gnu} @command{tac} command. If any option-argument is a number @var{n} starting with a @samp{+}, @command{tail} begins printing with the @var{n}th item from the start of each file, instead of from the end. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -c @var{bytes} @itemx --bytes=@var{bytes} @opindex -c @opindex --bytes Output the last @var{bytes} bytes, instead of final lines. Appending @samp{b} multiplies @var{bytes} by 512, @samp{k} by 1024, and @samp{m} by 1048576. @item -f @itemx --follow[=@var{how}] @opindex -f @opindex --follow @cindex growing files @vindex name @r{follow option} @vindex descriptor @r{follow option} Loop forever trying to read more characters at the end of the file, presumably because the file is growing. If more than one file is given, @command{tail} prints a header whenever it gets output from a different file, to indicate which file that output is from. There are two ways to specify how you'd like to track files with this option, but that difference is noticeable only when a followed file is removed or renamed. If you'd like to continue to track the end of a growing file even after it has been unlinked, use @option{--follow=descriptor}. This is the default behavior, but it is not useful if you're tracking a log file that may be rotated (removed or renamed, then reopened). In that case, use @option{--follow=name} to track the named file by reopening it periodically to see if it has been removed and recreated by some other program. No matter which method you use, if the tracked file is determined to have shrunk, @command{tail} prints a message saying the file has been truncated and resumes tracking the end of the file from the newly-determined endpoint. When a file is removed, @command{tail}'s behavior depends on whether it is following the name or the descriptor. When following by name, tail can detect that a file has been removed and gives a message to that effect, and if @option{--retry} has been specified it will continue checking periodically to see if the file reappears. When following a descriptor, tail does not detect that the file has been unlinked or renamed and issues no message; even though the file may no longer be accessible via its original name, it may still be growing. The option values @samp{descriptor} and @samp{name} may be specified only with the long form of the option, not with @option{-f}. @vindex POSIXLY_CORRECT If @env{POSIXLY_CORRECT} is set, the @option{-f} option is ignored if no @var{file} operand is specified and standard input is a pipe. @item -F @opindex -F This option is the same as @option{--follow=name --retry}. That is, tail will attempt to reopen a file when it is removed. Should this fail, tail will keep trying until it becomes accessible again. @itemx --retry @opindex --retry This option is useful mainly when following by name (i.e., with @option{--follow=name}). Without this option, when tail encounters a file that doesn't exist or is otherwise inaccessible, it reports that fact and never checks it again. @itemx --sleep-interval=@var{number} @opindex --sleep-interval Change the number of seconds to wait between iterations (the default is 1.0). During one iteration, every specified file is checked to see if it has changed size. Historical implementations of @command{tail} have required that @var{number} be an integer. However, GNU @command{tail} accepts an arbitrary floating point number (using a period before any fractional digits). @itemx --pid=@var{pid} @opindex --pid When following by name or by descriptor, you may specify the process ID, @var{pid}, of the sole writer of all @var{file} arguments. Then, shortly after that process terminates, tail will also terminate. This will work properly only if the writer and the tailing process are running on the same machine. For example, to save the output of a build in a file and to watch the file grow, if you invoke @command{make} and @command{tail} like this then the tail process will stop when your build completes. Without this option, you would have had to kill the @code{tail -f} process yourself. @example $ make >& makerr & tail --pid=$! -f makerr @end example If you specify a @var{pid} that is not in use or that does not correspond to the process that is writing to the tailed files, then @command{tail} may terminate long before any @var{file}s stop growing or it may not terminate until long after the real writer has terminated. Note that @option{--pid} cannot be supported on some systems; @command{tail} will print a warning if this is the case. @itemx --max-unchanged-stats=@var{n} @opindex --max-unchanged-stats When tailing a file by name, if there have been @var{n} (default n=@value{DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS}) consecutive iterations for which the file has not changed, then @code{open}/@code{fstat} the file to determine if that file name is still associated with the same device/inode-number pair as before. When following a log file that is rotated, this is approximately the number of seconds between when tail prints the last pre-rotation lines and when it prints the lines that have accumulated in the new log file. This option is meaningful only when following by name. @itemx -n @var{n} @itemx --lines=@var{n} @opindex -n @opindex --lines Output the last @var{n} lines. @item -q @itemx --quiet @itemx --silent @opindex -q @opindex --quiet @opindex --silent Never print file name headers. @item -v @itemx --verbose @opindex -v @opindex --verbose Always print file name headers. @end table For compatibility @command{tail} also supports an obsolete usage @samp{tail -[@var{count}][bcl][f] [@var{file}]}, which is recognized only if it does not conflict with the usage described above. This obsolete form uses exactly one option and at most one file. In the option, @var{count} is an optional decimal number optionally followed by a size letter (@samp{b}, @samp{c}, @samp{l}) to mean count by 512-byte blocks, bytes, or lines, optionally followed by @samp{f} which has the same meaning as @option{-f}. @vindex _POSIX2_VERSION On older systems, the leading @samp{-} can be replaced by @samp{+} in the obsolete option syntax with the same meaning as in counts, and obsolete usage overrides normal usage when the two conflict. This obsolete behavior can be enabled or disabled with the @env{_POSIX2_VERSION} environment variable (@pxref{Standards conformance}). Scripts intended for use on standard hosts should avoid obsolete syntax and should use @option{-c @var{count}[b]}, @option{-n @var{count}}, and/or @option{-f} instead. If your script must also run on hosts that support only the obsolete syntax, you can often rewrite it to avoid problematic usages, e.g., by using @samp{sed -n '$p'} rather than @samp{tail -1}. If that's not possible, the script can use a test like @samp{if tail -c +1 /dev/null 2>&1; then @dots{}} to decide which syntax to use. Even if your script assumes the standard behavior, you should still beware usages whose behaviors differ depending on the @acronym{POSIX} version. For example, avoid @samp{tail - main.c}, since it might be interpreted as either @samp{tail main.c} or as @samp{tail -- - main.c}; avoid @samp{tail -c 4}, since it might mean either @samp{tail -c4} or @samp{tail -c 10 4}; and avoid @samp{tail +4}, since it might mean either @samp{tail ./+4} or @samp{tail -n +4}. @exitstatus @node split invocation @section @command{split}: Split a file into fixed-size pieces @pindex split @cindex splitting a file into pieces @cindex pieces, splitting a file into @command{split} creates output files containing consecutive sections of @var{input} (standard input if none is given or @var{input} is @samp{-}). Synopsis: @example split [@var{option}] [@var{input} [@var{prefix}]] @end example By default, @command{split} puts 1000 lines of @var{input} (or whatever is left over for the last section), into each output file. @cindex output file name prefix The output files' names consist of @var{prefix} (@samp{x} by default) followed by a group of characters (@samp{aa}, @samp{ab}, @dots{} by default), such that concatenating the output files in traditional sorted order by file name produces the original input file. If the output file names are exhausted, @command{split} reports an error without deleting the output files that it did create. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @var{length} @itemx --suffix-length=@var{length} @opindex -a @opindex --suffix-length Use suffixes of length @var{length}. The default @var{length} is 2. @item -l @var{lines} @itemx --lines=@var{lines} @opindex -l @opindex --lines Put @var{lines} lines of @var{input} into each output file. For compatibility @command{split} also supports an obsolete option syntax @option{-@var{lines}}. New scripts should use @option{-l @var{lines}} instead. @item -b @var{bytes} @itemx --bytes=@var{bytes} @opindex -b @opindex --bytes Put the first @var{bytes} bytes of @var{input} into each output file. Appending @samp{b} multiplies @var{bytes} by 512, @samp{k} by 1024, and @samp{m} by 1048576. @item -C @var{bytes} @itemx --line-bytes=@var{bytes} @opindex -C @opindex --line-bytes Put into each output file as many complete lines of @var{input} as possible without exceeding @var{bytes} bytes. For lines longer than @var{bytes} bytes, put @var{bytes} bytes into each output file until less than @var{bytes} bytes of the line are left, then continue normally. @var{bytes} has the same format as for the @option{--bytes} option. @item -d @itemx --numeric-suffixes @opindex -d @opindex --numeric-suffixes Use digits in suffixes rather than lower-case letters. @itemx --verbose @opindex --verbose Write a diagnostic to standard error just before each output file is opened. @end table @exitstatus @node csplit invocation @section @command{csplit}: Split a file into context-determined pieces @pindex csplit @cindex context splitting @cindex splitting a file into pieces by context @command{csplit} creates zero or more output files containing sections of @var{input} (standard input if @var{input} is @samp{-}). Synopsis: @example csplit [@var{option}]@dots{} @var{input} @var{pattern}@dots{} @end example The contents of the output files are determined by the @var{pattern} arguments, as detailed below. An error occurs if a @var{pattern} argument refers to a nonexistent line of the input file (e.g., if no remaining line matches a given regular expression). After every @var{pattern} has been matched, any remaining input is copied into one last output file. By default, @command{csplit} prints the number of bytes written to each output file after it has been created. The types of pattern arguments are: @table @samp @item @var{n} Create an output file containing the input up to but not including line @var{n} (a positive integer). If followed by a repeat count, also create an output file containing the next @var{n} lines of the input file once for each repeat. @item /@var{regexp}/[@var{offset}] Create an output file containing the current line up to (but not including) the next line of the input file that contains a match for @var{regexp}. The optional @var{offset} is an integer. If it is given, the input up to (but not including) the matching line plus or minus @var{offset} is put into the output file, and the line after that begins the next section of input. @item %@var{regexp}%[@var{offset}] Like the previous type, except that it does not create an output file, so that section of the input file is effectively ignored. @item @{@var{repeat-count}@} Repeat the previous pattern @var{repeat-count} additional times. The @var{repeat-count} can either be a positive integer or an asterisk, meaning repeat as many times as necessary until the input is exhausted. @end table The output files' names consist of a prefix (@samp{xx} by default) followed by a suffix. By default, the suffix is an ascending sequence of two-digit decimal numbers from @samp{00} to @samp{99}. In any case, concatenating the output files in sorted order by file name produces the original input file. By default, if @command{csplit} encounters an error or receives a hangup, interrupt, quit, or terminate signal, it removes any output files that it has created so far before it exits. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -f @var{prefix} @itemx --prefix=@var{prefix} @opindex -f @opindex --prefix @cindex output file name prefix Use @var{prefix} as the output file name prefix. @item -b @var{suffix} @itemx --suffix=@var{suffix} @opindex -b @opindex --suffix @cindex output file name suffix Use @var{suffix} as the output file name suffix. When this option is specified, the suffix string must include exactly one @code{printf(3)}-style conversion specification, possibly including format specification flags, a field width, a precision specifications, or all of these kinds of modifiers. The format letter must convert a binary integer argument to readable form; thus, only @samp{d}, @samp{i}, @samp{u}, @samp{o}, @samp{x}, and @samp{X} conversions are allowed. The entire @var{suffix} is given (with the current output file number) to @code{sprintf(3)} to form the file name suffixes for each of the individual output files in turn. If this option is used, the @option{--digits} option is ignored. @item -n @var{digits} @itemx --digits=@var{digits} @opindex -n @opindex --digits Use output file names containing numbers that are @var{digits} digits long instead of the default 2. @item -k @itemx --keep-files @opindex -k @opindex --keep-files Do not remove output files when errors are encountered. @item -z @itemx --elide-empty-files @opindex -z @opindex --elide-empty-files Suppress the generation of zero-length output files. (In cases where the section delimiters of the input file are supposed to mark the first lines of each of the sections, the first output file will generally be a zero-length file unless you use this option.) The output file sequence numbers always run consecutively starting from 0, even when this option is specified. @item -s @itemx -q @itemx --silent @itemx --quiet @opindex -s @opindex -q @opindex --silent @opindex --quiet Do not print counts of output file sizes. @end table @exitstatus @node Summarizing files @chapter Summarizing files @cindex summarizing files These commands generate just a few numbers representing entire contents of 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. @end menu @node wc invocation @section @command{wc}: Print newline, word, and byte counts @pindex wc @cindex byte count @cindex character count @cindex word count @cindex line count @command{wc} counts the number of bytes, characters, whitespace-separated words, and newlines in each given @var{file}, or standard input if none are given or for a @var{file} of @samp{-}. Synopsis: @example wc [@var{option}]@dots{} [@var{file}]@dots{} @end example @cindex total counts @command{wc} prints one line of counts for each file, and if the file was given as an argument, it prints the file name following the counts. If more than one @var{file} is given, @command{wc} prints a final line containing the cumulative counts, with the file name @file{total}. The counts are printed in this order: newlines, words, characters, bytes. Each count is printed right-justified in a field with at least one space between fields so that the numbers and file names normally line up nicely in columns. The width of the count fields varies depending on the inputs, so you should not depend on a particular field width. However, as a @acronym{GNU} extension, if only one count is printed, it is guaranteed to be printed without leading spaces. By default, @command{wc} prints three counts: the newline, words, and byte counts. Options can specify that only certain counts be printed. Options do not undo others previously given, so @example wc --bytes --words @end example @noindent prints both the byte counts and the word counts. With the @option{--max-line-length} option, @command{wc} prints the length of the longest line per file, and if there is more than one file it prints the maximum (not the sum) of those lengths. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -c @itemx --bytes @opindex -c @opindex --bytes Print only the byte counts. @item -m @itemx --chars @opindex -m @opindex --chars Print only the character counts. @item -w @itemx --words @opindex -w @opindex --words Print only the word counts. @item -l @itemx --lines @opindex -l @opindex --lines Print only the newline counts. @item -L @itemx --max-line-length @opindex -L @opindex --max-line-length Print only the maximum line lengths. @itemx --files0-from=@var{FILE} @opindex --files0-from=@var{FILE} @cindex including files from @command{du} Rather than processing files named on the command line, process those named in file @var{FILE}; each name is terminated by a null byte. This is useful when the list of file names is so long that it may exceed a command line length limitation. In such cases, running @command{wc} via @command{xargs} is undesirable because it splits the list into pieces and makes @command{wc} print a total for each sublist rather than for the entire list. One way to produce a list of null-byte-terminated file names is with @sc{gnu} @command{find}, using its @option{-print0} predicate. For example, to find the length of the longest line in any @file{.c} or @file{.h} file in the current hierarchy, do this: @example find . -name '*.[ch]' -print0 | wc -L --files0-from=- | tail -n1 @end example Do not specify any @var{FILE} on the command line when using this option. @end table @exitstatus @node sum invocation @section @command{sum}: Print checksum and block counts @pindex sum @cindex 16-bit checksum @cindex checksum, 16-bit @command{sum} computes a 16-bit checksum for each given @var{file}, or standard input if none are given or for a @var{file} of @samp{-}. Synopsis: @example sum [@var{option}]@dots{} [@var{file}]@dots{} @end example @command{sum} prints the checksum for each @var{file} followed by the number of blocks in the file (rounded up). If more than one @var{file} is given, file names are also printed (by default). (With the @option{--sysv} option, corresponding file names are printed when there is at least one file argument.) By default, @sc{gnu} @command{sum} computes checksums using an algorithm compatible with BSD @command{sum} and prints file sizes in units of 1024-byte blocks. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -r @opindex -r @cindex BSD @command{sum} Use the default (BSD compatible) algorithm. This option is included for compatibility with the System V @command{sum}. Unless @option{-s} was also given, it has no effect. @item -s @itemx --sysv @opindex -s @opindex --sysv @cindex System V @command{sum} Compute checksums using an algorithm compatible with System V @command{sum}'s default, and print file sizes in units of 512-byte blocks. @end table @command{sum} is provided for compatibility; the @command{cksum} program (see next section) is preferable in new applications. @exitstatus @node cksum invocation @section @command{cksum}: Print CRC checksum and byte counts @pindex cksum @cindex cyclic redundancy check @cindex CRC checksum @command{cksum} computes a cyclic redundancy check (CRC) checksum for each given @var{file}, or standard input if none are given or for a @var{file} of @samp{-}. Synopsis: @example cksum [@var{option}]@dots{} [@var{file}]@dots{} @end example @command{cksum} prints the CRC checksum for each file along with the number of bytes in the file, and the file name unless no arguments were given. @command{cksum} is typically used to ensure that files transferred by unreliable means (e.g., netnews) have not been corrupted, by comparing the @command{cksum} output for the received files with the @command{cksum} output for the original files (typically given in the distribution). The CRC algorithm is specified by the @acronym{POSIX} standard. It is not compatible with the BSD or System V @command{sum} algorithms (see the previous section); it is more robust. The only options are @option{--help} and @option{--version}. @xref{Common options}. @exitstatus @node md5sum invocation @section @command{md5sum}: Print or check MD5 digests @pindex md5sum @cindex MD5 @cindex 128-bit checksum @cindex checksum, 128-bit @cindex fingerprint, 128-bit @cindex message-digest, 128-bit @command{md5sum} computes a 128-bit checksum (or @dfn{fingerprint} or @dfn{message-digest}) for each specified @var{file}. Note: The MD5 digest is more reliable than a simple CRC (provided by the @command{cksum} command) for detecting accidental file corruption, as the chances of accidentally having two files with identical MD5 are vanishingly small. However, it should not be considered truly secure against malicious tampering: although finding a file with a given MD5 fingerprint, or modifying a file so as to retain its MD5 are considered infeasible at the moment, it is known how to produce different files with identical MD5 (a ``collision''), something which can be a security issue in certain contexts. For more secure hashes, consider using SHA-1 or SHA-2. @xref{sha1sum invocation}, and @ref{sha2 utilities}. If a @var{file} is specified as @samp{-} or if no files are given @command{md5sum} computes the checksum for the standard input. @command{md5sum} can also determine whether a file and checksum are consistent. Synopsis: @example md5sum [@var{option}]@dots{} [@var{file}]@dots{} @end example For each @var{file}, @samp{md5sum} outputs the MD5 checksum, a flag indicating a binary or text input file, and the file name. If @var{file} is omitted or specified as @samp{-}, standard input is read. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -b @itemx --binary @opindex -b @opindex --binary @cindex binary input files Treat each input file as binary, by reading it in binary mode and outputting a @samp{*} flag. This is the inverse of @option{--text}. On systems like @acronym{GNU} that do not distinguish between binary and text files, this option merely flags each input file as binary: the MD5 checksum is unaffected. This option is the default on systems like MS-DOS that distinguish between binary and text files, except for reading standard input when standard input is a terminal. @item -c @itemx --check Read file names and checksum information (not data) from each @var{file} (or from stdin if no @var{file} was specified) and report whether the checksums match the contents of the named files. The input to this mode of @command{md5sum} is usually the output of a prior, checksum-generating run of @samp{md5sum}. Each valid line of input consists of an MD5 checksum, a binary/text flag, and then a file name. Binary files are marked with @samp{*}, text with @samp{ }. For each such line, @command{md5sum} reads the named file and computes its MD5 checksum. Then, if the computed message digest does not match the one on the line with the file name, the file is noted as having failed the test. Otherwise, the file passes the test. By default, for each valid line, one line is written to standard output indicating whether the named file passed the test. After all checks have been performed, if there were any failures, a warning is issued to standard error. Use the @option{--status} option to inhibit that output. If any listed file cannot be opened or read, if any valid line has an MD5 checksum inconsistent with the associated file, or if no valid line is found, @command{md5sum} exits with nonzero status. Otherwise, it exits successfully. @itemx --status @opindex --status @cindex verifying MD5 checksums This option is useful only when verifying checksums. When verifying checksums, don't generate the default one-line-per-file diagnostic and don't output the warning summarizing any failures. Failures to open or read a file still evoke individual diagnostics to standard error. If all listed files are readable and are consistent with the associated MD5 checksums, exit successfully. Otherwise exit with a status code indicating there was a failure. @item -t @itemx --text @opindex -t @opindex --text @cindex text input files Treat each input file as text, by reading it in text mode and outputting a @samp{ } flag. This is the inverse of @option{--binary}. This option is the default on systems like @acronym{GNU} that do not distinguish between binary and text files. On other systems, it is the default for reading standard input when standard input is a terminal. @item -w @itemx --warn @opindex -w @opindex --warn @cindex verifying MD5 checksums When verifying checksums, warn about improperly formatted MD5 checksum lines. This option is useful only if all but a few lines in the checked input are valid. @end table @exitstatus @node sha1sum invocation @section @command{sha1sum}: Print or check SHA-1 digests @pindex sha1sum @cindex SHA-1 @cindex 160-bit checksum @cindex checksum, 160-bit @cindex fingerprint, 160-bit @cindex message-digest, 160-bit @command{sha1sum} computes a 160-bit checksum for each specified @var{file}. The usage and options of this command are precisely the same as for @command{md5sum}. @xref{md5sum invocation}. Note: The SHA-1 digest is more secure than MD5, and no collisions of it are known (different files having the same fingerprint). However, it is known that they can be produced with considerable, but not unreasonable, resources. For this reason, it is generally considered that SHA-1 should be gradually phased out in favor of the more secure SHA-2 hash algorithms. @xref{sha2 utilities}. @node sha2 utilities @section sha2 utilities: Print or check SHA-2 digests @pindex sha224sum @pindex sha256sum @pindex sha384sum @pindex sha512sum @cindex SHA-2 @cindex 224-bit checksum @cindex 256-bit checksum @cindex 384-bit checksum @cindex 512-bit checksum @cindex checksum, 224-bit @cindex checksum, 256-bit @cindex checksum, 384-bit @cindex checksum, 512-bit @cindex fingerprint, 224-bit @cindex fingerprint, 256-bit @cindex fingerprint, 384-bit @cindex fingerprint, 512-bit @cindex message-digest, 224-bit @cindex message-digest, 256-bit @cindex message-digest, 384-bit @cindex message-digest, 512-bit The commands @command{sha224sum}, @command{sha256sum}, @command{sha384sum} and @command{sha512sum} compute checksums of various lengths (respectively 224, 256, 384 and 512 bits), collectively known as the SHA-2 hashes. The usage and options of these commands are precisely the same as for @command{md5sum}. @xref{md5sum invocation}. Note: The SHA384 and SHA512 digests are considerably slower to compute, especially on 32-bit computers, than SHA224 or SHA256. @node Operating on sorted files @chapter Operating on sorted files @cindex operating on sorted files @cindex sorted files, operations on These commands work with (or produce) sorted files. @menu * sort invocation:: Sort 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. * tsort background:: Where tsort came from. @end menu @node sort invocation @section @command{sort}: Sort text files @pindex sort @cindex sorting files @command{sort} sorts, merges, or compares all the lines from the given files, or standard input if none are given or for a @var{file} of @samp{-}. By default, @command{sort} writes the results to standard output. Synopsis: @example sort [@var{option}]@dots{} [@var{file}]@dots{} @end example @command{sort} has three modes of operation: sort (the default), merge, and check for sortedness. The following options change the operation mode: @table @samp @item -c @itemx --check @opindex -c @opindex --check @cindex checking for sortedness Check whether the given files are already sorted: if they are not all sorted, print an error message and exit with a status of 1. Otherwise, exit successfully. @item -m @itemx --merge @opindex -m @opindex --merge @cindex merging sorted files Merge the given files by sorting them as a group. Each input file must always be individually sorted. It always works to sort instead of merge; merging is provided because it is faster, in the case where it works. @end table @cindex sort stability @cindex sort's last-resort comparison A pair of lines is compared as follows: @command{sort} compares each pair of fields, in the order specified on the command line, according to the associated ordering options, until a difference is found or no fields are left. If no key fields are specified, @command{sort} uses a default key of the entire line. Finally, as a last resort when all keys compare equal, @command{sort} compares entire lines as if no ordering options other than @option{--reverse} (@option{-r}) were specified. The @option{--stable} (@option{-s}) option disables this @dfn{last-resort comparison} so that lines in which all fields compare equal are left in their original relative order. The @option{--unique} (@option{-u}) option also disables the last-resort comparison. @vindex LC_ALL @vindex LC_COLLATE Unless otherwise specified, all comparisons use the character collating sequence specified by the @env{LC_COLLATE} locale.@footnote{If you use a non-@acronym{POSIX} locale (e.g., by setting @env{LC_ALL} to @samp{en_US}), then @command{sort} may produce output that is sorted differently than you're accustomed to. In that case, set the @env{LC_ALL} environment variable to @samp{C}. Note that setting only @env{LC_COLLATE} has two problems. First, it is ineffective if @env{LC_ALL} is also set. Second, it has undefined behavior if @env{LC_CTYPE} (or @env{LANG}, if @env{LC_CTYPE} is unset) is set to an incompatible value. For example, you get undefined behavior if @env{LC_CTYPE} is @code{ja_JP.PCK} but @env{LC_COLLATE} is @code{en_US.UTF-8}.} @sc{gnu} @command{sort} (as specified for all @sc{gnu} utilities) has no limit on input line length or restrictions on bytes allowed within lines. In addition, if the final byte of an input file is not a newline, @sc{gnu} @command{sort} silently supplies one. A line's trailing newline is not part of the line for comparison purposes. @cindex exit status of @command{sort} Exit status: @display 0 if no error occurred 1 if invoked with @option{-c} and the input is not properly sorted 2 if an error occurred @end display @vindex TMPDIR If the environment variable @env{TMPDIR} is set, @command{sort} uses its value as the directory for temporary files instead of @file{/tmp}. The @option{--temporary-directory} (@option{-T}) option in turn overrides the environment variable. The following options affect the ordering of output lines. They may be specified globally or as part of a specific key field. If no key fields are specified, global options apply to comparison of entire lines; otherwise the global options are inherited by key fields that do not specify any special options of their own. In pre-@acronym{POSIX} versions of @command{sort}, global options affect only later key fields, so portable shell scripts should specify global options first. @table @samp @item -b @itemx --ignore-leading-blanks @opindex -b @opindex --ignore-leading-blanks @cindex blanks, ignoring leading @vindex LC_CTYPE Ignore leading blanks when finding sort keys in each line. By default a blank is a space or a tab, but the @env{LC_CTYPE} locale can change this. @item -d @itemx --dictionary-order @opindex -d @opindex --dictionary-order @cindex dictionary order @cindex phone directory order @cindex telephone directory order @vindex LC_CTYPE Sort in @dfn{phone directory} order: ignore all characters except letters, digits and blanks when sorting. By default letters and digits are those of @acronym{ASCII} and a blank is a space or a tab, but the @env{LC_CTYPE} locale can change this. @item -f @itemx --ignore-case @opindex -f @opindex --ignore-case @cindex ignoring case @cindex case folding @vindex LC_CTYPE Fold lowercase characters into the equivalent uppercase characters when comparing so that, for example, @samp{b} and @samp{B} sort as equal. The @env{LC_CTYPE} locale determines character types. @item -g @itemx --general-numeric-sort @opindex -g @opindex --general-numeric-sort @cindex general numeric sort @vindex LC_NUMERIC Sort numerically, using the standard C function @code{strtod} to convert a prefix of each line to a double-precision floating point number. This allows floating point numbers to be specified in scientific notation, like @code{1.0e-34} and @code{10e100}. The @env{LC_NUMERIC} locale determines the decimal-point character. Do not report overflow, underflow, or conversion errors. Use the following collating sequence: @itemize @bullet @item Lines that do not start with numbers (all considered to be equal). @item NaNs (``Not a Number'' values, in IEEE floating point arithmetic) in a consistent but machine-dependent order. @item Minus infinity. @item Finite numbers in ascending numeric order (with @math{-0} and @math{+0} equal). @item Plus infinity. @end itemize Use this option only if there is no alternative; it is much slower than @option{--numeric-sort} (@option{-n}) and it can lose information when converting to floating point. @item -i @itemx --ignore-nonprinting @opindex -i @opindex --ignore-nonprinting @cindex nonprinting characters, ignoring @cindex unprintable characters, ignoring @vindex LC_CTYPE Ignore nonprinting characters. The @env{LC_CTYPE} locale determines character types. This option has no effect if the stronger @option{--dictionary-order} (@option{-d}) option is also given. @item -M @itemx --month-sort @opindex -M @opindex --month-sort @cindex months, sorting by @vindex LC_TIME An initial string, consisting of any amount of blanks, followed by a month name abbreviation, is folded to UPPER case and compared in the order @samp{JAN} < @samp{FEB} < @dots{} < @samp{DEC}. Invalid names compare low to valid names. The @env{LC_TIME} locale category determines the month spellings. By default a blank is a space or a tab, but the @env{LC_CTYPE} locale can change this. @item -n @itemx --numeric-sort @opindex -n @opindex --numeric-sort @cindex numeric sort @vindex LC_NUMERIC Sort numerically: the number begins each line; specifically, it consists of optional blanks, an optional @samp{-} sign, and zero or more digits possibly separated by thousands separators, optionally followed by a decimal-point character and zero or more digits. A string of no digits is interpreted as @samp{0}. The @env{LC_NUMERIC} locale specifies the decimal-point character and thousands separator. By default a blank is a space or a tab, but the @env{LC_CTYPE} locale can change this. Numeric sort uses what might be considered an unconventional method to compare strings representing floating point numbers. Rather than first converting each string to the C @code{double} type and then comparing those values, @command{sort} aligns the decimal-point characters in the two strings and compares the strings a character at a time. One benefit of using this approach is its speed. In practice this is much more efficient than performing the two corresponding string-to-double (or even string-to-integer) conversions and then comparing doubles. In addition, there is no corresponding loss of precision. Converting each string to @code{double} before comparison would limit precision to about 16 digits on most systems. Neither a leading @samp{+} nor exponential notation is recognized. To compare such strings numerically, use the @option{--general-numeric-sort} (@option{-g}) option. @item -r @itemx --reverse @opindex -r @opindex --reverse @cindex reverse sorting Reverse the result of comparison, so that lines with greater key values appear earlier in the output instead of later. @item -R @itemx --random-sort @opindex -R @opindex --random-sort @cindex random sort Sort by hashing the input keys and then sorting the hash values. This is much like a random shuffle of the inputs, except that keys with the same value sort together. The hash function is chosen at random. @end table Other options are: @table @samp @item -k @var{pos1}[,@var{pos2}] @itemx --key=@var{pos1}[,@var{pos2}] @opindex -k @opindex --key @cindex sort field Specify a sort field that consists of the part of the line between @var{pos1} and @var{pos2} (or the end of the line, if @var{pos2} is omitted), @emph{inclusive}. Fields and character positions are numbered starting with 1. So to sort on the second field, you'd use @option{--key=2,2} (@option{-k 2,2}). See below for more examples. @item -o @var{output-file} @itemx --output=@var{output-file} @opindex -o @opindex --output @cindex overwriting of input, allowed Write output to @var{output-file} instead of standard output. Normally, @command{sort} reads all input before opening @var{output-file}, so you can safely sort a file in place by using commands like @code{sort -o F F} and @code{cat F | sort -o F}. However, @command{sort} with @option{--merge} (@option{-m}) can open the output file before reading all input, so a command like @code{cat F | sort -m -o F - G} is not safe as @command{sort} might start writing @file{F} before @command{cat} is done reading it. @vindex POSIXLY_CORRECT On newer systems, @option{-o} cannot appear after an input file if @env{POSIXLY_CORRECT} is set, e.g., @samp{sort F -o F}. Portable scripts should specify @option{-o @var{output-file}} before any input files. @item -s @itemx --stable @opindex -s @opindex --stable @cindex sort stability @cindex sort's last-resort comparison Make @command{sort} stable by disabling its last-resort comparison. This option has no effect if no fields or global ordering options other than @option{--reverse} (@option{-R}) are specified. @item -S @var{size} @itemx --buffer-size=@var{size} @opindex -S @opindex --buffer-size @cindex size for main memory sorting Use a main-memory sort buffer of the given @var{size}. By default, @var{size} is in units of 1024 bytes. Appending @samp{%} causes @var{size} to be interpreted as a percentage of physical memory. Appending @samp{K} multiplies @var{size} by 1024 (the default), @samp{M} by 1,048,576, @samp{G} by 1,073,741,824, and so on for @samp{T}, @samp{P}, @samp{E}, @samp{Z}, and @samp{Y}. Appending @samp{b} causes @var{size} to be interpreted as a byte count, with no multiplication. This option can improve the performance of @command{sort} by causing it to start with a larger or smaller sort buffer than the default. However, this option affects only the initial buffer size. The buffer grows beyond @var{size} if @command{sort} encounters input lines larger than @var{size}. @item -t @var{separator} @itemx --field-separator=@var{separator} @opindex -t @opindex --field-separator @cindex field separator character Use character @var{separator} as the field separator when finding the sort keys in each line. By default, fields are separated by the empty string between a non-blank character and a blank character. By default a blank is a space or a tab, but the @env{LC_CTYPE} locale can change this. That is, given the input line @w{@samp{ foo bar}}, @command{sort} breaks it into fields @w{@samp{ foo}} and @w{@samp{ bar}}. The field separator is not considered to be part of either the field preceding or the field following, so with @samp{sort @w{-t " "}} the same input line has three fields: an empty field, @samp{foo}, and @samp{bar}. However, fields that extend to the end of the line, as @option{-k 2}, or fields consisting of a range, as @option{-k 2,3}, retain the field separators present between the endpoints of the range. To specify a null character (@acronym{ASCII} @sc{nul}) as the field separator, use the two-character string @samp{\0}, e.g., @samp{sort -t '\0'}. @item -T @var{tempdir} @itemx --temporary-directory=@var{tempdir} @opindex -T @opindex --temporary-directory @cindex temporary directory @vindex TMPDIR Use directory @var{tempdir} to store temporary files, overriding the @env{TMPDIR} environment variable. If this option is given more than once, temporary files are stored in all the directories given. If you have a large sort or merge that is I/O-bound, you can often improve performance by using this option to specify directories on different disks and controllers. @item -u @itemx --unique @opindex -u @opindex --unique @cindex uniquifying output Normally, output only the first of a sequence of lines that compare equal. For the @option{--check} (@option{-c}) option, check that no pair of consecutive lines compares equal. This option also disables the default last-resort comparison. The commands @code{sort -u} and @code{sort | uniq} are equivalent, but this equivalence does not extend to arbitrary @command{sort} options. For example, @code{sort -n -u} inspects only the value of the initial numeric string when checking for uniqueness, whereas @code{sort -n | uniq} inspects the entire line. @xref{uniq invocation}. @item -z @itemx --zero-terminated @opindex -z @opindex --zero-terminated @cindex sort zero-terminated lines Treat the input as a set of lines, each terminated by a null character (@acronym{ASCII} @sc{nul}) instead of a line feed (@acronym{ASCII} @sc{lf}). This option can be useful in conjunction with @samp{perl -0} or @samp{find -print0} and @samp{xargs -0} which do the same in order to reliably handle arbitrary file names (even those containing blanks or other special characters). @end table Historical (BSD and System V) implementations of @command{sort} have differed in their interpretation of some options, particularly @option{-b}, @option{-f}, and @option{-n}. @sc{gnu} sort follows the @acronym{POSIX} behavior, which is usually (but not always!) like the System V behavior. According to @acronym{POSIX}, @option{-n} no longer implies @option{-b}. For consistency, @option{-M} has been changed in the same way. This may affect the meaning of character positions in field specifications in obscure cases. The only fix is to add an explicit @option{-b}. A position in a sort field specified with the @option{-k} option has the form @samp{@var{f}.@var{c}}, where @var{f} is the number of the field to use and @var{c} is the number of the first character from the beginning of the field. In a start position, an omitted @samp{.@var{c}} stands for the field's first character. In an end position, an omitted or zero @samp{.@var{c}} stands for the field's last character. If the start field falls after the end of the line or after the end field, the field is empty. If the @option{-b} option was specified, the @samp{.@var{c}} part of a field specification is counted from the first nonblank character of the field. A sort key position may also have any of the option letters @samp{Mbdfinr} appended to it, in which case the global ordering options are not used for that particular field. The @option{-b} option may be independently attached to either or both of the start and end positions of a field specification, and if it is inherited from the global options it will be attached to both. If input lines can contain leading or adjacent blanks and @option{-t} is not used, then @option{-k} is typically combined with @option{-b}, @option{-g}, @option{-M}, or @option{-n}; otherwise the varying numbers of leading blanks in fields can cause confusing results. Keys can span multiple fields. @vindex _POSIX2_VERSION @vindex POSIXLY_CORRECT On older systems, @command{sort} supports an obsolete origin-zero syntax @samp{+@var{pos1} [-@var{pos2}]} for specifying sort keys. This obsolete behavior can be enabled or disabled with the @env{_POSIX2_VERSION} environment variable (@pxref{Standards conformance}); it can also be enabled when @env{POSIXLY_CORRECT} is not set by using the obsolete syntax with @samp{-@var{pos2}} present. Scripts intended for use on standard hosts should avoid obsolete syntax and should use @option{-k} instead. For example, avoid @samp{sort +2}, since it might be interpreted as either @samp{sort ./+2} or @samp{sort -k 3}. If your script must also run on hosts that support only the obsolete syntax, it can use a test like @samp{if sort -k 1 /dev/null 2>&1; then @dots{}} to decide which syntax to use. Here are some examples to illustrate various combinations of options. @itemize @bullet @item Sort in descending (reverse) numeric order. @example sort -n -r @end example @item Sort alphabetically, omitting the first and second fields and the blanks at the start of the third field. This uses a single key composed of the characters beginning at the start of the first nonblank character in field three and extending to the end of each line. @example sort -k 3b @end example @item Sort numerically on the second field and resolve ties by sorting alphabetically on the third and fourth characters of field five. Use @samp{:} as the field delimiter. @example sort -t : -k 2,2n -k 5.3,5.4 @end example Note that if you had written @option{-k 2n} instead of @option{-k 2,2n} @command{sort} would have used all characters beginning in the second field and extending to the end of the line as the primary @emph{numeric} key. For the large majority of applications, treating keys spanning more than one field as numeric will not do what you expect. Also note that the @samp{n} modifier was applied to the field-end specifier for the first key. It would have been equivalent to specify @option{-k 2n,2} or @option{-k 2n,2n}. All modifiers except @samp{b} apply to the associated @emph{field}, regardless of whether the modifier character is attached to the field-start and/or the field-end part of the key specifier. @item Sort the password file on the fifth field and ignore any leading blanks. Sort lines with equal values in field five on the numeric user ID in field three. Fields are separated by @samp{:}. @example sort -t : -k 5b,5 -k 3,3n /etc/passwd sort -t : -n -k 5b,5 -k 3,3 /etc/passwd sort -t : -b -k 5,5 -k 3,3n /etc/passwd @end example These three commands have equivalent effect. The first specifies that the first key's start position ignores leading blanks and the second key is sorted numerically. The other two commands rely on global options being inherited by sort keys that lack modifiers. The inheritance works in this case because @option{-k 5b,5b} and @option{-k 5b,5} are equivalent, as the location of a field-end lacking a @samp{.@var{c}} character position is not affected by whether initial blanks are skipped. @item Sort a set of log files, primarily by IPv4 address and secondarily by time stamp. If two lines' primary and secondary keys are identical, output the lines in the same order that they were input. The log files contain lines that look like this: @example 4.150.156.3 - - [01/Apr/2004:06:31:51 +0000] message 1 211.24.3.231 - - [24/Apr/2004:20:17:39 +0000] message 2 @end example Fields are separated by exactly one space. Sort IPv4 addresses lexicographically, e.g., 212.61.52.2 sorts before 212.129.233.201 because 61 is less than 129. @example 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,4n @end example This example cannot be done with a single @command{sort} invocation, since IPv4 address components are separated by @samp{.} while dates come just after a space. So it is broken down into two invocations of @command{sort}: the first sorts by time stamp and the second by IPv4 address. The time stamp is sorted by year, then month, then day, and finally by hour-minute-second field, using @option{-k} to isolate each field. Except for hour-minute-second there's no need to specify the end of each key field, since the @samp{n} and @samp{M} modifiers sort based on leading prefixes that cannot cross field boundaries. The IPv4 addresses are sorted lexicographically. The second sort uses @samp{-s} so that ties in the primary key are broken by the secondary key; the first sort uses @samp{-s} so that the combination of the two sorts is stable. @item Generate a tags file in case-insensitive sorted order. @smallexample find src -type f -print0 | sort -z -f | xargs -0 etags --append @end smallexample The use of @option{-print0}, @option{-z}, and @option{-0} in this case means that file names that contain blanks or other special characters are not broken up by the sort operation. @c This example is a bit contrived and needs more explanation. @c @item @c Sort records separated by an arbitrary string by using a pipe to convert @c each record delimiter string to @samp{\0}, then using sort's -z option, @c and converting each @samp{\0} back to the original record delimiter. @c @c @example @c printf 'c\n\nb\n\na\n'|perl -0pe 's/\n\n/\n\0/g'|sort -z|perl -0pe 's/\0/\n/g' @c @end example @item Shuffle a list of directories, but preserve the order of files within each directory. For instance, one could use this to generate a music playlist in which albums are shuffled but the songs of each album are played in order. @example ls */* | sort -t / -k 1,1R -k 2,2 @end example @end itemize @node uniq invocation @section @command{uniq}: Uniquify files @pindex uniq @cindex uniquify files @command{uniq} writes the unique lines in the given @file{input}, or standard input if nothing is given or for an @var{input} name of @samp{-}. Synopsis: @example uniq [@var{option}]@dots{} [@var{input} [@var{output}]] @end example By default, @command{uniq} prints its input lines, except that it discards all but the first of adjacent repeated lines, so that no output lines are repeated. Optionally, it can instead discard lines that are not repeated, or all repeated lines. The input need not be sorted, but repeated input lines are detected only if they are adjacent. If you want to discard non-adjacent duplicate lines, perhaps you want to use @code{sort -u}. @xref{sort invocation}. @vindex LC_COLLATE Comparisons use the character collating sequence specified by the @env{LC_COLLATE} locale category. If no @var{output} file is specified, @command{uniq} writes to standard output. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -f @var{n} @itemx --skip-fields=@var{n} @opindex -f @opindex --skip-fields Skip @var{n} fields on each line before checking for uniqueness. Use a null string for comparison if a line has fewer than @var{n} fields. Fields are sequences of non-space non-tab characters that are separated from each other by at least one space or tab. For compatibility @command{uniq} supports an obsolete option syntax @option{-@var{n}}. New scripts should use @option{-f @var{n}} instead. @item -s @var{n} @itemx --skip-chars=@var{n} @opindex -s @opindex --skip-chars Skip @var{n} characters before checking for uniqueness. Use a null string for comparison if a line has fewer than @var{n} characters. If you use both the field and character skipping options, fields are skipped over first. @vindex _POSIX2_VERSION On older systems, @command{uniq} supports an obsolete option syntax @option{+@var{n}}. This obsolete behavior can be enabled or disabled with the @env{_POSIX2_VERSION} environment variable (@pxref{Standards conformance}), but portable scripts should avoid commands whose behavior depends on this variable. For example, use @samp{uniq ./+10} or @samp{uniq -s 10} rather than the ambiguous @samp{uniq +10}. @item -c @itemx --count @opindex -c @opindex --count Print the number of times each line occurred along with the line. @item -i @itemx --ignore-case @opindex -i @opindex --ignore-case Ignore differences in case when comparing lines. @item -d @itemx --repeated @opindex -d @opindex --repeated @cindex repeated lines, outputting Discard lines that are not repeated. When used by itself, this option causes @command{uniq} to print the first copy of each repeated line, and nothing else. @item -D @itemx --all-repeated[=@var{delimit-method}] @opindex -D @opindex --all-repeated @cindex all repeated lines, outputting Do not discard the second and subsequent repeated input lines, but discard lines that are not repeated. This option is useful mainly in conjunction with other options e.g., to ignore case or to compare only selected fields. The optional @var{delimit-method} tells how to delimit groups of repeated lines, and must be one of the following: @table @samp @item none Do not delimit groups of repeated lines. This is equivalent to @option{--all-repeated} (@option{-D}). @item prepend Output a newline before each group of repeated lines. @item separate Separate groups of repeated lines with a single newline. This is the same as using @samp{prepend}, except that there is no newline before the first group, and hence may be better suited for output direct to users. @end table Note that when groups are delimited and the input stream contains two or more consecutive blank lines, then the output is ambiguous. To avoid that, filter the input through @samp{tr -s '\n'} to replace each sequence of consecutive newlines with a single newline. This is a @sc{gnu} extension. @c FIXME: give an example showing *how* it's useful @item -u @itemx --unique @opindex -u @opindex --unique @cindex unique lines, outputting Discard the first repeated line. When used by itself, this option causes @command{uniq} to print unique lines, and nothing else. @item -w @var{n} @itemx --check-chars=@var{n} @opindex -w @opindex --check-chars Compare at most @var{n} characters on each line (after skipping any specified fields and characters). By default the entire rest of the lines are compared. @end table @exitstatus @node comm invocation @section @command{comm}: Compare two sorted files line by line @pindex comm @cindex line-by-line comparison @cindex comparing sorted files @command{comm} writes to standard output lines that are common, and lines that are unique, to two input files; a file name of @samp{-} means standard input. Synopsis: @example comm [@var{option}]@dots{} @var{file1} @var{file2} @end example @vindex LC_COLLATE Before @command{comm} can be used, the input files must be sorted using the collating sequence specified by the @env{LC_COLLATE} locale. If an input file ends in a non-newline character, a newline is silently appended. The @command{sort} command with no options always outputs a file that is suitable input to @command{comm}. @cindex differing lines @cindex common lines With no options, @command{comm} produces three-column output. Column one contains lines unique to @var{file1}, column two contains lines unique to @var{file2}, and column three contains lines common to both files. Columns are separated by a single TAB character. @c FIXME: when there's an option to supply an alternative separator @c string, append `by default' to the above sentence. @opindex -1 @opindex -2 @opindex -3 The options @option{-1}, @option{-2}, and @option{-3} suppress printing of the corresponding columns. Also see @ref{Common options}. Unlike some other comparison utilities, @command{comm} has an exit status that does not depend on the result of the comparison. Upon normal completion @command{comm} produces an exit code of zero. If there is an error it exits with nonzero status. @node tsort invocation @section @command{tsort}: Topological sort @pindex tsort @cindex topological sort @command{tsort} performs a topological sort on the given @var{file}, or standard input if no input file is given or for a @var{file} of @samp{-}. For more details and some history, see @ref{tsort background}. Synopsis: @example tsort [@var{option}] [@var{file}] @end example @command{tsort} reads its input as pairs of strings, separated by blanks, indicating a partial ordering. The output is a total ordering that corresponds to the given partial ordering. For example @example tsort < out $ dd bs=1 skip=222 count=6 < out 2>/dev/null; echo deeper @end example Note that although the listing above includes a trailing slash for the @samp{deeper} entry, the offsets select the name without the trailing slash. However, if you invoke @command{ls} with @option{--dired} along with an option like @option{--escape} (aka @option{-b}) and operate on a file whose name contains special characters, notice that the backslash @emph{is} included: @example $ 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=escape @end example If you use a quoting style that adds quote marks (e.g., @option{--quoting-style=c}), then the offsets include the quote marks. So beware that the user may select the quoting style via the environment variable @env{QUOTING_STYLE}. Hence, applications using @option{--dired} should either specify an explicit @option{--quoting-style=literal} option (aka @option{-N} or @option{--literal}) on the command line, or else be prepared to parse the escaped names. @item --full-time @opindex --full-time Produce long format directory listings, and list times in full. It is equivalent to using @option{--format=long} with @option{--time-style=full-iso} (@pxref{Formatting file timestamps}). @item -g @opindex -g Produce long format directory listings, but don't display owner information. @item -G @itemx --no-group @opindex -G @opindex --no-group Inhibit display of group information in a long format directory listing. (This is the default in some non-@sc{gnu} versions of @command{ls}, so we provide this option for compatibility.) @optHumanReadable @item -i @itemx --inode @opindex -i @opindex --inode @cindex inode number, printing Print the inode number (also called the file serial number and index number) of each file to the left of the file name. (This number uniquely identifies each file within a particular file system.) @item -l @itemx --format=long @itemx --format=verbose @opindex -l @opindex --format @opindex long ls @r{format} @opindex verbose ls @r{format} In addition to the name of each file, print the file type, file mode bits, number of hard links, owner name, group name, size, and timestamp (@pxref{Formatting file timestamps}), normally the modification time. Normally the size is printed as a byte count without punctuation, but this can be overridden (@pxref{Block size}). For example, @option{-h} prints an abbreviated, human-readable count, and @samp{--block-size="'1"} prints a byte count with the thousands separator of the current locale. For each directory that is listed, preface the files with a line @samp{total @var{blocks}}, where @var{blocks} is the total disk allocation for all files in that directory. The block size currently defaults to 1024 bytes, but this can be overridden (@pxref{Block size}). The @var{blocks} computed counts each hard link separately; this is arguably a deficiency. The file type is one of the following characters: @c The commented-out entries are ones we're not sure about. @table @samp @item - regular file @item b block special file @item c character special file @item C high performance (``contiguous data'') file @item d directory @item D door (Solaris 2.5 and up) @c @item F @c semaphore, if this is a distinct file type @item l symbolic link @c @item m @c multiplexed file (7th edition Unix; obsolete) @item M off-line (``migrated'') file (Cray DMF) @item n network special file (HP-UX) @item p FIFO (named pipe) @item P port (Solaris 10 and up) @c @item Q @c message queue, if this is a distinct file type @item s socket @c @item S @c shared memory object, if this is a distinct file type @c @item T @c typed memory object, if this is a distinct file type @c @item w @c whiteout (4.4BSD; not implemented) @item ? some other file type @end table @cindex permissions, output by @command{ls} The file mode bits listed are similar to symbolic mode specifications (@pxref{Symbolic Modes}). But @command{ls} combines multiple bits into the third character of each set of permissions as follows: @table @samp @item s If the setuid or setgid bit and the corresponding executable bit are both set. @item S If the setuid or setgid bit is set but the corresponding executable bit is not set. @item t If the sticky bit and the other-executable bit are both set. @item T If the sticky bit is set but the other-executable bit is not set. @item x If the executable bit is set and none of the above apply. @item - Otherwise. @end table Following the file mode bits is a single character that specifies whether an alternate access method such as an access control list applies to the file. When the character following the file mode bits is a space, there is no alternate access method. When it is a printing character, then there is such a method. For a file with an extended access control list, a @samp{+} character is listed. Basic access control lists are equivalent to the permissions listed, and are not considered an alternate access method. @item -n @itemx --numeric-uid-gid @opindex -n @opindex --numeric-uid-gid @cindex numeric uid and gid @cindex numeric user and group IDs Produce long format directory listings, but display numeric user and group IDs instead of the owner and group names. @item -o @opindex -o Produce long format directory listings, but don't display group information. It is equivalent to using @option{--format=long} with @option{--no-group} . @item -s @itemx --size @opindex -s @opindex --size @cindex disk allocation @cindex size of files, reporting Print the disk allocation of each file to the left of the file name. This is the amount of disk space used by the file, which is usually a bit more than the file's size, but it can be less if the file has holes. Normally the disk allocation is printed in units of 1024 bytes, but this can be overridden (@pxref{Block size}). @cindex NFS mounts from BSD to HP-UX For files that are NFS-mounted from an HP-UX system to a BSD system, this option reports sizes that are half the correct values. On HP-UX systems, it reports sizes that are twice the correct 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 @command{ls} program. @optSi @end table @node Sorting the output @subsection Sorting the output @cindex sorting @command{ls} output These options change the order in which @command{ls} sorts the information it outputs. By default, sorting is done by character code (e.g., @acronym{ASCII} order). @table @samp @item -c @itemx --time=ctime @itemx --time=status @opindex -c @opindex --time @opindex ctime@r{, printing or sorting by} @opindex status time@r{, printing or sorting by} @opindex use time@r{, printing or sorting files by} If the long listing format (e.g., @option{-l}, @option{-o}) is being used, print the status change time (the @samp{ctime} in the inode) instead of the modification time. When explicitly sorting by time (@option{--sort=time} or @option{-t}) or when not using a long listing format, sort according to the status change time. @item -f @opindex -f @cindex unsorted directory listing @cindex directory order, listing by Primarily, like @option{-U}---do not sort; list the files in whatever order they are stored in the directory. But also enable @option{-a} (list all files) and disable @option{-l}, @option{--color}, and @option{-s} (if they were specified before the @option{-f}). @item -r @itemx --reverse @opindex -r @opindex --reverse @cindex reverse sorting Reverse whatever the sorting method is---e.g., list files in reverse alphabetical order, youngest first, smallest first, or whatever. @item -S @itemx --sort=size @opindex -S @opindex --sort @opindex size of files@r{, sorting files by} Sort by file size, largest first. @item -t @itemx --sort=time @opindex -t @opindex --sort @opindex modification time@r{, sorting files by} Sort by modification time (the @samp{mtime} in the inode), newest first. @item -u @itemx --time=atime @itemx --time=access @itemx --time=use @opindex -u @opindex --time @opindex use time@r{, printing or sorting files by} @opindex atime@r{, printing or sorting files by} @opindex access time@r{, printing or sorting files by} If the long listing format (e.g., @option{--format=long}) is being used, print the last access time (the @samp{atime} in the inode). When explicitly sorting by time (@option{--sort=time} or @option{-t}) or when not using a long listing format, sort according to the access time. @item -U @itemx --sort=none @opindex -U @opindex --sort @opindex none@r{, sorting option for @command{ls}} Do not sort; list the files in whatever order they are stored in the directory. (Do not do any of the other unrelated things that @option{-f} does.) This is especially useful when listing very large directories, since not doing any sorting can be noticeably faster. @item -v @itemx --sort=version @opindex -v @opindex --sort @opindex version@r{, sorting option for @command{ls}} Sort by version name and number, lowest first. It behaves like a default sort, except that each sequence of decimal digits is treated numerically as an index/version number. (@xref{More details about version sort}.) @item -X @itemx --sort=extension @opindex -X @opindex --sort @opindex extension@r{, sorting files by} Sort directory contents alphabetically by file extension (characters after the last @samp{.}); files with no extension are sorted first. @end table @node More details about version sort @subsection More details about version sort The version sort takes into account the fact that file names frequently include indices or version numbers. Standard sorting functions usually do not produce the ordering that people expect because comparisons are made on a character-by-character basis. The version sort addresses this problem, and is especially useful when browsing directories that contain many files with indices/version numbers in their names: @example $ ls -1 $ ls -1v foo.zml-1.gz foo.zml-1.gz foo.zml-100.gz foo.zml-2.gz foo.zml-12.gz foo.zml-6.gz foo.zml-13.gz foo.zml-12.gz foo.zml-2.gz foo.zml-13.gz foo.zml-25.gz foo.zml-25.gz foo.zml-6.gz foo.zml-100.gz @end example Note also that numeric parts with leading zeros are considered as fractional one: @example $ ls -1 $ ls -1v abc-1.007.tgz abc-1.007.tgz abc-1.012b.tgz abc-1.01a.tgz abc-1.01a.tgz abc-1.012b.tgz @end example This functionality is implemented using the @code{strverscmp} function. @xref{String/Array Comparison, , , libc, The GNU C Library Reference Manual}. One result of that implementation decision is that @code{ls -v} does not use the locale category, @env{LC_COLLATE}. As a result, non-numeric prefixes are sorted as if @env{LC_COLLATE} were set to @code{C}. @node General output formatting @subsection General output formatting These options affect the appearance of the overall output. @table @samp @item -1 @itemx --format=single-column @opindex -1 @opindex --format @opindex single-column @r{output of files} List one file per line. This is the default for @command{ls} when standard output is not a terminal. @item -C @itemx --format=vertical @opindex -C @opindex --format @opindex vertical @r{sorted files in columns} List files in columns, sorted vertically. This is the default for @command{ls} if standard output is a terminal. It is always the default for the @command{dir} program. @sc{gnu} @command{ls} uses variable width columns to display as many files as possible in the fewest lines. @item --color [=@var{when}] @opindex --color @cindex color, distinguishing file types with Specify whether to use color for distinguishing file types. @var{when} may be omitted, or one of: @itemize @bullet @item none @vindex none @r{color option} - Do not use color at all. This is the default. @item auto @vindex auto @r{color option} @cindex terminal, using color iff - Only use color if standard output is a terminal. @item always @vindex always @r{color option} - Always use color. @end itemize Specifying @option{--color} and no @var{when} is equivalent to @option{--color=always}. Piping a colorized listing through a pager like @command{more} or @command{less} usually produces unreadable results. However, using @code{more -f} does seem to work. @item -F @itemx --classify @itemx --indicator-style=classify @opindex -F @opindex --classify @opindex --indicator-style @cindex file type and executables, marking @cindex executables and file type, marking Append a character to each file name indicating the file type. Also, for regular files that are executable, append @samp{*}. The file type indicators are @samp{/} for directories, @samp{@@} for symbolic links, @samp{|} for FIFOs, @samp{=} for sockets, @samp{>} for doors, and nothing for regular files. @c The following sentence is the same as the one for -d. Do not follow symbolic links listed on the command line unless the @option{--dereference-command-line} (@option{-H}), @option{--dereference} (@option{-L}), or @option{--dereference-command-line-symlink-to-dir} options are specified. @item --file-type @itemx --indicator-style=file-type @opindex --file-type @opindex --indicator-style @cindex file type, marking Append a character to each file name indicating the file type. This is like @option{-F}, except that executables are not marked. @item --indicator-style=@var{word} @opindex --indicator-style Append a character indicator with style @var{word} to entry names, as follows: @table @samp @item none Do not append any character indicator; this is the default. @item slash Append @samp{/} for directories. This is the same as the @option{-p} option. @item file-type Append @samp{/} for directories, @samp{@@} for symbolic links, @samp{|} for FIFOs, @samp{=} for sockets, and nothing for regular files. This is the same as the @option{--file-type} option. @item classify Append @samp{*} for executable regular files, otherwise behave as for @samp{file-type}. This is the same as the @option{-F} or @option{--classify} option. @end table @item -k @opindex -k Print file sizes in 1024-byte blocks, overriding the default block size (@pxref{Block size}). This option is equivalent to @option{--block-size=1K}. @item -m @itemx --format=commas @opindex -m @opindex --format @opindex commas@r{, outputting between files} List files horizontally, with as many as will fit on each line, separated by @samp{, } (a comma and a space). @item -p @itemx --indicator-style=slash @opindex -p @opindex --indicator-style @cindex file type, marking Append a @samp{/} to directory names. @item -x @itemx --format=across @itemx --format=horizontal @opindex -x @opindex --format @opindex across@r{, listing files} @opindex horizontal@r{, listing files} List the files in columns, sorted horizontally. @item -T @var{cols} @itemx --tabsize=@var{cols} @opindex -T @opindex --tabsize Assume that each tab stop is @var{cols} columns wide. The default is 8. @command{ls} uses tabs where possible in the output, for efficiency. If @var{cols} is zero, do not use tabs at all. @item -w @itemx --width=@var{cols} @opindex -w @opindex --width @vindex COLUMNS Assume the screen is @var{cols} columns wide. The default is taken from the terminal settings if possible; otherwise the environment variable @env{COLUMNS} is used if it is set; otherwise the default is 80. @end table @node Formatting file timestamps @subsection Formatting file timestamps By default, file timestamps are listed in abbreviated form. Most locales use a timestamp like @samp{2002-03-30 23:45}. However, the default @acronym{POSIX} locale uses a date like @samp{Mar 30@ @ 2002} for non-recent timestamps, and a date-without-year and time like @samp{Mar 30 23:45} for recent timestamps. A timestamp is considered to be @dfn{recent} if it is less than six months old, and is not dated in the future. If a timestamp dated today is not listed in recent form, the timestamp is in the future, which means you probably have clock skew problems which may break programs like @command{make} that rely on file timestamps. @vindex TZ Time stamps are listed according to the time zone rules specified by the @env{TZ} environment variable, or by the system default rules if @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone with @env{TZ}, libc, The GNU C Library}. The following option changes how file timestamps are printed. @table @samp @item --time-style=@var{style} @opindex --time-style @cindex time style List timestamps in style @var{style}. The @var{style} should be one of the following: @table @samp @item +@var{format} @vindex LC_TIME List timestamps using @var{format}, where @var{format} is interpreted like the format argument of @command{date} (@pxref{date invocation}). For example, @option{--time-style="+%Y-%m-%d %H:%M:%S"} causes @command{ls} to list timestamps like @samp{2002-03-30 23:45:56}. As with @command{date}, @var{format}'s interpretation is affected by the @env{LC_TIME} locale category. If @var{format} contains two format strings separated by a newline, the former is used for non-recent files and the latter for recent files; if you want output columns to line up, you may need to insert spaces in one of the two formats. @item full-iso List timestamps in full using @acronym{ISO} 8601 date, time, and time zone format with nanosecond precision, e.g., @samp{2002-03-30 23:45:56.477817180 -0700}. This style is equivalent to @samp{+%Y-%m-%d %H:%M:%S.%N %z}. This is useful because the time output includes all the information that is available from the operating system. For example, this can help explain @command{make}'s behavior, since @acronym{GNU} @command{make} uses the full timestamp to determine whether a file is out of date. @item long-iso List @acronym{ISO} 8601 date and time in minutes, e.g., @samp{2002-03-30 23:45}. These timestamps are shorter than @samp{full-iso} timestamps, and are usually good enough for everyday work. This style is equivalent to @samp{+%Y-%m-%d %H:%M}. @item iso List @acronym{ISO} 8601 dates for non-recent timestamps (e.g., @samp{2002-03-30@ }), and @acronym{ISO} 8601 month, day, hour, and minute for recent timestamps (e.g., @samp{03-30 23:45}). These timestamps are uglier than @samp{long-iso} timestamps, but they carry nearly the same information in a smaller space and their brevity helps @command{ls} output fit within traditional 80-column output lines. The following two @command{ls} invocations are equivalent: @example newline=' ' ls -l --time-style="+%Y-%m-%d $newline%m-%d %H:%M" ls -l --time-style="iso" @end example @item locale @vindex LC_TIME List timestamps in a locale-dependent form. For example, a Finnish locale might list non-recent timestamps like @samp{maalis 30@ @ 2002} and recent timestamps like @samp{maalis 30 23:45}. Locale-dependent timestamps typically consume more space than @samp{iso} timestamps and are harder for programs to parse because locale conventions vary so widely, but they are easier for many people to read. The @env{LC_TIME} locale category specifies the timestamp format. The default @acronym{POSIX} locale uses timestamps like @samp{Mar 30@ @ 2002} and @samp{Mar 30 23:45}; in this locale, the following two @command{ls} invocations are equivalent: @example newline=' ' ls -l --time-style="+%b %e %Y$newline%b %e %H:%M" ls -l --time-style="locale" @end example Other locales behave differently. For example, in a German locale, @option{--time-style="locale"} might be equivalent to @option{--time-style="+%e. %b %Y $newline%e. %b %H:%M"} and might generate timestamps like @samp{30. M@"ar 2002@ } and @samp{30. M@"ar 23:45}. @item posix-@var{style} @vindex LC_TIME List @acronym{POSIX}-locale timestamps if the @env{LC_TIME} locale category is @acronym{POSIX}, @var{style} timestamps otherwise. For example, the @samp{posix-long-iso} style lists timestamps like @samp{Mar 30@ @ 2002} and @samp{Mar 30 23:45} when in the @acronym{POSIX} locale, and like @samp{2002-03-30 23:45} otherwise. @end table @end table @vindex TIME_STYLE You can specify the default value of the @option{--time-style} option with the environment variable @env{TIME_STYLE}; if @env{TIME_STYLE} is not set the default style is @samp{locale}. @acronym{GNU} Emacs 21.3 and later use the @option{--dired} option and therefore can parse any date format, but if you are using Emacs 21.1 or 21.2 and specify a non-@acronym{POSIX} locale you may need to set @samp{TIME_STYLE="posix-long-iso"}. To avoid certain denial-of-service attacks, timestamps that would be longer than 1000 bytes may be treated as errors. @node Formatting the file names @subsection Formatting the file names These options change how file names themselves are printed. @table @samp @item -b @itemx --escape @itemx --quoting-style=escape @opindex -b @opindex --escape @opindex --quoting-style @cindex backslash sequences for file names Quote nongraphic characters in file names using alphabetic and octal backslash sequences like those used in C. @item -N @itemx --literal @itemx --quoting-style=literal @opindex -N @opindex --literal @opindex --quoting-style Do not quote file names. However, with @command{ls} nongraphic characters are still printed as question marks if the output is a terminal and you do not specify the @option{--show-control-chars} option. @item -q @itemx --hide-control-chars @opindex -q @opindex --hide-control-chars Print question marks instead of nongraphic characters in file names. This is the default if the output is a terminal and the program is @command{ls}. @item -Q @itemx --quote-name @itemx --quoting-style=c @opindex -Q @opindex --quote-name @opindex --quoting-style Enclose file names in double quotes and quote nongraphic characters as in C. @item --quoting-style=@var{word} @opindex --quoting-style @cindex quoting style Use style @var{word} to quote file names and other strings that may contain arbitrary characters. The @var{word} should be one of the following: @table @samp @item literal Output strings as-is; this is the same as the @option{-N} or @option{--literal} option. @item shell Quote strings for the shell if they contain shell metacharacters or would cause ambiguous output. The quoting is suitable for @acronym{POSIX}-compatible shells like @command{bash}, but it does not always work for incompatible shells like @command{csh}. @item shell-always Quote strings for the shell, even if they would normally not require quoting. @item c Quote strings as for C character string literals, including the surrounding double-quote characters; this is the same as the @option{-Q} or @option{--quote-name} option. @item escape Quote strings as for C character string literals, except omit the surrounding double-quote characters; this is the same as the @option{-b} or @option{--escape} option. @item clocale Quote strings as for C character string literals, except use surrounding quotation marks appropriate for the locale. @item locale @c Use @t instead of @samp to avoid duplicate quoting in some output styles. Quote strings as for C character string literals, except use surrounding quotation marks appropriate for the locale, and quote @t{`like this'} instead of @t{"like this"} in the default C locale. This looks nicer on many displays. @end table You can specify the default value of the @option{--quoting-style} option with the environment variable @env{QUOTING_STYLE}. If that environment variable is not set, the default value is @samp{literal}, but this default may change to @samp{shell} in a future version of this package. @item --show-control-chars @opindex --show-control-chars Print nongraphic characters as-is in file names. This is the default unless the output is a terminal and the program is @command{ls}. @end table @node dir invocation @section @command{dir}: Briefly list directory contents @pindex dir @cindex directory listing, brief @command{dir} is equivalent to @code{ls -C -b}; that is, by default files are listed in columns, sorted vertically, and special characters are represented by backslash escape sequences. @xref{ls invocation, @command{ls}}. @node vdir invocation @section @command{vdir}: Verbosely list directory contents @pindex vdir @cindex directory listing, verbose @command{vdir} is equivalent to @code{ls -l -b}; that is, by default files are listed in long format and special characters are represented by backslash escape sequences. @node dircolors invocation @section @command{dircolors}: Color setup for @command{ls} @pindex dircolors @cindex color setup @cindex setup for color @command{dircolors} outputs a sequence of shell commands to set up the terminal for color output from @command{ls} (and @command{dir}, etc.). Typical usage: @example eval "`dircolors [@var{option}]@dots{} [@var{file}]`" @end example If @var{file} is specified, @command{dircolors} reads it to determine which colors to use for which file types and extensions. Otherwise, a precompiled database is used. For details on the format of these files, run @samp{dircolors --print-database}. @vindex LS_COLORS @vindex SHELL @r{environment variable, and color} The output is a shell command to set the @env{LS_COLORS} environment variable. You can specify the shell syntax to use on the command line, or @command{dircolors} will guess it from the value of the @env{SHELL} environment variable. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -b @itemx --sh @itemx --bourne-shell @opindex -b @opindex --sh @opindex --bourne-shell @cindex Bourne shell syntax for color setup @cindex @command{sh} syntax for color setup Output Bourne shell commands. This is the default if the @env{SHELL} environment variable is set and does not end with @samp{csh} or @samp{tcsh}. @item -c @itemx --csh @itemx --c-shell @opindex -c @opindex --csh @opindex --c-shell @cindex C shell syntax for color setup @cindex @command{csh} syntax for color setup Output C shell commands. This is the default if @code{SHELL} ends with @command{csh} or @command{tcsh}. @item -p @itemx --print-database @opindex -p @opindex --print-database @cindex color database, printing @cindex database for color setup, printing @cindex printing color database Print the (compiled-in) default color configuration database. This output is itself a valid configuration file, and is fairly descriptive of the possibilities. @end table @exitstatus @node Basic operations @chapter Basic operations @cindex manipulating files 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. @end menu @node cp invocation @section @command{cp}: Copy files and directories @pindex cp @cindex copying files and directories @cindex files, copying @cindex directories, copying @command{cp} copies files (or, optionally, directories). The copy is completely independent of the original. You can either copy one file to another, or copy arbitrarily many files to a destination directory. Synopses: @example cp [@var{option}]@dots{} [-T] @var{source} @var{dest} cp [@var{option}]@dots{} @var{source}@dots{} @var{directory} cp [@var{option}]@dots{} -t @var{directory} @var{source}@dots{} @end example @itemize @bullet @item If two file names are given, @command{cp} copies the first file to the second. @item If the @option{--target-directory} (@option{-t}) option is given, or failing that if the last file is a directory and the @option{--no-target-directory} (@option{-T}) option is not given, @command{cp} copies each @var{source} file to the specified directory, using the @var{source}s' names. @end itemize Generally, files are written just as they are read. For exceptions, see the @option{--sparse} option below. By default, @command{cp} does not copy directories. However, the @option{-R}, @option{-a}, and @option{-r} options cause @command{cp} to copy recursively by descending into source directories and copying files to corresponding destination directories. By default, @command{cp} follows symbolic links only when not copying recursively. This default can be overridden with the @option{--archive} (@option{-a}), @option{-d}, @option{--dereference} (@option{-L}), @option{--no-dereference} (@option{-P}), and @option{-H} options. If more than one of these options is specified, the last one silently overrides the others. By default, @command{cp} copies the contents of special files only when not copying recursively. This default can be overridden with the @option{--copy-contents} option. @cindex self-backups @cindex backups, making only @command{cp} generally refuses to copy a file onto itself, with the following exception: if @option{--force --backup} is specified with @var{source} and @var{dest} identical, and referring to a regular file, @command{cp} will make a backup file, either regular or numbered, as specified in the usual ways (@pxref{Backup options}). This is useful when you simply want to make a backup of an existing file before changing it. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @itemx --archive @opindex -a @opindex --archive Preserve as much as possible of the structure and attributes of the original files in the copy (but do not attempt to preserve internal directory structure; i.e., @samp{ls -U} may list the entries in a copied directory in a different order). Equivalent to @option{-dpPR}. @item -b @itemx @w{@kbd{--backup}[=@var{method}]} @opindex -b @opindex --backup @vindex VERSION_CONTROL @cindex backups, making @xref{Backup options}. Make a backup of each file that would otherwise be overwritten or removed. As a special case, @command{cp} makes a backup of @var{source} when the force and backup options are given and @var{source} and @var{dest} are the same name for an existing, regular file. One useful application of this combination of options is this tiny Bourne shell script: @example #!/bin/sh # Usage: backup FILE... # Create a @sc{gnu}-style backup of each listed FILE. for i; do cp --backup --force -- "$i" "$i" done @end example @item --copy-contents @cindex directories, copying recursively @cindex copying directories recursively @cindex recursively copying directories @cindex non-directories, copying as special files 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 writing it to the destination. It is usually a mistake to use this option, as it normally has undesirable effects on special files like FIFOs and the ones typically found in the @file{/dev} directory. In most cases, @code{cp -R --copy-contents} will hang indefinitely trying to read from FIFOs and special files like @file{/dev/console}, and it will fill up your destination disk if you use it to copy @file{/dev/zero}. This option has no effect unless copying recursively, and it does not affect the copying of symbolic links. @item -d @opindex -d @cindex symbolic links, copying @cindex hard links, preserving Copy symbolic links as symbolic links rather than copying the files that they point to, and preserve hard links between source files in the copies. Equivalent to @option{--no-dereference --preserve=links}. @item -f @itemx --force @opindex -f @opindex --force When copying without this option and an existing destination file cannot be opened for writing, the copy fails. However, with @option{--force}), when a destination file cannot be opened, @command{cp} then unlinks it and tries to open it again. Contrast this behavior with that enabled by @option{--link} and @option{--symbolic-link}, whereby the destination file is never opened but rather is unlinked unconditionally. Also see the description of @option{--remove-destination}. @item -H @opindex -H If a command line argument specifies a symbolic link, then copy the file it points to rather than the symbolic link itself. However, copy (preserving its nature) any symbolic link that is encountered via recursive traversal. @item -i @itemx --interactive @opindex -i @opindex --interactive Prompt whether to overwrite existing regular destination files. @item -l @itemx --link @opindex -l @opindex --link Make hard links instead of copies of non-directories. @item -L @itemx --dereference @opindex -L @opindex --dereference Always follow symbolic links. @item -P @itemx --no-dereference @opindex -P @opindex --no-dereference @cindex symbolic links, copying Copy symbolic links as symbolic links rather than copying the files that they point to. @item -p @itemx @w{@kbd{--preserve}[=@var{attribute_list}]} @opindex -p @opindex --preserve @cindex file information, preserving Preserve the specified attributes of the original files. If specified, the @var{attribute_list} must be a comma-separated list of one or more of the following strings: @table @samp @itemx mode Preserve the file mode bits and access control lists. @itemx ownership Preserve the owner and group. On most modern systems, only the super-user may change the owner of a file, and regular users may preserve the group ownership of a file only if they happen to be a member of the desired group. @itemx timestamps Preserve the times of last access and last modification. @itemx links Preserve in the destination files any links between corresponding source files. @c Give examples illustrating how hard links are preserved. @c Also, show how soft links map to hard links with -L and -H. @itemx all Preserve all file attributes. Equivalent to specifying all of the above. @end table Using @option{--preserve} with no @var{attribute_list} is equivalent to @option{--preserve=mode,ownership,timestamps}. In the absence of this option, each destination file is created with the mode bits of the corresponding source file, minus the bits set in the umask and minus the set-user-ID and set-group-ID bits. @xref{File permissions}. @itemx @w{@kbd{--no-preserve}=@var{attribute_list}} @cindex file information, preserving Do not preserve the specified attributes. The @var{attribute_list} has the same form as for @option{--preserve}. @itemx --parents @opindex --parents @cindex parent directories and @command{cp} Form the name of each destination file by appending to the target directory a slash and the specified name of the source file. The last argument given to @command{cp} must be the name of an existing directory. For example, the command: @example cp --parents a/b/c existing_dir @end example @noindent copies the file @file{a/b/c} to @file{existing_dir/a/b/c}, creating any missing intermediate directories. @itemx @w{@kbd{--reply}=@var{how}} @opindex --reply @cindex interactivity @c FIXME: remove in 2008 @strong{Deprecated: to be removed in 2008.}@* Using @option{--reply=yes} makes @command{cp} act as if @samp{yes} were given as a response to every prompt about a destination file. That effectively cancels any preceding @option{--interactive} or @option{-i} option. Specify @option{--reply=no} to make @command{cp} act as if @samp{no} were given as a response to every prompt about a destination file. Specify @option{--reply=query} to make @command{cp} prompt the user about each existing destination file. @item -R @itemx -r @itemx --recursive @opindex -R @opindex -r @opindex --recursive @cindex directories, copying recursively @cindex copying directories recursively @cindex recursively copying directories @cindex non-directories, copying as special files Copy directories recursively. Symbolic links are not followed by default; see the @option{--archive} (@option{-a}), @option{-d}, @option{--dereference} (@option{-L}), @option{--no-dereference} (@option{-P}), and @option{-H} options. Special files are copied by creating a destination file of the same type as the source; see the @option{--copy-contents} option. It is not portable to use @option{-r} to copy symbolic links or special files. On some non-@sc{gnu} systems, @option{-r} implies the equivalent of @option{-L} and @option{--copy-contents} for historical reasons. Also, it is not portable to use @option{-R} to copy symbolic links unless you also specify @option{-P}, as @acronym{POSIX} allows implementations that dereference symbolic links by default. @item --remove-destination @opindex --remove-destination Remove each existing destination file before attempting to open it (contrast with @option{-f} above). @item --sparse=@var{when} @opindex --sparse=@var{when} @cindex sparse files, copying @cindex holes, copying files with @findex read @r{system call, and holes} A @dfn{sparse file} contains @dfn{holes}---a sequence of zero bytes that does not occupy any physical disk blocks; the @samp{read} system call reads these as zeros. This can both save considerable disk space and increase speed, since many binary files contain lots of consecutive zero bytes. By default, @command{cp} detects holes in input source files via a crude heuristic and makes the corresponding output file sparse as well. Only regular files may be sparse. The @var{when} value can be one of the following: @table @samp @item auto The default behavior: if the input file is sparse, attempt to make the output file sparse, too. However, if an output file exists but refers to a non-regular file, then do not attempt to make it sparse. @item always For each sufficiently long sequence of zero bytes in the input file, attempt to create a corresponding hole in the output file, even if the input file does not appear to be sparse. This is useful when the input file resides on a file system that does not support sparse files (for example, @samp{efs} file systems in SGI IRIX 5.3 and earlier), but the output file is on a type of file system that does support them. Holes may be created only in regular files, so if the destination file is of some other type, @command{cp} does not even try to make it sparse. @item never Never make the output file sparse. This is useful in creating a file for use with the @command{mkswap} command, since such a file must not have any holes. @end table @optStripTrailingSlashes @item -s @itemx --symbolic-link @opindex -s @opindex --symbolic-link @cindex symbolic links, copying with Make symbolic links instead of copies of non-directories. All source file names must be absolute (starting with @samp{/}) unless the destination files are in the current directory. This option merely results in an error message on systems that do not support symbolic links. @optBackupSuffix @optTargetDirectory @optNoTargetDirectory @item -u @itemx --update @opindex -u @opindex --update @cindex newer files, copying only Do not copy a non-directory that has an existing destination with the same or newer modification time. If time stamps are being preserved, the comparison is to the source time stamp truncated to the resolutions of the destination file system and of the system calls used to update time stamps; this avoids duplicate work if several @samp{cp -pu} commands are executed with the same source and destination. @item -v @itemx --verbose @opindex -v @opindex --verbose Print the name of each file before copying it. @item -x @itemx --one-file-system @opindex -x @opindex --one-file-system @cindex file systems, omitting copying to different Skip subdirectories that are on different file systems from the one that the copy started on. However, mount point directories @emph{are} copied. @end table @exitstatus @node dd invocation @section @command{dd}: Convert and copy a file @pindex dd @cindex converting while copying a file @command{dd} copies a file (from standard input to standard output, by default) with a changeable I/O block size, while optionally performing conversions on it. Synopses: @example dd [@var{operand}]@dots{} dd @var{option} @end example The only options are @option{--help} and @option{--version}. @xref{Common options}. @command{dd} accepts the following operands. @table @samp @item if=@var{file} @opindex if Read from @var{file} instead of standard input. @item of=@var{file} @opindex of Write to @var{file} instead of standard output. Unless @samp{conv=notrunc} is given, @command{dd} truncates @var{file} to zero bytes (or the size specified with @samp{seek=}). @item ibs=@var{bytes} @opindex ibs @cindex block size of input @cindex input block size Read @var{bytes} bytes at a time. @item obs=@var{bytes} @opindex obs @cindex block size of output @cindex output block size Write @var{bytes} bytes at a time. @item bs=@var{bytes} @opindex bs @cindex block size Both read and write @var{bytes} bytes at a time. This overrides @samp{ibs} and @samp{obs}. @item cbs=@var{bytes} @opindex cbs @cindex block size of conversion @cindex conversion block size Convert @var{bytes} bytes at a time. @item skip=@var{blocks} @opindex skip Skip @var{blocks} @samp{ibs}-byte blocks in the input file before copying. @item seek=@var{blocks} @opindex seek Skip @var{blocks} @samp{obs}-byte blocks in the output file before copying. @item count=@var{blocks} @opindex count Copy @var{blocks} @samp{ibs}-byte blocks from the input file, instead of everything until the end of the file. @item conv=@var{conversion}[,@var{conversion}]@dots{} @opindex conv Convert the file as specified by the @var{conversion} argument(s). (No spaces around any comma(s).) Conversions: @table @samp @item ascii @opindex ascii@r{, converting to} Convert @acronym{EBCDIC} to @acronym{ASCII}, using the conversion table specified by @acronym{POSIX}. This provides a 1:1 translation for all 256 bytes. @item ebcdic @opindex ebcdic@r{, converting to} Convert @acronym{ASCII} to @acronym{EBCDIC}. This is the inverse of the @samp{ascii} conversion. @item ibm @opindex alternate ebcdic@r{, converting to} Convert @acronym{ASCII} to alternate @acronym{EBCDIC}, using the alternate conversion table specified by @acronym{POSIX}. This is not a 1:1 translation, but reflects common historical practice for @samp{~}, @samp{[}, and @samp{]}. The @samp{ascii}, @samp{ebcdic}, and @samp{ibm} conversions are mutually exclusive. @item block @opindex block @r{(space-padding)} For each line in the input, output @samp{cbs} bytes, replacing the input newline with a space and padding with spaces as necessary. @item unblock @opindex unblock Replace trailing spaces in each @samp{cbs}-sized input block with a newline. The @samp{block} and @samp{unblock} conversions are mutually exclusive. @item lcase @opindex lcase@r{, converting to} Change uppercase letters to lowercase. @item ucase @opindex ucase@r{, converting to} Change lowercase letters to uppercase. The @samp{lcase} and @samp{ucase} conversions are mutually exclusive. @item swab @opindex swab @r{(byte-swapping)} @cindex byte-swapping Swap every pair of input bytes. @sc{gnu} @command{dd}, unlike others, works when an odd number of bytes are read---the last byte is simply copied (since there is nothing to swap it with). @item noerror @opindex noerror @cindex read errors, ignoring Continue after read errors. @item nocreat @opindex nocreat @cindex creating output file, avoiding Do not create the output file; the output file must already exist. @item excl @opindex excl @cindex creating output file, requiring Fail if the output file already exists; @command{dd} must create the output file itself. The @samp{excl} and @samp{nocreat} conversions are mutually exclusive. @item notrunc @opindex notrunc @cindex truncating output file, avoiding Do not truncate the output file. @item sync @opindex sync @r{(padding with nulls)} Pad every input block to size of @samp{ibs} with trailing zero bytes. When used with @samp{block} or @samp{unblock}, pad with spaces instead of zero bytes. @item fdatasync @opindex fdatasync @cindex synchronized data writes, before finishing Synchronize output data just before finishing. This forces a physical write of output data. @item fsync @opindex fsync @cindex synchronized data and metadata writes, before finishing Synchronize output data and metadata just before finishing. This forces a physical write of output data and metadata. @end table @item iflag=@var{flag}[,@var{flag}]@dots{} @opindex iflag Access the input file using the flags specified by the @var{flag} argument(s). (No spaces around any comma(s).) @item oflag=@var{flag}[,@var{flag}]@dots{} @opindex oflag Access the output file using the flags specified by the @var{flag} argument(s). (No spaces around any comma(s).) Here are the flags. Not every flag is supported on every operating system. @table @samp @item append @opindex append @cindex appending to the output file Write in append mode, so that even if some other process is writing to this file, every @command{dd} write will append to the current contents of the file. This flag makes sense only for output. @item direct @opindex direct @cindex direct I/O Use direct I/O for data, avoiding the buffer cache. @item directory @opindex directory @cindex directory I/O Fail unless the file is a directory. Most operating systems do not allow I/O to a directory, so this flag has limited utility. @item dsync @opindex dsync @cindex synchronized data reads Use synchronized I/O for data. For the output file, this forces a physical write of output data on each write. For the input file, this flag can matter when reading from a remote file that has been written to synchronously by some other process. Metadata (e.g., last-access and last-modified time) is not necessarily synchronized. @item sync @opindex sync @cindex synchronized data and metadata I/O Use synchronized I/O for both data and metadata. @item nonblock @opindex nonblock @cindex nonblocking I/O Use non-blocking I/O. @item noatime @opindex noatime @cindex access time Do not update the file's access time. @item noctty @opindex noctty @cindex controlling terminal Do not assign the file to be a controlling terminal for @command{dd}. This has no effect when the file is not a terminal. On many hosts (e.g., @acronym{GNU}/Linux hosts), this option has no effect at all. @item nofollow @opindex nofollow @cindex symbolic links, following Do not follow symbolic links. @item nolinks @opindex nolinks @cindex hard links Fail if the file has multiple hard links. @item binary @opindex binary @cindex binary I/O Use binary I/O. This option has an effect only on nonstandard platforms that distinguish binary from text I/O. @item text @opindex text @cindex text I/O Use text I/O. Like @samp{binary}, this option has no effect on standard platforms. @end table These flags are not supported on all systems, and @samp{dd} rejects attempts to use them when they are not supported. When reading from standard input or writing to standard output, the @samp{nofollow} and @samp{noctty} flags should not be specified, and the other flags (e.g., @samp{nonblock}) can affect how other processes behave with the affected file descriptors, even after @command{dd} exits. @end table @cindex multipliers after numbers The numeric-valued strings above (@var{bytes} and @var{blocks}) can be followed by a multiplier: @samp{b}=512, @samp{c}=1, @samp{w}=2, @samp{x@var{m}}=@var{m}, or any of the standard block size suffixes like @samp{k}=1024 (@pxref{Block size}). Use different @command{dd} invocations to use different block sizes for skipping and I/O@. For example, the following shell commands copy data in 512 KiB blocks between a disk and a tape, but do not save or restore a 4 KiB label at the start of the disk: @example disk=/dev/rdsk/c0t1d0s2 tape=/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 >$disk @end example Sending an @samp{INFO} signal to a running @command{dd} process makes it print I/O statistics to standard error and then resume copying. In the example below, @command{dd} is run in the background to copy 10 million blocks. The @command{kill} command makes it output intermediate I/O statistics, and when @command{dd} completes, it outputs the final statistics. @example $ dd if=/dev/zero of=/dev/null count=10MB & pid=$! $ kill -s INFO $pid; wait $pid 3385223+0 records in 3385223+0 records out 1733234176 bytes (1.7 GB) copied, 6.42173 seconds, 270 MB/s 10000000+0 records in 10000000+0 records out 5120000000 bytes (5.1 GB) copied, 18.913 seconds, 271 MB/s @end example @vindex POSIXLY_CORRECT On systems lacking the @samp{INFO} signal @command{dd} responds to the @samp{USR1} signal instead, unless the @env{POSIXLY_CORRECT} environment variable is set. @exitstatus @node install invocation @section @command{install}: Copy files and set attributes @pindex install @cindex copying files and setting attributes @command{install} copies files while setting their file mode bits and, if possible, their owner and group. Synopses: @example install [@var{option}]@dots{} [-T] @var{source} @var{dest} install [@var{option}]@dots{} @var{source}@dots{} @var{directory} install [@var{option}]@dots{} -t @var{directory} @var{source}@dots{} install [@var{option}]@dots{} -d @var{directory}@dots{} @end example @itemize @bullet @item If two file names are given, @command{install} copies the first file to the second. @item If the @option{--target-directory} (@option{-t}) option is given, or failing that if the last file is a directory and the @option{--no-target-directory} (@option{-T}) option is not given, @command{install} copies each @var{source} file to the specified directory, using the @var{source}s' names. @item If the @option{--directory} (@option{-d}) option is given, @command{install} creates each @var{directory} and any missing parent directories. @end itemize @cindex Makefiles, installing programs in @command{install} is similar to @command{cp}, but allows you to control the attributes of destination files. It is typically used in Makefiles to copy programs into their destination directories. It refuses to copy files onto themselves. The program accepts the following options. Also see @ref{Common options}. @table @samp @optBackup @item -c @opindex -c Ignored; for compatibility with old Unix versions of @command{install}. @item -d @itemx --directory @opindex -d @opindex --directory @cindex directories, creating with given attributes @cindex parent directories, creating missing @cindex leading directories, creating missing Create each given directory and any missing parent directories, setting the owner, group and mode as given on the command line or to the defaults. It also gives any parent directories it creates those attributes. (This is different from the SunOS 4.x @command{install}, which gives directories that it creates the default attributes.) @item -g @var{group} @itemx --group=@var{group} @opindex -g @opindex --group @cindex group ownership of installed files, setting Set the group ownership of installed files or directories to @var{group}. The default is the process's current group. @var{group} may be either a group name or a numeric group ID. @item -m @var{mode} @itemx --mode=@var{mode} @opindex -m @opindex --mode @cindex permissions of installed files, setting Set the file mode bits for the installed file or directory to @var{mode}, which can be either an octal number, or a symbolic mode as in @command{chmod}, with @samp{a=} (no access allowed to anyone) as the point of departure (@pxref{File permissions}). The default mode is @samp{u=rwx,go=rx}---read, write, and execute for the owner, and read and execute for group and other. @item -o @var{owner} @itemx --owner=@var{owner} @opindex -o @opindex --owner @cindex ownership of installed files, setting @cindex appropriate privileges @vindex root @r{as default owner} If @command{install} has appropriate privileges (is run as root), set the ownership of installed files or directories to @var{owner}. The default is @code{root}. @var{owner} may be either a user name or a numeric user ID. @item -p @itemx --preserve-timestamps @opindex -p @opindex --preserve-timestamps @cindex timestamps of installed files, preserving Set the time of last access and the time of last modification of each installed file to match those of each corresponding original file. When a file is installed without this option, its last access and last modification times are both set to the time of installation. This option is useful if you want to use the last modification times of installed files to keep track of when they were last built as opposed to when they were last installed. @item -s @itemx --strip @opindex -s @opindex --strip @cindex symbol table information, stripping @cindex stripping symbol table information Strip the symbol tables from installed binary executables. @optBackupSuffix @optTargetDirectory @optNoTargetDirectory @item -v @itemx --verbose @opindex -v @opindex --verbose Print the name of each file before copying it. @end table @exitstatus @node mv invocation @section @command{mv}: Move (rename) files @pindex mv @command{mv} moves or renames files (or directories). Synopses: @example mv [@var{option}]@dots{} [-T] @var{source} @var{dest} mv [@var{option}]@dots{} @var{source}@dots{} @var{directory} mv [@var{option}]@dots{} -t @var{directory} @var{source}@dots{} @end example @itemize @bullet @item If two file names are given, @command{mv} moves the first file to the second. @item If the @option{--target-directory} (@option{-t}) option is given, or failing that if the last file is a directory and the @option{--no-target-directory} (@option{-T}) option is not given, @command{mv} moves each @var{source} file to the specified directory, using the @var{source}s' names. @end itemize @command{mv} can move any type of file from one file system to another. Prior to version @code{4.0} of the fileutils, @command{mv} could move only regular files between file systems. For example, now @command{mv} can move an entire directory hierarchy including special device files from one partition to another. It first uses some of the same code that's used by @code{cp -a} to copy the requested directories and files, then (assuming the copy succeeded) it removes the originals. If the copy fails, then the part that was copied to the destination partition is removed. If you were to copy three directories from one partition to another and the copy of the first directory succeeded, but the second didn't, the first would be left on the destination partition and the second and third would be left on the original partition. @cindex prompting, and @command{mv} If a destination file exists but is normally unwritable, standard input is a terminal, and the @option{-f} or @option{--force} option is not given, @command{mv} prompts the user for whether to replace the file. (You might own the file, or have write permission on its directory.) If the response is not affirmative, the file is skipped. @emph{Warning}: If you try to move a symlink that points to a directory, and you specify the symlink with a trailing slash, then @command{mv} doesn't move the symlink but instead moves the directory referenced by the symlink. @xref{Trailing slashes}. The program accepts the following options. Also see @ref{Common options}. @table @samp @optBackup @item -f @itemx --force @opindex -f @opindex --force @cindex prompts, omitting Do not prompt the user before removing a destination file. @item -i @itemx --interactive @opindex -i @opindex --interactive @cindex prompts, forcing Prompt whether to overwrite each existing destination file, regardless of its permissions. If the response is not affirmative, the file is skipped. @itemx @w{@kbd{--reply}=@var{how}} @opindex --reply @cindex interactivity @c FIXME: remove in 2008 @strong{Deprecated: to be removed in 2008.}@* Specifying @option{--reply=yes} is equivalent to using @option{--force}. Specify @option{--reply=no} to make @command{mv} act as if @samp{no} were given as a response to every prompt about a destination file. Specify @option{--reply=query} to make @command{mv} prompt the user about each existing destination file. Note that @option{--reply=no} has an effect only when @command{mv} would prompt without @option{-i} or equivalent, i.e., when a destination file exists and is not writable, standard input is a terminal, and no @option{-f} (or equivalent) option is specified. @item -u @itemx --update @opindex -u @opindex --update @cindex newer files, moving only Do not move a non-directory that has an existing destination with the same or newer modification time. If the move is across file system boundaries, the comparison is to the source time stamp truncated to the resolutions of the destination file system and of the system calls used to update time stamps; this avoids duplicate work if several @samp{mv -u} commands are executed with the same source and destination. @item -v @itemx --verbose @opindex -v @opindex --verbose Print the name of each file before moving it. @optStripTrailingSlashes @optBackupSuffix @optTargetDirectory @optNoTargetDirectory @end table @exitstatus @node rm invocation @section @command{rm}: Remove files or directories @pindex rm @cindex removing files or directories @command{rm} removes each given @var{file}. By default, it does not remove directories. Synopsis: @example rm [@var{option}]@dots{} [@var{file}]@dots{} @end example @cindex prompting, and @command{rm} If the @option{-I} or @option{--interactive=once} option is given, and there are more than three files or the @option{-r}, @option{-R}, or @option{--recursive} are given, then @command{rm} prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted. Otherwise, if a file is unwritable, standard input is a terminal, and the @option{-f} or @option{--force} option is not given, or the @option{-i} or @option{--interactive=always} option @emph{is} given, @command{rm} prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped. @emph{Warning}: If you use @command{rm} to remove a file, it is usually possible to recover the contents of that file. If you want more assurance that the contents are truly unrecoverable, consider using @command{shred}. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -f @itemx --force @opindex -f @opindex --force Ignore nonexistent files and never prompt the user. Ignore any previous @option{--interactive} (@option{-i}) option. @item -i @opindex -i Prompt whether to remove each file. If the response is not affirmative, the file is skipped. Ignore any previous @option{--force} (@option{-f}) option. Equivalent to @option{--interactive=always}. @item -I @opindex -I Prompt once whether to proceed with the command, if more than three files are named or if a recursive removal is requested. Ignore any previous @option{--force} (@option{-f}) option. Equivalent to @option{--interactive=once}. @itemx --interactive [=@var{when}] @opindex --interactive Specify when to issue an interactive prompt. @var{when} may be omitted, or one of: @itemize @bullet @item never @vindex never @r{interactive option} - Do not prompt at all. @item once @vindex once @r{interactive option} - Prompt once if more than three files are named or if a recursive removal is requested. Equivalent to @option{-I}. @item always @vindex always @r{interactive option} - Prompt for every file being removed. Equivalent to @option{-i}. @end itemize Specifying @option{--interactive} and no @var{when} is equivalent to @option{--interactive=always}. @itemx --preserve-root @opindex --preserve-root @cindex root directory, disallow recursive destruction Fail upon any attempt to remove the file system root, @file{/}, when used with the @option{--recursive} option. Without @option{--recursive}, this option has no effect. @xref{Treating / specially}. @itemx --no-preserve-root @opindex --no-preserve-root @cindex root directory, allow recursive destruction Cancel the effect of any preceding @option{--preserve-root} option. @xref{Treating / specially}. @item -r @itemx -R @itemx --recursive @opindex -r @opindex -R @opindex --recursive @cindex directories, removing (recursively) Remove the listed directories and their contents recursively. @item -v @itemx --verbose @opindex -v @opindex --verbose Print the name of each file before removing it. @end table @cindex files beginning with @samp{-}, removing @cindex @samp{-}, removing files beginning with One common question is how to remove files whose names begin with a @samp{-}. @sc{gnu} @command{rm}, like every program that uses the @code{getopt} function to parse its arguments, lets you use the @samp{--} option to indicate that all following arguments are non-options. To remove a file called @file{-f} in the current directory, you could type either: @example rm -- -f @end example @noindent or: @example rm ./-f @end example @opindex - @r{and Unix @command{rm}} The Unix @command{rm} program's use of a single @samp{-} for this purpose predates the development of the getopt standard syntax. @exitstatus @node shred invocation @section @command{shred}: Remove files more securely @pindex shred @cindex data, erasing @cindex erasing data @command{shred} overwrites devices or files, to help prevent even very expensive hardware from recovering the data. Ordinarily when you remove a file (@pxref{rm invocation}), the data is not actually destroyed. Only the index listing where the file is stored is destroyed, and the storage is made available for reuse. There are undelete utilities that will attempt to reconstruct the index and 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 a few seconds. But there is no way to know for sure. If you have sensitive data, you may want to be sure that recovery is not possible by actually overwriting the file with non-sensitive data. However, even after doing that, it is possible to take the disk back to a laboratory and use a lot of sensitive (and expensive) equipment to look for the faint ``echoes'' of the original data underneath the overwritten data. If the data has only been overwritten once, it's not even that hard. The best way to remove something irretrievably is to destroy the media it's on with acid, melt it down, or the like. For cheap removable media like floppy disks, this is the preferred method. However, hard drives are expensive and hard to melt, so the @command{shred} utility tries to achieve a similar effect non-destructively. This uses many overwrite passes, with the data patterns chosen to maximize the damage they do to the old data. While this will work on floppies, the patterns are designed for best effect on hard drives. For more details, see the source code and Peter Gutmann's paper @uref{http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html, @cite{Secure Deletion of Data from Magnetic and Solid-State Memory}}, from the proceedings of the Sixth @acronym{USENIX} Security Symposium (San Jose, California, July 22--25, 1996). @strong{Please note} that @command{shred} relies on a very important assumption: that the file system overwrites data in place. This is the traditional way to do things, but many modern file system designs do not satisfy this assumption. Exceptions include: @itemize @bullet @item Log-structured or journaled file systems, such as those supplied with AIX and Solaris, and JFS, ReiserFS, XFS, Ext3 (in @code{data=journal} mode), BFS, NTFS, etc.@: when they are configured to journal @emph{data}. @item File systems that write redundant data and carry on even if some writes fail, such as RAID-based file systems. @item File systems that make snapshots, such as Network Appliance's NFS server. @item File systems that cache in temporary locations, such as NFS version 3 clients. @item Compressed file systems. @end itemize In the particular case of ext3 file systems, the above disclaimer applies (and @command{shred} is thus of limited effectiveness) only in @code{data=journal} mode, which journals file data in addition to just metadata. In both the @code{data=ordered} (default) and @code{data=writeback} modes, @command{shred} works as usual. Ext3 journaling modes can be changed by adding the @code{data=something} option to the mount options for a particular file system in the @file{/etc/fstab} file, as documented in the mount man page (man mount). If you are not sure how your file system operates, then you should assume that it does not overwrite data in place, which means that shred cannot reliably operate on regular files in your file system. Generally speaking, it is more reliable to shred a device than a file, since this bypasses the problem of file system design mentioned above. However, even shredding devices is not always completely reliable. For example, most disks map out bad sectors invisibly to the application; if the bad sectors contain sensitive data, @command{shred} won't be able to destroy it. @command{shred} makes no attempt to detect or report this problem, just as it makes no attempt to do anything about backups. However, since it is more reliable to shred devices than files, @command{shred} by default does not truncate or remove the output file. This default is more suitable for devices, which typically cannot be truncated and should not be removed. Finally, consider the risk of backups and mirrors. File system backups and remote mirrors may contain copies of the file that cannot be 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 @command{shred}, be sure that it is not backed up or mirrored. @example shred [@var{option}]@dots{} @var{file}[@dots{}] @end example The program accepts the following options. Also see @ref{Common options}. @table @samp @item -f @itemx --force @opindex -f @opindex --force @cindex force deletion Override file permissions if necessary to allow overwriting. @item -@var{NUMBER} @itemx -n @var{NUMBER} @itemx --iterations=@var{NUMBER} @opindex -n @var{NUMBER} @opindex --iterations=@var{NUMBER} @cindex iterations, selecting the number of By default, @command{shred} uses 25 passes of overwrite. This is enough for all of the useful overwrite patterns to be used at least once. You can reduce this to save time, or increase it if you have a lot of time to waste. @item -s @var{BYTES} @itemx --size=@var{BYTES} @opindex -s @var{BYTES} @opindex --size=@var{BYTES} @cindex size of file to shred Shred the first @var{BYTES} bytes of the file. The default is to shred the whole file. @var{BYTES} can be followed by a size specification like @samp{K}, @samp{M}, or @samp{G} to specify a multiple. @xref{Block size}. @item -u @itemx --remove @opindex -u @opindex --remove @cindex removing files after shredding After shredding a file, truncate it (if possible) and then remove it. If a file has multiple links, only the named links will be removed. @item -v @itemx --verbose @opindex -v @opindex --verbose Display status updates as sterilization proceeds. @item -x @itemx --exact @opindex -x @opindex --exact By default, @command{shred} rounds the size of a regular file up to the next multiple of the file system block size to fully erase the last block of the file. Use @option{--exact} to suppress that behavior. Thus, by default if you shred a 10-byte regular file on a system with 512-byte blocks, the resulting file will be 512 bytes long. With this option, shred does not increase the apparent size of the file. @item -z @itemx --zero @opindex -z @opindex --zero Normally, the last pass that @command{shred} writes is made up of random data. If this would be conspicuous on your hard drive (for example, because it looks like encrypted data), or you just think it's tidier, the @option{--zero} option adds an additional overwrite pass with all zero bits. This is in addition to the number of passes specified by the @option{--iterations} option. @end table You might use the following command to erase all trace of the file system you'd created on the floppy disk in your first drive. That command takes about 20 minutes to erase a ``1.44MB'' (actually 1440 KiB) floppy. @example shred --verbose /dev/fd0 @end example Similarly, to erase all data on a selected partition of your hard disk, you could give a command like this: @example shred --verbose /dev/sda5 @end example A @var{file} of @samp{-} denotes standard output. The intended use of this is to shred a removed temporary file. For example: @example i=`tempfile -m 0600` exec 3<>"$i" rm -- "$i" echo "Hello, world" >&3 shred - >&3 exec 3>- @end example However, the command @samp{shred - >file} does not shred the contents of @var{file}, since the shell truncates @var{file} before invoking @command{shred}. Use the command @samp{shred file} or (if using a Bourne-compatible shell) the command @samp{shred - 1<>file} instead. @exitstatus @node Special file types @chapter Special file types @cindex special file types @cindex file types, special This chapter describes commands which create special types of files (and @command{rmdir}, which removes directories, one special file type). @cindex special file types @cindex file types Although Unix-like operating systems have markedly fewer special file types than others, not @emph{everything} can be treated only as the undifferentiated byte stream of @dfn{normal files}. For example, when a file is created or removed, the system must record this information, which it does in a @dfn{directory}---a special type of file. Although you can read directories as normal files, if you're curious, in order for the 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 @dfn{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 syscall @end menu @node link invocation @section @command{link}: Make a hard link via the link syscall @pindex link @cindex links, creating @cindex hard links, creating @cindex creating links (hard only) @command{link} creates a single hard link at a time. It is a minimalist interface to the system-provided @code{link} function. @xref{Hard Links, , , libc, The GNU C Library Reference Manual}. It avoids the bells and whistles of the more commonly-used @command{ln} command (@pxref{ln invocation}). Synopsis: @example link @var{filename} @var{linkname} @end example @var{filename} must specify an existing file, and @var{linkname} must specify a nonexistent entry in an existing directory. @command{link} simply calls @code{link (@var{filename}, @var{linkname})} to create the link. On a @acronym{GNU} system, this command acts like @samp{ln --directory --no-target-directory @var{filename} @var{linkname}}. However, the @option{--directory} and @option{--no-target-directory} options are not specified by @acronym{POSIX}, and the @command{link} command is more portable in practice. @exitstatus @node ln invocation @section @command{ln}: Make links between files @pindex ln @cindex links, creating @cindex hard links, creating @cindex symbolic (soft) links, creating @cindex creating links (hard or soft) @cindex file systems and hard links @command{ln} makes links between files. By default, it makes hard links; with the @option{-s} option, it makes symbolic (or @dfn{soft}) links. Synopses: @example ln [@var{option}]@dots{} [-T] @var{target} @var{linkname} ln [@var{option}]@dots{} @var{target} ln [@var{option}]@dots{} @var{target}@dots{} @var{directory} ln [@var{option}]@dots{} -t @var{directory} @var{target}@dots{} @end example @itemize @bullet @item If two file names are given, @command{ln} creates a link to the first file from the second. @item If one @var{target} is given, @command{ln} creates a link to that file in the current directory. @item If the @option{--target-directory} (@option{-t}) option is given, or failing that if the last file is a directory and the @option{--no-target-directory} (@option{-T}) option is not given, @command{ln} creates a link to each @var{target} file in the specified directory, using the @var{target}s' names. @end itemize Normally @command{ln} does not remove existing files. Use the @option{--force} (@option{-f}) option to remove them unconditionally, the @option{--interactive} (@option{-i}) option to remove them conditionally, and the @option{--backup} (@option{-b}) option to rename them. @cindex hard link, defined @cindex inode, and hard links A @dfn{hard link} is another name for an existing file; the link and the original are indistinguishable. Technically speaking, they share the same inode, and the inode contains all the information about a file---indeed, it is not incorrect to say that the inode @emph{is} the file. On all existing implementations, you cannot make a hard link to a directory, and hard links cannot cross file system boundaries. (These restrictions are not mandated by @acronym{POSIX}, however.) @cindex dereferencing symbolic links @cindex symbolic link, defined @dfn{Symbolic links} (@dfn{symlinks} for short), on the other hand, are a special file type (which not all kernels support: System V release 3 (and older) systems lack symlinks) in which the link file actually refers to a different file, by name. When most operations (opening, reading, writing, and so on) are passed the symbolic link file, the kernel automatically @dfn{dereferences} the link and operates on the target of the link. But some operations (e.g., removing) work on the link file itself, rather than on its target. @xref{Symbolic Links,,, libc, The GNU C Library Reference Manual}. The program accepts the following options. Also see @ref{Common options}. @table @samp @optBackup @item -d @itemx -F @itemx --directory @opindex -d @opindex -F @opindex --directory @cindex hard links to directories Allow the super-user to attempt to make hard links to directories. However, note that this will probably fail due to system restrictions, even for the super-user. @item -f @itemx --force @opindex -f @opindex --force Remove existing destination files. @item -i @itemx --interactive @opindex -i @opindex --interactive @cindex prompting, and @command{ln} Prompt whether to remove existing destination files. @item -n @itemx --no-dereference @opindex -n @opindex --no-dereference Do not treat the last operand specially when it is a symbolic link to 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. @command{ln} can treat the destination just as it would a normal directory and create the link in it. On the other hand, the destination can be viewed as a non-directory---as the symlink itself. In that case, @command{ln} must delete or backup that symlink before creating the new link. The default is to treat a destination that is a symlink to a directory just like a directory. This option is weaker than the @option{--no-target-directory} (@option{-T}) option, so it has no effect if both options are given. @item -s @itemx --symbolic @opindex -s @opindex --symbolic Make symbolic links instead of hard links. This option merely produces an error message on systems that do not support symbolic links. @optBackupSuffix @optTargetDirectory @optNoTargetDirectory @item -v @itemx --verbose @opindex -v @opindex --verbose Print the name of each file after linking it successfully. @end table @exitstatus Examples: @smallexample 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 anotherfile ln -s ../adir/afile yetanotherfile @end smallexample @node mkdir invocation @section @command{mkdir}: Make directories @pindex mkdir @cindex directories, creating @cindex creating directories @command{mkdir} creates directories with the specified names. Synopsis: @example mkdir [@var{option}]@dots{} @var{name}@dots{} @end example If a @var{name} is an existing file but not a directory, @command{mkdir} prints a warning message on stderr and will exit with a status of 1 after processing any remaining @var{name}s. The same is done when a @var{name} is an existing directory and the -p option is not given. If a @var{name} is an existing directory and the -p option is given, @command{mkdir} will ignore it. That is, @command{mkdir} will not print a warning, raise an error, or change the mode of the directory (even if the -m option is given), and will move on to processing any remaining @var{name}s. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -m @var{mode} @itemx --mode=@var{mode} @opindex -m @opindex --mode @cindex modes of created directories, setting Set the mode of created directories to @var{mode}, which is symbolic as in @command{chmod} and uses @samp{a=rwx} (read, write and execute allowed for everyone) for the point of the departure. @xref{File permissions}. @item -p @itemx --parents @opindex -p @opindex --parents @cindex parent directories, creating Make any missing parent directories for each argument. The file permission bits of parent directories are set to the umask modified by @samp{u+wx}. Ignore arguments corresponding to existing directories. @item -v @item --verbose @opindex -v @opindex --verbose Print a message for each created directory. This is most useful with @option{--parents}. @end table @exitstatus @node mkfifo invocation @section @command{mkfifo}: Make FIFOs (named pipes) @pindex mkfifo @cindex FIFOs, creating @cindex named pipes, creating @cindex creating FIFOs (named pipes) @command{mkfifo} creates FIFOs (also called @dfn{named pipes}) with the specified names. Synopsis: @example mkfifo [@var{option}] @var{name}@dots{} @end example A @dfn{FIFO} is a special file type that permits independent processes to communicate. One process opens the FIFO file for writing, and another for reading, after which data can flow as with the usual anonymous pipe in shells or elsewhere. The program accepts the following option. Also see @ref{Common options}. @table @samp @item -m @var{mode} @itemx --mode=@var{mode} @opindex -m @opindex --mode @cindex modes of created FIFOs, setting Set the mode of created FIFOs to @var{mode}, which is symbolic as in @command{chmod} and uses @samp{a=rw} (read and write allowed for everyone) for the point of departure. @var{mode} should specify only file permission bits. @xref{File permissions}. @end table @exitstatus @node mknod invocation @section @command{mknod}: Make block or character special files @pindex mknod @cindex block special files, creating @cindex character special files, creating @command{mknod} creates a FIFO, character special file, or block special file with the specified name. Synopsis: @example mknod [@var{option}]@dots{} @var{name} @var{type} [@var{major} @var{minor}] @end example @cindex special files @cindex block special files @cindex character special files Unlike the phrase ``special file type'' above, the term @dfn{special file} has a technical meaning on Unix: something that can generate or receive data. Usually this corresponds to a physical piece of hardware, e.g., a printer or a disk. (These files are typically created at system-configuration time.) The @command{mknod} command is what creates files of this type. Such devices can be read either a character at a time or a ``block'' (many characters) at a time, hence we say there are @dfn{block special} files and @dfn{character special} files. The arguments after @var{name} specify the type of file to make: @table @samp @item p @opindex p @r{for FIFO file} for a FIFO @item b @opindex b @r{for block special file} for a block special file @item c @c Don't document the `u' option -- it's just a synonym for `c'. @c Do *any* versions of mknod still use it? @c @itemx u @opindex c @r{for character special file} @c @opindex u @r{for character special file} for a character special file @end table When making a block or character special file, the major and minor device numbers must be given after the file type. If a major or minor device number begins with @samp{0x} or @samp{0X}, it is interpreted as hexadecimal; otherwise, if it begins with @samp{0}, as octal; otherwise, as decimal. The program accepts the following option. Also see @ref{Common options}. @table @samp @item -m @var{mode} @itemx --mode=@var{mode} @opindex -m @opindex --mode Set the mode of created files to @var{mode}, which is symbolic as in @command{chmod} and uses @samp{a=rw} as the point of departure. @var{mode} should specify only file permission bits. @xref{File permissions}. @end table @exitstatus @node readlink invocation @section @command{readlink}: Print the referent of a symbolic link @pindex readlink @cindex displaying value of a symbolic link @command{readlink} may work in one of two supported modes: @table @samp @item Readlink mode @command{readlink} outputs the value of the given symbolic link. If @command{readlink} is invoked with an argument other than the name of a symbolic link, it produces no output and exits with a nonzero exit code. @item Canonicalize mode @command{readlink} outputs the absolute name of the given file which contains no @file{.}, @file{..} components nor any repeated separators (@file{/}) or symbolic links. @end table @example readlink [@var{option}] @var{file} @end example By default, @command{readlink} operates in readlink mode. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -f @itemx --canonicalize @opindex -f @opindex --canonicalize Activate canonicalize mode. If any component of the file name except the last one is missing or unavailable, @command{readlink} produces no output and exits with a nonzero exit code. @item -e @itemx --canonicalize-existing @opindex -e @opindex --canonicalize-existing Activate canonicalize mode. If any component is missing or unavailable, @command{readlink} produces no output and exits with a nonzero exit code. @item -m @itemx --canonicalize-missing @opindex -m @opindex --canonicalize-missing Activate canonicalize mode. If any component is missing or unavailable, @command{readlink} treats it as a directory. @item -n @itemx --no-newline @opindex -n @opindex --no-newline Do not output the trailing newline. @item -s @itemx -q @itemx --silent @itemx --quiet @opindex -s @opindex -q @opindex --silent @opindex --quiet Suppress most error messages. @item -v @itemx --verbose @opindex -v @opindex --verbose Report error messages. @end table The @command{readlink} utility first appeared in OpenBSD 2.1. @exitstatus @node rmdir invocation @section @command{rmdir}: Remove empty directories @pindex rmdir @cindex removing empty directories @cindex directories, removing empty @command{rmdir} removes empty directories. Synopsis: @example rmdir [@var{option}]@dots{} @var{directory}@dots{} @end example If any @var{directory} argument does not refer to an existing empty directory, it is an error. The program accepts the following option. Also see @ref{Common options}. @table @samp @item --ignore-fail-on-non-empty @opindex --ignore-fail-on-non-empty @cindex directory deletion, ignoring failures Ignore each failure to remove a directory that is solely because the directory is non-empty. @item -p @itemx --parents @opindex -p @opindex --parents @cindex parent directories, removing Remove @var{directory}, then try to remove each component of @var{directory}. So, for example, @samp{rmdir -p a/b/c} is similar to @samp{rmdir a/b/c a/b a}. As such, it fails if any of those directories turns out not to be empty. Use the @option{--ignore-fail-on-non-empty} option to make it so such a failure does not evoke a diagnostic and does not cause @command{rmdir} to exit unsuccessfully. @item -v @item --verbose @opindex -v @opindex --verbose @cindex directory deletion, reporting Give a diagnostic for each successful removal. @var{directory} is removed. @end table @xref{rm invocation}, for how to remove non-empty directories (recursively). @exitstatus @node unlink invocation @section @command{unlink}: Remove files via the unlink syscall @pindex unlink @cindex removing files or directories (via the unlink syscall) @command{unlink} deletes a single specified file name. It is a minimalist interface to the system-provided @code{unlink} function. @xref{Deleting Files, , , libc, The GNU C Library Reference Manual}. Synopsis: It avoids the bells and whistles of the more commonly-used @command{rm} command (@pxref{rm invocation}). @example unlink @var{filename} @end example On some systems @code{unlink} can be used to delete the name of a directory. On others, it can be used that way only by a privileged user. In the GNU system @code{unlink} can never delete the name of a directory. The @command{unlink} command honors the @option{--help} and @option{--version} options. To remove a file whose name begins with @samp{-}, prefix the name with @samp{./}, e.g., @samp{unlink ./--help}. @exitstatus @node Changing file attributes @chapter Changing file attributes @cindex changing file attributes @cindex file attributes, changing @cindex attributes, file A file is not merely its contents, a name, and a file type (@pxref{Special 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, what people in the group can do, and what everyone else can do), various timestamps, and other information. Collectively, we call these a file's @dfn{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. @end menu @node chown invocation @section @command{chown}: Change file owner and group @pindex chown @cindex file ownership, changing @cindex group ownership, changing @cindex changing file ownership @cindex changing group ownership @command{chown} changes the user and/or group ownership of each given @var{file} to @var{new-owner} or to the user and group of an existing reference file. Synopsis: @example chown [@var{option}]@dots{} @{@var{new-owner} | --reference=@var{ref_file}@} @var{file}@dots{} @end example If used, @var{new-owner} specifies the new owner and/or group as follows (with no embedded white space): @example [@var{owner}] [ : [@var{group}] ] @end example Specifically: @table @var @item owner If only an @var{owner} (a user name or numeric user ID) is given, that user is made the owner of each given file, and the files' group is not changed. @item owner@samp{:}group If the @var{owner} is followed by a colon and a @var{group} (a group name or numeric group ID), with no spaces between them, the group ownership of the files is changed as well (to @var{group}). @item owner@samp{:} If a colon but no group name follows @var{owner}, that user is made the owner of the files and the group of the files is changed to @var{owner}'s login group. @item @samp{:}group If the colon and following @var{group} are given, but the owner is omitted, only the group of the files is changed; in this case, @command{chown} performs the same function as @command{chgrp}. @item @samp{:} If only a colon is given, or if @var{new-owner} is empty, neither the owner nor the group is changed. @end table Some older scripts may still use @samp{.} in place of the @samp{:} separator. @acronym{POSIX} 1003.1-2001 (@pxref{Standards conformance}) does not require support for that, but for backward compatibility @acronym{GNU} @command{chown} supports @samp{.} so long as no ambiguity results. New scripts should avoid the use of @samp{.} because it is not portable, and because it has undesirable results if the entire @var{owner@samp{.}group} happens to identify a user whose name contains @samp{.}. The @command{chown} command sometimes clears the set-user-ID or set-group-ID permission bits. This behavior depends on the policy and functionality of the underlying @code{chown} system call, which may make system-dependent file mode modifications outside the control of the @command{chown} command. For example, the @command{chown} command might not affect those bits when operated as the superuser, or if the bits signify some function other than executable permission (e.g., mandatory locking). When in doubt, check the underlying system behavior. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -c @itemx --changes @opindex -c @opindex --changes @cindex changed owners, verbosely describing Verbosely describe the action for each @var{file} whose ownership actually changes. @item -f @itemx --silent @itemx --quiet @opindex -f @opindex --silent @opindex --quiet @cindex error messages, omitting Do not print error messages about files whose ownership cannot be changed. @itemx @w{@kbd{--from}=@var{old-owner}} @opindex --from @cindex symbolic links, changing owner Change a @var{file}'s ownership only if it has current attributes specified by @var{old-owner}. @var{old-owner} has the same form as @var{new-owner} described above. This option is useful primarily from a security standpoint in that it narrows considerably the window of potential abuse. For example, to reflect a user ID numbering change for one user's files without an option like this, @code{root} might run @smallexample find / -owner OLDUSER -print0 | xargs -0 chown -h NEWUSER @end smallexample But that is dangerous because the interval between when the @command{find} tests the existing file's owner and when the @command{chown} is actually run may be quite large. One way to narrow the gap would be to invoke chown for each file as it is found: @example find / -owner OLDUSER -exec chown -h NEWUSER @{@} \; @end example But that is very slow if there are many affected files. With this option, it is safer (the gap is narrower still) though still not perfect: @example chown -h -R --from=OLDUSER NEWUSER / @end example @item --dereference @opindex --dereference @cindex symbolic links, changing owner @findex lchown Do not act on symbolic links themselves but rather on what they point to. This is the default. @item -h @itemx --no-dereference @opindex -h @opindex --no-dereference @cindex symbolic links, changing owner @findex lchown Act on symbolic links themselves instead of what they point to. This mode relies on the @code{lchown} system call. On systems that do not provide the @code{lchown} system call, @command{chown} fails when a file specified on the command line is a symbolic link. By default, no diagnostic is issued for symbolic links encountered during a recursive traversal, but see @option{--verbose}. @itemx --preserve-root @opindex --preserve-root @cindex root directory, disallow recursive modification Fail upon any attempt to recursively change the file system root, @file{/}. Without @option{--recursive}, this option has no effect. @xref{Treating / specially}. @itemx --no-preserve-root @opindex --no-preserve-root @cindex root directory, allow recursive modification Cancel the effect of any preceding @option{--preserve-root} option. @xref{Treating / specially}. @item --reference=@var{ref_file} @opindex --reference Change the user and group of each @var{file} to be the same as those of @var{ref_file}. If @var{ref_file} is a symbolic link, do not use the user and group of the symbolic link, but rather those of the file it refers to. @item -v @itemx --verbose @opindex -v @opindex --verbose Output a diagnostic for every file processed. If a symbolic link is encountered during a recursive traversal on a system without the @code{lchown} system call, and @option{--no-dereference} is in effect, then issue a diagnostic saying neither the symbolic link nor its referent is being changed. @item -R @itemx --recursive @opindex -R @opindex --recursive @cindex recursively changing file ownership Recursively change ownership of directories and their contents. @choptH @xref{Traversing symlinks}. @choptL @xref{Traversing symlinks}. @choptP @xref{Traversing symlinks}. @end table @exitstatus Examples: @smallexample # 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 /u @end smallexample @node chgrp invocation @section @command{chgrp}: Change group ownership @pindex chgrp @cindex group ownership, changing @cindex changing group ownership @command{chgrp} changes the group ownership of each given @var{file} to @var{group} (which can be either a group name or a numeric group ID) or to the group of an existing reference file. Synopsis: @example chgrp [@var{option}]@dots{} @{@var{group} | --reference=@var{ref_file}@} @var{file}@dots{} @end example The program accepts the following options. Also see @ref{Common options}. @table @samp @item -c @itemx --changes @opindex -c @opindex --changes @cindex changed files, verbosely describing Verbosely describe the action for each @var{file} whose group actually changes. @item -f @itemx --silent @itemx --quiet @opindex -f @opindex --silent @opindex --quiet @cindex error messages, omitting Do not print error messages about files whose group cannot be changed. @item --dereference @opindex --dereference @cindex symbolic links, changing owner @findex lchown Do not act on symbolic links themselves but rather on what they point to. This is the default. @item -h @itemx --no-dereference @opindex -h @opindex --no-dereference @cindex symbolic links, changing group @findex lchown Act on symbolic links themselves instead of what they point to. This mode relies on the @code{lchown} system call. On systems that do not provide the @code{lchown} system call, @command{chgrp} fails when a file specified on the command line is a symbolic link. By default, no diagnostic is issued for symbolic links encountered during a recursive traversal, but see @option{--verbose}. @itemx --preserve-root @opindex --preserve-root @cindex root directory, disallow recursive modification Fail upon any attempt to recursively change the file system root, @file{/}. Without @option{--recursive}, this option has no effect. @xref{Treating / specially}. @itemx --no-preserve-root @opindex --no-preserve-root @cindex root directory, allow recursive modification Cancel the effect of any preceding @option{--preserve-root} option. @xref{Treating / specially}. @item --reference=@var{ref_file} @opindex --reference Change the group of each @var{file} to be the same as that of @var{ref_file}. If @var{ref_file} is a symbolic link, do not use the group of the symbolic link, but rather that of the file it refers to. @item -v @itemx --verbose @opindex -v @opindex --verbose Output a diagnostic for every file processed. If a symbolic link is encountered during a recursive traversal on a system without the @code{lchown} system call, and @option{--no-dereference} is in effect, then issue a diagnostic saying neither the symbolic link nor its referent is being changed. @item -R @itemx --recursive @opindex -R @opindex --recursive @cindex recursively changing group ownership Recursively change the group ownership of directories and their contents. @choptH @xref{Traversing symlinks}. @choptL @xref{Traversing symlinks}. @choptP @xref{Traversing symlinks}. @end table @exitstatus Examples: @smallexample # Change the group of /u to "staff". chgrp staff /u # Change the group of /u and subfiles to "staff". chgrp -hR staff /u @end smallexample @node chmod invocation @section @command{chmod}: Change access permissions @pindex chmod @cindex changing access permissions @cindex access permissions, changing @cindex permissions, changing access @command{chmod} changes the access permissions of the named files. Synopsis: @example chmod [@var{option}]@dots{} @{@var{mode} | --reference=@var{ref_file}@} @var{file}@dots{} @end example @cindex symbolic links, permissions of @command{chmod} never changes the permissions of symbolic links, since the @command{chmod} system call cannot change their permissions. This is not a problem since the permissions of symbolic links are never used. However, for each symbolic link listed on the command line, @command{chmod} changes the permissions of the pointed-to file. In contrast, @command{chmod} ignores symbolic links encountered during recursive directory traversals. If used, @var{mode} specifies the new file mode bits. For details, see the section on @ref{File permissions}. If you really want @var{mode} to have a leading @samp{-}, you should use @option{--} first, e.g., @samp{chmod -- -w file}. Typically, though, @samp{chmod a-w file} is preferable, and @command{chmod -w file} (without the @option{--}) complains if it behaves differently from what @samp{chmod a-w file} would do. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -c @itemx --changes @opindex -c @opindex --changes Verbosely describe the action for each @var{file} whose permissions actually changes. @item -f @itemx --silent @itemx --quiet @opindex -f @opindex --silent @opindex --quiet @cindex error messages, omitting Do not print error messages about files whose permissions cannot be changed. @itemx --preserve-root @opindex --preserve-root @cindex root directory, disallow recursive modification Fail upon any attempt to recursively change the file system root, @file{/}. Without @option{--recursive}, this option has no effect. @xref{Treating / specially}. @itemx --no-preserve-root @opindex --no-preserve-root @cindex root directory, allow recursive modification Cancel the effect of any preceding @option{--preserve-root} option. @xref{Treating / specially}. @item -v @itemx --verbose @opindex -v @opindex --verbose Verbosely describe the action or non-action taken for every @var{file}. @item --reference=@var{ref_file} @opindex --reference Change the mode of each @var{file} to be the same as that of @var{ref_file}. @xref{File permissions}. If @var{ref_file} is a symbolic link, do not use the mode of the symbolic link, but rather that of the file it refers to. @item -R @itemx --recursive @opindex -R @opindex --recursive @cindex recursively changing access permissions Recursively change permissions of directories and their contents. @end table @exitstatus @node touch invocation @section @command{touch}: Change file timestamps @pindex touch @cindex changing file timestamps @cindex file timestamps, changing @cindex timestamps, changing file @command{touch} changes the access and/or modification times of the specified files. Synopsis: @example touch [@var{option}]@dots{} @var{file}@dots{} @end example @cindex empty files, creating Any @var{file} that does not exist is created empty. A @var{file} of @samp{-} causes @command{touch} to change the times of the file associated with standard output. @cindex permissions, for changing file timestamps If changing both the access and modification times to the current time, @command{touch} can change the timestamps for files that the user running it does not own but has write permission for. Otherwise, the user must own the files. Although @command{touch} provides options for changing two of the times---the times of last access and modification---of a file, there is actually a third one as well: the inode change time. This is often referred to as a file's @code{ctime}. The inode change time represents the time when the file's meta-information last changed. One common example of this is when the permissions of a file change. Changing the permissions doesn't access the file, so the atime doesn't change, nor does it modify the file, so the mtime doesn't change. Yet, something about the file itself has changed, and this must be noted somewhere. This is the job of the ctime field. This is necessary, so that, for example, a backup program can make a fresh copy of the file, including the new permissions value. Another operation that modifies a file's ctime without affecting the others is renaming. In any case, it is not possible, in normal operations, for a user to change the ctime field to a user-specified value. @vindex TZ Time stamps assume the time zone rules specified by the @env{TZ} environment variable, or by the system default rules if @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone with @env{TZ}, libc, The GNU C Library}. You can avoid avoid ambiguities during daylight saving transitions by using @sc{utc} time stamps. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @itemx --time=atime @itemx --time=access @itemx --time=use @opindex -a @opindex --time @opindex atime@r{, changing} @opindex access @r{time, changing} @opindex use @r{time, changing} Change the access time only. @item -c @itemx --no-create @opindex -c @opindex --no-create Do not create files that do not exist. @item -d @itemx --date=@var{time} @opindex -d @opindex --date @opindex time Use @var{time} instead of the current time. It can contain month names, time zones, @samp{am} and @samp{pm}, @samp{yesterday}, etc. For example, @option{--date="2004-02-27 14:19:13.489392193 +0530"} specifies the instant 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 minutes east of @acronym{UTC}. @xref{Date input formats}. File systems that do not support high-resolution time stamps silently ignore any excess precision here. @item -f @opindex -f @cindex BSD @command{touch} compatibility Ignored; for compatibility with BSD versions of @command{touch}. @item -m @itemx --time=mtime @itemx --time=modify @opindex -m @opindex --time @opindex mtime@r{, changing} @opindex modify @r{time, changing} Change the modification time only. @item -r @var{file} @itemx --reference=@var{file} @opindex -r @opindex --reference Use the times of the reference @var{file} instead of the current time. If this option is combined with the @option{--date=@var{time}} (@option{-d @var{time}}) option, the reference @var{file}'s time is the origin for any relative @var{time}s given, but is otherwise ignored. For example, @samp{-r foo -d '-5 seconds'} specifies a time stamp equal to five seconds before the corresponding time stamp for @file{foo}. @item -t [[@var{CC}]@var{YY}]@var{MMDDhhmm}[.@var{ss}] Use the argument (optional four-digit or two-digit years, months, days, hours, minutes, optional seconds) instead of the current time. If the year is specified with only two digits, then @var{CC} is 20 for years in the range 0 @dots{} 68, and 19 for years in 69 @dots{} 99. If no digits of the year are specified, the argument is interpreted as a date in the current year. @end table @vindex _POSIX2_VERSION On older systems, @command{touch} supports an obsolete syntax, as follows. If no timestamp is given with any of the @option{-d}, @option{-r}, or @option{-t} options, and if there are two or more @var{file}s and the first @var{file} is of the form @samp{@var{MMDDhhmm}[@var{YY}]} and this would be a valid argument to the @option{-t} option (if the @var{YY}, if any, were moved to the front), and if the represented year is in the range 1969--1999, that argument is interpreted as the time for the other files instead of as a file name. This obsolete behavior can be enabled or disabled with the @env{_POSIX2_VERSION} environment variable (@pxref{Standards conformance}), but portable scripts should avoid commands whose behavior depends on this variable. For example, use @samp{touch ./12312359 main.c} or @samp{touch -t 12312359 main.c} rather than the ambiguous @samp{touch 12312359 main.c}. @exitstatus @node Disk usage @chapter Disk usage @cindex disk usage No disk can hold an infinite amount of data. These commands report on how much disk storage is in use or available. (This has nothing much to do with how much @emph{main memory}, i.e., RAM, a program is using when it runs; for that, you want @command{ps} or @command{pstat} or @command{swap} or some such command.) @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. @end menu @node df invocation @section @command{df}: Report file system disk space usage @pindex df @cindex file system disk usage @cindex disk usage by file system @command{df} reports the amount of disk space used and available on file systems. Synopsis: @example df [@var{option}]@dots{} [@var{file}]@dots{} @end example With no arguments, @command{df} reports the space used and available on all currently mounted file systems (of all types). Otherwise, @command{df} reports on the file system containing each argument @var{file}. Normally the disk space is printed in units of 1024 bytes, but this can be overridden (@pxref{Block size}). Non-integer quantities are rounded up to the next higher unit. @cindex disk device file @cindex device file, disk If an argument @var{file} is a disk device file containing a mounted file system, @command{df} shows the space available on that file system rather than on the file system containing the device node (i.e., the root file system). @sc{gnu} @command{df} does not attempt to determine the disk usage on unmounted file systems, because on most kinds of systems doing so requires extremely nonportable intimate knowledge of file system structures. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @itemx --all @opindex -a @opindex --all @cindex automounter file systems @cindex ignore file systems Include in the listing dummy file systems, which are omitted by default. Such file systems are typically special-purpose pseudo-file-systems, such as automounter entries. @item -B @var{size} @itemx --block-size=@var{size} @opindex -B @opindex --block-size @cindex file system sizes Scale sizes by @var{size} before printing them (@pxref{Block size}). For example, @option{-BG} prints sizes in units of 1,073,741,824 bytes. @optHumanReadable @item -H @opindex -H Equivalent to @option{--si}. @item -i @itemx --inodes @opindex -i @opindex --inodes @cindex inode usage List inode usage information instead of block usage. An inode (short for index node) contains information about a file such as its owner, permissions, timestamps, and location on the disk. @item -k @opindex -k @cindex kibibytes for file system sizes Print sizes in 1024-byte blocks, overriding the default block size (@pxref{Block size}). This option is equivalent to @option{--block-size=1K}. @item -l @itemx --local @opindex -l @opindex --local @cindex file system types, limiting output to certain Limit the listing to local file systems. By default, remote file systems are also listed. @item --no-sync @opindex --no-sync @cindex file system space, retrieving old data more quickly Do not invoke the @code{sync} system call before getting any usage data. This may make @command{df} run significantly faster on systems with many disks, but on some systems (notably SunOS) the results may be slightly out of date. This is the default. @item -P @itemx --portability @opindex -P @opindex --portability @cindex one-line output format @cindex @acronym{POSIX} output format @cindex portable output format @cindex output format, portable Use the @acronym{POSIX} output format. This is like the default format except for the following: @enumerate @item The information about each file system is always printed on exactly one line; a mount device is never put on a line by itself. This means that if the mount device name is more than 20 characters long (e.g., for some network mounts), the columns are misaligned. @item The labels in the header output line are changed to conform to @acronym{POSIX}. @end enumerate @optSi @item --sync @opindex --sync @cindex file system space, retrieving current data more slowly Invoke the @code{sync} system call before getting any usage data. On some systems (notably SunOS), doing this yields more up to date results, but in general this option makes @command{df} much slower, especially when there are many or very busy file systems. @item -t @var{fstype} @itemx --type=@var{fstype} @opindex -t @opindex --type @cindex file system types, limiting output to certain Limit the listing to file systems of type @var{fstype}. Multiple file system types can be specified by giving multiple @option{-t} options. By default, nothing is omitted. @item -T @itemx --print-type @opindex -T @opindex --print-type @cindex file system types, printing Print each file system's type. The types printed here are the same ones you can include or exclude with @option{-t} and @option{-x}. The particular types printed are whatever is supported by the system. Here are some of the common names (this list is certainly not exhaustive): @table @samp @item nfs @cindex @acronym{NFS} file system type An @acronym{NFS} file system, i.e., one mounted over a network from another machine. This is the one type name which seems to be used uniformly by all systems. @item 4.2@r{, }ufs@r{, }efs@dots{} @cindex Linux file system types @cindex local file system types @opindex 4.2 @r{file system type} @opindex ufs @r{file system type} @opindex efs @r{file system type} A file system on a locally-mounted hard disk. (The system might even support more than one type here; Linux does.) @item hsfs@r{, }cdfs @cindex CD-ROM file system type @cindex High Sierra file system @opindex hsfs @r{file system type} @opindex cdfs @r{file system type} A file system on a CD-ROM drive. HP-UX uses @samp{cdfs}, most other systems use @samp{hsfs} (@samp{hs} for ``High Sierra''). @item pcfs @cindex PC file system @cindex DOS file system @cindex MS-DOS file system @cindex diskette file system @opindex pcfs An MS-DOS file system, usually on a diskette. @end table @item -x @var{fstype} @itemx --exclude-type=@var{fstype} @opindex -x @opindex --exclude-type Limit the listing to file systems not of type @var{fstype}. Multiple file system types can be eliminated by giving multiple @option{-x} options. By default, no file system types are omitted. @item -v Ignored; for compatibility with System V versions of @command{df}. @end table @exitstatus @node du invocation @section @command{du}: Estimate file space usage @pindex du @cindex file space usage @cindex disk usage for files @command{du} reports the amount of disk space used by the specified files and for each subdirectory (of directory arguments). Synopsis: @example du [@var{option}]@dots{} [@var{file}]@dots{} @end example With no arguments, @command{du} reports the disk space for the current directory. Normally the disk space is printed in units of 1024 bytes, but this can be overridden (@pxref{Block size}). Non-integer quantities are rounded up to the next higher unit. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @itemx --all @opindex -a @opindex --all Show counts for all files, not just directories. @itemx --apparent-size @opindex --apparent-size Print apparent sizes, rather than disk usage. The apparent size of a file is the number of bytes reported by @code{wc -c} on regular files, or more generally, @code{ls -l --block-size=1} or @code{stat --format=%s}. For example, a file containing the word @samp{zoo} with no newline would, of course, have an apparent size of 3. Such a small file may require anywhere from 0 to 16 KiB or more of disk space, depending on the type and configuration of the file system on which the file resides. However, a sparse file created with this command: @example dd bs=1 seek=2GiB if=/dev/null of=big @end example @noindent has an apparent size of 2 GiB, yet on most modern systems, it actually uses almost no disk space. @item -b @itemx --bytes @opindex -b @opindex --bytes Equivalent to @code{--apparent-size --block-size=1}. @item -B @var{size} @itemx --block-size=@var{size} @opindex -B @opindex --block-size @cindex file sizes Scale sizes by @var{size} before printing them (@pxref{Block size}). For example, @option{-BG} prints sizes in units of 1,073,741,824 bytes. @item -c @itemx --total @opindex -c @opindex --total @cindex grand total of disk space Print a grand total of all arguments after all arguments have been processed. This can be used to find out the total disk usage of a given set of files or directories. @item -D @itemx --dereference-args @opindex -D @opindex --dereference-args Dereference symbolic links that are command line arguments. Does not affect other symbolic links. This is helpful for finding out the disk usage of directories, such as @file{/usr/tmp}, which are often symbolic links. @itemx --files0-from=@var{FILE} @opindex --files0-from=@var{FILE} @cindex including files from @command{du} Rather than processing files named on the command line, process those named in file @var{FILE}; each name is terminated by a null byte. This is useful with the @option{--total} (@option{-c}) option when the list of file names is so long that it may exceed a command line length limitation. In such cases, running @command{du} via @command{xargs} is undesirable because it splits the list into pieces and makes @command{du} print a total for each sublist rather than for the entire list. One way to produce a list of null-byte-terminated file names is with @sc{gnu} @command{find}, using its @option{-print0} predicate. Do not specify any @var{FILE} on the command line when using this option. @optHumanReadable @item -H @opindex -H Currently, @option{-H} is the same as @option{--si}, except that @option{-H} evokes a warning. This option will be changed to be equivalent to @option{--dereference-args} (@option{-D}). @item -k @opindex -k @cindex kibibytes for file sizes Print sizes in 1024-byte blocks, overriding the default block size (@pxref{Block size}). This option is equivalent to @option{--block-size=1K}. @item -l @itemx --count-links @opindex -l @opindex --count-links @cindex hard links, counting in @command{du} Count the size of all files, even if they have appeared already (as a hard link). @item -L @itemx --dereference @opindex -L @opindex --dereference @cindex symbolic links, dereferencing in @command{du} Dereference symbolic links (show the disk space used by the file or directory that the link points to instead of the space used by the link). @item -m @opindex -m @cindex mebibytes for file sizes Print sizes in 1,048,576-byte blocks, overriding the default block size (@pxref{Block size}). This option is equivalent to @option{--block-size=1M}. @item -P @itemx --no-dereference @opindex -P @opindex --no-dereference @cindex symbolic links, dereferencing in @command{du} For each symbolic links encountered by @command{du}, consider the disk space used by the symbolic link. @item --max-depth=@var{DEPTH} @opindex --max-depth=@var{DEPTH} @cindex limiting output of @command{du} Show the total for each directory (and file if --all) that is at most MAX_DEPTH levels down from the root of the hierarchy. The root is at level 0, so @code{du --max-depth=0} is equivalent to @code{du -s}. @item -0 @opindex -0 @itemx --null @opindex --null @cindex output null-byte-terminated lines Output a null byte at the end of each line, rather than a newline. This option enables other programs to parse the output of @command{du} even when that output would contain file names with embedded newlines. @itemx --si @opindex --si @cindex SI output Append an SI-style abbreviation to each size, such as @samp{MB} for megabytes. Powers of 1000 are used, not 1024; @samp{MB} stands for 1,000,000 bytes. Use the @option{-h} or @option{--human-readable} option if you prefer powers of 1024. @item -s @itemx --summarize @opindex -s @opindex --summarize Display only a total for each argument. @item -S @itemx --separate-dirs @opindex -S @opindex --separate-dirs Report the size of each directory separately, not including the sizes of subdirectories. @itemx --time @opindex --time @cindex last modified dates, displaying in @command{du} Show time of the most recent modification of any file in the directory, or any of its subdirectories. @itemx --time=ctime @itemx --time=status @itemx --time=use @opindex --time @opindex ctime@r{, show the most recent} @opindex status time@r{, show the most recent} @opindex use time@r{, show the most recent} Show the most recent status change time (the @samp{ctime} in the inode) of any file in the directory, instead of the modification time. @itemx --time=atime @itemx --time=access @opindex --time @opindex atime@r{, show the most recent} @opindex access time@r{, show the most recent} Show the most recent access time (the @samp{atime} in the inode) of any file in the directory, instead of the modification time. @item --time-style=@var{style} @opindex --time-style @cindex time style List timestamps in style @var{style}. This option has an effect only if the @option{--time} option is also specified. The @var{style} should be one of the following: @table @samp @item +@var{format} @vindex LC_TIME List timestamps using @var{format}, where @var{format} is interpreted like the format argument of @command{date} (@pxref{date invocation}). For example, @option{--time-style="+%Y-%m-%d %H:%M:%S"} causes @command{du} to list timestamps like @samp{2002-03-30 23:45:56}. As with @command{date}, @var{format}'s interpretation is affected by the @env{LC_TIME} locale category. @item full-iso List timestamps in full using @acronym{ISO} 8601 date, time, and time zone format with nanosecond precision, e.g., @samp{2002-03-30 23:45:56.477817180 -0700}. This style is equivalent to @samp{+%Y-%m-%d %H:%M:%S.%N %z}. @item long-iso List @acronym{ISO} 8601 date and time in minutes, e.g., @samp{2002-03-30 23:45}. These timestamps are shorter than @samp{full-iso} timestamps, and are usually good enough for everyday work. This style is equivalent to @samp{+%Y-%m-%d %H:%M}. @item iso List @acronym{ISO} 8601 dates for timestamps, e.g., @samp{2002-03-30}. This style is equivalent to @samp{+%Y-%m-%d}. @end table @vindex TIME_STYLE You can specify the default value of the @option{--time-style} option with the environment variable @env{TIME_STYLE}; if @env{TIME_STYLE} is not set the default style is @samp{long-iso}. For compatibility with @command{ls}, if @env{TIME_STYLE} begins with @samp{+} and contains a newline, the newline and any later characters are ignored; if @env{TIME_STYLE} begins with @samp{posix-} the @samp{posix-} is ignored; and if @env{TIME_STYLE} is @samp{locale} it is ignored. @item -x @itemx --one-file-system @opindex -x @opindex --one-file-system @cindex one file system, restricting @command{du} to Skip directories that are on different file systems from the one that the argument being processed is on. @item --exclude=@var{PATTERN} @opindex --exclude=@var{PATTERN} @cindex excluding files from @command{du} When recursing, skip subdirectories or files matching @var{PATTERN}. For example, @code{du --exclude='*.o'} excludes files whose names end in @samp{.o}. @item -X @var{FILE} @itemx --exclude-from=@var{FILE} @opindex -X @var{FILE} @opindex --exclude-from=@var{FILE} @cindex excluding files from @command{du} Like @option{--exclude}, except take the patterns to exclude from @var{FILE}, one per line. If @var{FILE} is @samp{-}, take the patterns from standard input. @end table @cindex NFS mounts from BSD to HP-UX On BSD systems, @command{du} reports sizes that are half the correct values for 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 are NFS-mounted from BSD systems. This is due to a flaw in HP-UX; it also affects the HP-UX @command{du} program. @exitstatus @node stat invocation @section @command{stat}: Report file or file system status @pindex stat @cindex file status @cindex file system status @command{stat} displays information about the specified file(s). Synopsis: @example stat [@var{option}]@dots{} [@var{file}]@dots{} @end example With no option, @command{stat} reports all information about the given files. But it also can be used to report the information of the file systems the given files are located on. If the files are links, @command{stat} can also give information about the files the links point to. @table @samp @item -L @itemx --dereference @opindex -L @opindex --dereference @cindex symbolic links, dereferencing in @command{stat} Change how @command{stat} treats symbolic links. With this option, @command{stat} acts on the file referenced by each symbolic link argument. Without it, @command{stat} acts on any symbolic link argument directly. @item -f @itemx --file-system @opindex -f @opindex --file-system @cindex file systems Report information about the file systems where the given files are located instead of information about the files themselves. @item -c @itemx --format=@var{format} @opindex -c @opindex --format=@var{format} @cindex output format Use @var{format} rather than the default format. @var{format} is automatically newline-terminated, so running a command like the following with two or more @var{file} operands produces a line of output for each operand: @example $ stat --format=%d:%i / /usr 2050:2 2057:2 @end example @itemx --printf=@var{format} @opindex --printf=@var{format} @cindex output format Use @var{format} rather than the default format. Like like @option{--format}, but interpret backslash escapes, and do not output a mandatory trailing newline. If you want a newline, include @samp{\n} in the @var{format}. Here's how you would use @option{--printf} to print the device and inode numbers of @file{/} and @file{/usr}: @example $ stat --printf='%d:%i\n' / /usr 2050:2 2057:2 @end example @item -t @itemx --terse @opindex -t @opindex --terse @cindex terse output Print the information in terse form, suitable for parsing by other programs. The valid format sequences for files are: @itemize @bullet @item %a - Access rights in octal @item %A - Access rights in human readable form @item %b - Number of blocks allocated (see @samp{%B}) @item %B - The size in bytes of each block reported by @samp{%b} @item %d - Device number in decimal @item %D - Device number in hex @item %f - Raw mode in hex @item %F - File type @item %g - Group ID of owner @item %G - Group name of owner @item %h - Number of hard links @item %i - Inode number @item %n - File name @item %N - Quoted file name with dereference if symbolic link @item %o - I/O block size @item %s - Total size, in bytes @item %t - Major device type in hex @item %T - Minor device type in hex @item %u - User ID of owner @item %U - User name of owner @item %x - Time of last access @item %X - Time of last access as seconds since Epoch @item %y - Time of last modification @item %Y - Time of last modification as seconds since Epoch @item %z - Time of last change @item %Z - Time of last change as seconds since Epoch @end itemize The valid format sequences for file systems are: @itemize @bullet @item %a - Free blocks available to non-superuser @item %b - Total data blocks in file system @item %c - Total file nodes in file system @item %d - Free file nodes in file system @item %f - Free blocks in file system @item %i - File System ID in hex @item %l - Maximum length of file names @item %n - File name @item %s - Block size (for faster transfers) @item %S - Fundamental block size (for block counts) @item %t - Type in hex @item %T - Type in human readable form @end itemize @vindex TZ Time stamps are listed according to the time zone rules specified by the @env{TZ} environment variable, or by the system default rules if @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone with @env{TZ}, libc, The GNU C Library}. @end table @exitstatus @node sync invocation @section @command{sync}: Synchronize data on disk with memory @pindex sync @cindex synchronize disk and memory @cindex superblock, writing @cindex inodes, written buffered @command{sync} writes any data buffered in memory out to disk. This can include (but is not limited to) modified superblocks, modified inodes, and delayed reads and writes. This must be implemented by the kernel; The @command{sync} program does nothing but exercise the @code{sync} system call. @cindex crashes and corruption The kernel keeps data in memory to avoid doing (relatively slow) disk reads and writes. This improves performance, but if the computer crashes, data may be lost or the file system corrupted as a result. The @command{sync} command ensures everything in memory is written to disk. Any arguments are ignored, except for a lone @option{--help} or @option{--version} (@pxref{Common options}). @exitstatus @node Printing text @chapter Printing text @cindex printing text, commands for @cindex commands for 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. @end menu @node echo invocation @section @command{echo}: Print a line of text @pindex echo @cindex displaying text @cindex printing text @cindex text, displaying @cindex arbitrary text, displaying @command{echo} writes each given @var{string} to standard output, with a space between each and a newline after the last one. Synopsis: @example echo [@var{option}]@dots{} [@var{string}]@dots{} @end example The program accepts the following options. Also see @ref{Common options}. Options must precede operands, and the normally-special argument @samp{--} has no special meaning and is treated like any other @var{string}. @table @samp @item -n @opindex -n Do not output the trailing newline. @item -e @opindex -e @cindex backslash escapes Enable interpretation of the following backslash-escaped characters in each @var{string}: @table @samp @item \a alert (bell) @item \b backspace @item \c suppress trailing newline @item \f form feed @item \n new line @item \r carriage return @item \t horizontal tab @item \v vertical tab @item \\ backslash @item \0@var{nnn} the eight-bit value that is the octal number @var{nnn} (zero to three octal digits) @item \@var{nnn} the eight-bit value that is the octal number @var{nnn} (one to three octal digits) @item \x@var{hh} the eight-bit value that is the hexadecimal number @var{hh} (one or two hexadecimal digits) @end table @item -E @opindex -E @cindex backslash escapes Disable interpretation of backslash escapes in each @var{string}. This is the default. If @option{-e} and @option{-E} are both specified, the last one given takes effect. @end table @vindex POSIXLY_CORRECT If the @env{POSIXLY_CORRECT} environment variable is set, then when @command{echo}'s first argument is not @option{-n} it outputs option-like arguments instead of treating them as options. For example, @code{echo -ne hello} outputs @samp{-ne hello} instead of plain @samp{hello}. @acronym{POSIX} does not require support for any options, and says that the behavior of @command{echo} is implementation-defined if any @var{string} contains a backslash or if the first argument is @option{-n}. Portable programs can use the @command{printf} command if they need to omit trailing newlines or output control characters or backslashes. @xref{printf invocation}. @exitstatus @node printf invocation @section @command{printf}: Format and print data @pindex printf @command{printf} does formatted printing of text. Synopsis: @example printf @var{format} [@var{argument}]@dots{} @end example @command{printf} prints the @var{format} string, interpreting @samp{%} directives and @samp{\} escapes to format numeric and string arguments in a way that is mostly similar to the C @samp{printf} function. The differences are as follows: @itemize @bullet @item The @var{format} argument is reused as necessary to convert all the given @var{argument}s. For example, the command @samp{printf %s a b} outputs @samp{ab}. @item Missing @var{argument}s are treated as null strings or as zeros, depending on whether the context expects a string or a number. For example, the command @samp{printf %sx%d} prints @samp{x0}. @item @kindex \c An additional escape, @samp{\c}, causes @command{printf} to produce no further output. For example, the command @samp{printf 'A%sC\cD%sF' B E} prints @samp{ABC}. @item The hexadecimal escape sequence @samp{\x@var{hh}} has at most two digits, as opposed to C where it can have an unlimited number of digits. For example, the command @samp{printf '\x07e'} prints two bytes, whereas the C statement @samp{printf ("\x07e")} prints just one. @item @kindex %b @command{printf} has an additional directive, @samp{%b}, which prints its argument string with @samp{\} escapes interpreted in the same way as in the @var{format} string, except that octal escapes are of the form @samp{\0@var{ooo}} where @var{ooo} is 0 to 3 octal digits. If a precision is also given, it limits the number of bytes printed from the converted string. @item Numeric arguments must be single C constants, possibly with leading @samp{+} or @samp{-}. For example, @samp{printf %.4d -3} outputs @samp{-0003}. @item @vindex POSIXLY_CORRECT If the leading character of a numeric argument is @samp{"} or @samp{'} then its value is the numeric value of the immediately following character. Any remaining characters are silently ignored if the @env{POSIXLY_CORRECT} environment variable is set; otherwise, a warning is printed. For example, @samp{printf "%d" "'a"} outputs @samp{97} on hosts that use the @acronym{ASCII} character set, since @samp{a} has the numeric value 97 in @acronym{ASCII}. @end itemize @vindex LC_NUMERIC A floating-point argument must use a period before any fractional digits, but is printed according to the @env{LC_NUMERIC} category of the current locale. For example, in a locale whose radix character is a comma, the command @samp{printf %g 3.14} outputs @samp{3,14} whereas the command @samp{printf %g 3,14} is an error. @kindex \@var{ooo} @kindex \x@var{hh} @command{printf} interprets @samp{\@var{ooo}} in @var{format} as an octal number (if @var{ooo} is 1 to 3 octal digits) specifying a character to print, and @samp{\x@var{hh}} as a hexadecimal number (if @var{hh} is 1 to 2 hex digits) specifying a character to print. @kindex \uhhhh @kindex \Uhhhhhhhh @cindex Unicode @cindex ISO/IEC 10646 @vindex LC_CTYPE @command{printf} interprets two character syntaxes introduced in @acronym{ISO} C 99: @samp{\u} for 16-bit Unicode (@acronym{ISO}/@acronym{IEC} 10646) characters, specified as four hexadecimal digits @var{hhhh}, and @samp{\U} for 32-bit Unicode characters, specified as eight hexadecimal digits @var{hhhhhhhh}. @command{printf} outputs the Unicode characters according to the @env{LC_CTYPE} locale. The processing of @samp{\u} and @samp{\U} requires a full-featured @code{iconv} facility. It is activated on systems with glibc 2.2 (or newer), or when @code{libiconv} is installed prior to this package. Otherwise @samp{\u} and @samp{\U} will print as-is. The only options are a lone @option{--help} or @option{--version}. @xref{Common options}. Options must precede operands. The Unicode character syntaxes are useful for writing strings in a locale independent way. For example, a string containing the Euro currency symbol @example $ /usr/local/bin/printf '\u20AC 14.95' @end example @noindent will be output correctly in all locales supporting the Euro symbol (@acronym{ISO}-8859-15, UTF-8, and others). Similarly, a Chinese string @example $ /usr/local/bin/printf '\u4e2d\u6587' @end example @noindent will be output correctly in all Chinese locales (GB2312, BIG5, UTF-8, etc). Note that in these examples, the full name of @command{printf} has been given, to distinguish it from the GNU @code{bash} built-in function @command{printf}. For larger strings, you don't need to look up the hexadecimal code values of each character one by one. @acronym{ASCII} characters mixed with \u escape sequences is also known as the JAVA source file encoding. You can 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 will output this text in a locale-independent way: @smallexample $ 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.sh @end smallexample @exitstatus @node yes invocation @section @command{yes}: Print a string until interrupted @pindex yes @cindex repeated output of a string @command{yes} prints the command line arguments, separated by spaces and followed by a newline, forever until it is killed. If no arguments are given, it prints @samp{y} followed by a newline forever until killed. Upon a write error, @command{yes} exits with status @samp{1}. The only options are a lone @option{--help} or @option{--version}. To output an argument that begins with @samp{-}, precede it with @option{--}, e.g., @samp{yes -- --help}. @xref{Common options}. @node Conditions @chapter Conditions @cindex conditions @cindex commands for exit status @cindex exit status commands This section describes commands that are primarily useful for their exit status, rather than their output. Thus, they are often used as the condition of shell @code{if} statements, or as the last command in a pipeline. @menu * false invocation:: Do nothing, unsuccessfully. * true invocation:: Do nothing, successfully. * test invocation:: Check file types and compare values. * expr invocation:: Evaluate expressions. @end menu @node false invocation @section @command{false}: Do nothing, unsuccessfully @pindex false @cindex do nothing, unsuccessfully @cindex failure exit status @cindex exit status of @command{false} @command{false} does nothing except return an exit status of 1, meaning @dfn{failure}. It can be used as a place holder in shell scripts where an unsuccessful command is needed. In most modern shells, @command{false} is a built-in command, so when you use @samp{false} in a script, you're probably using the built-in command, not the one documented here. @command{false} honors the @option{--help} and @option{--version} options. This version of @command{false} is implemented as a C program, and is thus more secure and faster than a shell script implementation, and may safely be used as a dummy shell for the purpose of disabling accounts. Note that @command{false} (unlike all other programs documented herein) exits unsuccessfully, even when invoked with @option{--help} or @option{--version}. Portable programs should not assume that the exit status of @command{false} is 1, as it is greater than 1 on some non-@acronym{GNU} hosts. @node true invocation @section @command{true}: Do nothing, successfully @pindex true @cindex do nothing, successfully @cindex no-op @cindex successful exit @cindex exit status of @command{true} @command{true} does nothing except return an exit status of 0, meaning @dfn{success}. It can be used as a place holder in shell scripts where a successful command is needed, although the shell built-in command @code{:} (colon) may do the same thing faster. In most modern shells, @command{true} is a built-in command, so when you use @samp{true} in a script, you're probably using the built-in command, not the one documented here. @command{true} honors the @option{--help} and @option{--version} options. Note, however, that it is possible to cause @command{true} to exit with nonzero status: with the @option{--help} or @option{--version} option, and with standard output already closed or redirected to a file that evokes an I/O error. For example, using a Bourne-compatible shell: @example $ ./true --version >&- ./true: write error: Bad file number $ ./true --version > /dev/full ./true: write error: No space left on device @end example This version of @command{true} is implemented as a C program, and is thus more secure and faster than a shell script implementation, and may safely be used as a dummy shell for the purpose of disabling accounts. @node test invocation @section @command{test}: Check file types and compare values @pindex test @cindex check file types @cindex compare values @cindex expression evaluation @command{test} returns a status of 0 (true) or 1 (false) depending on the evaluation of the conditional expression @var{expr}. Each part of the expression must be a separate argument. @command{test} has file status checks, string operators, and numeric comparison operators. @command{test} has an alternate form that uses opening and closing square brackets instead a leading @samp{test}. For example, instead of @samp{test -d /}, you can write @samp{[ -d / ]}. The square brackets must be separate arguments; for example, @samp{[-d /]} does not have the desired effect. Since @samp{test @var{expr}} and @samp{[ @var{expr} ]} have the same meaning, only the former form is discussed below. Synopses: @example test @var{expression} test [ @var{expression} ] [ ] [ @var{option} @end example @cindex conflicts with shell built-ins @cindex built-in shell commands, conflicts with Because most shells have a built-in @command{test} command, using an unadorned @command{test} in a script or interactively may get you different functionality than that described here. If @var{expression} is omitted, @command{test} returns false. If @var{expression} is a single argument, @command{test} returns false if the argument is null and true otherwise. The argument can be any string, including strings like @samp{-d}, @samp{-1}, @samp{--}, @samp{--help}, and @samp{--version} that most other programs would treat as options. To get help and version information, invoke the commands @samp{[ --help} and @samp{[ --version}, without the usual closing brackets. @xref{Common options}. @cindex exit status of @command{test} Exit status: @display 0 if the expression is true, 1 if the expression is false, 2 if an error occurred. @end display @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 -o @end menu @node File type tests @subsection File type tests @cindex file type tests These options test for particular types of files. (Everything's a file, but not all files are the same!) @table @samp @item -b @var{file} @opindex -b @cindex block special check True if @var{file} exists and is a block special device. @item -c @var{file} @opindex -c @cindex character special check True if @var{file} exists and is a character special device. @item -d @var{file} @opindex -d @cindex directory check True if @var{file} exists and is a directory. @item -f @var{file} @opindex -f @cindex regular file check True if @var{file} exists and is a regular file. @item -h @var{file} @itemx -L @var{file} @opindex -L @opindex -h @cindex symbolic link check True if @var{file} exists and is a symbolic link. Unlike all other file-related tests, this test does not dereference @var{file} if it is a symbolic link. @item -p @var{file} @opindex -p @cindex named pipe check True if @var{file} exists and is a named pipe. @item -S @var{file} @opindex -S @cindex socket check True if @var{file} exists and is a socket. @item -t @var{fd} @opindex -t @cindex terminal check True if @var{fd} is a file descriptor that is associated with a terminal. @end table @node Access permission tests @subsection Access permission tests @cindex access permission tests @cindex permission tests These options test for particular access permissions. @table @samp @item -g @var{file} @opindex -g @cindex set-group-ID check True if @var{file} exists and has its set-group-ID bit set. @item -k @var{file} @opindex -k @cindex sticky bit check True if @var{file} exists and has its @dfn{sticky} bit set. @item -r @var{file} @opindex -r @cindex readable file check True if @var{file} exists and read permission is granted. @item -u @var{file} @opindex -u @cindex set-user-ID check True if @var{file} exists and has its set-user-ID bit set. @item -w @var{file} @opindex -w @cindex writable file check True if @var{file} exists and write permission is granted. @item -x @var{file} @opindex -x @cindex executable file check True if @var{file} exists and execute permission is granted (or search permission, if it is a directory). @item -O @var{file} @opindex -O @cindex owned by effective user ID check True if @var{file} exists and is owned by the current effective user ID. @item -G @var{file} @opindex -G @cindex owned by effective group ID check True if @var{file} exists and is owned by the current effective group ID. @end table @node File characteristic tests @subsection File characteristic tests @cindex file characteristic tests These options test other file characteristics. @table @samp @item -e @var{file} @opindex -e @cindex existence-of-file check True if @var{file} exists. @item -s @var{file} @opindex -s @cindex nonempty file check True if @var{file} exists and has a size greater than zero. @item @var{file1} -nt @var{file2} @opindex -nt @cindex newer-than file check True if @var{file1} is newer (according to modification date) than @var{file2}, or if @var{file1} exists and @var{file2} does not. @item @var{file1} -ot @var{file2} @opindex -ot @cindex older-than file check True if @var{file1} is older (according to modification date) than @var{file2}, or if @var{file2} exists and @var{file1} does not. @item @var{file1} -ef @var{file2} @opindex -ef @cindex same file check @cindex hard link check True if @var{file1} and @var{file2} have the same device and inode numbers, i.e., if they are hard links to each other. @end table @node String tests @subsection String tests @cindex string tests These options test string characteristics. You may need to quote @var{string} arguments for the shell. For example: @example test -n "$V" @end example The quotes here prevent the wrong arguments from being passed to @command{test} if @samp{$V} is empty or contains special characters. @table @samp @item -z @var{string} @opindex -z @cindex zero-length string check True if the length of @var{string} is zero. @item -n @var{string} @itemx @var{string} @opindex -n @cindex nonzero-length string check True if the length of @var{string} is nonzero. @item @var{string1} = @var{string2} @opindex = @cindex equal string check True if the strings are equal. @item @var{string1} != @var{string2} @opindex != @cindex not-equal string check True if the strings are not equal. @end table @node Numeric tests @subsection Numeric tests @cindex numeric tests @cindex arithmetic tests Numeric relationals. The arguments must be entirely numeric (possibly negative), or the special expression @w{@code{-l @var{string}}}, which evaluates to the length of @var{string}. @table @samp @item @var{arg1} -eq @var{arg2} @itemx @var{arg1} -ne @var{arg2} @itemx @var{arg1} -lt @var{arg2} @itemx @var{arg1} -le @var{arg2} @itemx @var{arg1} -gt @var{arg2} @itemx @var{arg1} -ge @var{arg2} @opindex -eq @opindex -ne @opindex -lt @opindex -le @opindex -gt @opindex -ge These arithmetic binary operators return true if @var{arg1} is equal, not-equal, less-than, less-than-or-equal, greater-than, or greater-than-or-equal than @var{arg2}, respectively. @end table For example: @example test -1 -gt -2 && echo yes @result{} yes test -l abc -gt 1 && echo yes @result{} yes test 0x100 -eq 1 @error{} test: integer expression expected before -eq @end example @node Connectives for test @subsection Connectives for @command{test} @cindex logical connectives @cindex connectives, logical The usual logical connectives. @table @samp @item ! @var{expr} @opindex ! True if @var{expr} is false. @item @var{expr1} -a @var{expr2} @opindex -a @cindex logical and operator @cindex and operator True if both @var{expr1} and @var{expr2} are true. @item @var{expr1} -o @var{expr2} @opindex -o @cindex logical or operator @cindex or operator True if either @var{expr1} or @var{expr2} is true. @end table @node expr invocation @section @command{expr}: Evaluate expressions @pindex expr @cindex expression evaluation @cindex evaluation of expressions @command{expr} evaluates an expression and writes the result on standard output. Each token of the expression must be a separate argument. Operands are either integers or strings. Integers consist of one or more decimal digits, with an optional leading @samp{-}. @command{expr} converts anything appearing in an operand position to an integer or a string depending on the operation being applied to it. Strings are not quoted for @command{expr} itself, though you may need to quote them to protect characters with special meaning to the shell, e.g., spaces. However, regardless of whether it is quoted, a string operand should not be a parenthesis or any of @command{expr}'s operators like @code{+}, so you cannot safely pass an arbitrary string @code{$str} to expr merely by quoting it to the shell. One way to work around this is to use the @sc{gnu} extension @code{+}, (e.g., @code{+ "$str" = foo}); a more portable way is to use @code{@w{" $str"}} and to adjust the rest of the expression to take the leading space into account (e.g., @code{@w{" $str" = " foo"}}). You should not pass a negative integer or a string with leading @samp{-} as @command{expr}'s first argument, as it might be misinterpreted as an option; this can be avoided by parenthesization. Also, portable scripts should not use a string operand that happens to take the form of an integer; this can be worked around by inserting leading spaces as mentioned above. @cindex parentheses for grouping Operators may be given as infix symbols or prefix keywords. Parentheses may be used for grouping in the usual manner. You must quote parentheses and many operators to avoid the shell evaluating them, however. The only options are @option{--help} and @option{--version}. @xref{Common options}. Options must precede operands. @cindex exit status of @command{expr} Exit status: @display 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). @end display @menu * String expressions:: + : match substr index length * Numeric expressions:: + - * / % * Relations for expr:: | & < <= = == != >= > * Examples of expr:: Examples. @end menu @node String expressions @subsection String expressions @cindex string expressions @cindex expressions, string @command{expr} supports pattern matching and other string operators. These have lower precedence than both the numeric and relational operators (in the next sections). @table @samp @item @var{string} : @var{regex} @cindex pattern matching @cindex regular expression matching @cindex matching patterns Perform pattern matching. The arguments are converted to strings and the second is considered to be a (basic, a la GNU @code{grep}) regular expression, with a @code{^} implicitly prepended. The first argument is then matched against this regular expression. If the match succeeds and @var{regex} uses @samp{\(} and @samp{\)}, the @code{:} expression returns the part of @var{string} that matched the subexpression; otherwise, it returns the number of characters matched. If the match fails, the @code{:} operator returns the null string if @samp{\(} and @samp{\)} are used in @var{regex}, otherwise 0. @kindex \( @r{regexp operator} Only the first @samp{\( @dots{} \)} pair is relevant to the return value; additional pairs are meaningful only for grouping the regular expression operators. @kindex \+ @r{regexp operator} @kindex \? @r{regexp operator} @kindex \| @r{regexp operator} In the regular expression, @code{\+}, @code{\?}, and @code{\|} are operators which respectively match one or more, zero or one, or separate alternatives. SunOS and other @command{expr}'s treat these as regular characters. (@acronym{POSIX} allows either behavior.) @xref{Top, , Regular Expression Library, regex, Regex}, for details of regular expression syntax. Some examples are in @ref{Examples of expr}. @item match @var{string} @var{regex} @findex match An alternative way to do pattern matching. This is the same as @w{@samp{@var{string} : @var{regex}}}. @item substr @var{string} @var{position} @var{length} @findex substr Returns the substring of @var{string} beginning at @var{position} with length at most @var{length}. If either @var{position} or @var{length} is negative, zero, or non-numeric, returns the null string. @item index @var{string} @var{charset} @findex index Returns the first position in @var{string} where the first character in @var{charset} was found. If no character in @var{charset} is found in @var{string}, return 0. @item length @var{string} @findex length Returns the length of @var{string}. @item + @var{token} @kindex + Interpret @var{token} as a string, even if it is a keyword like @var{match} or an operator like @code{/}. This makes it possible to test @code{expr length + "$x"} or @code{expr + "$x" : '.*/\(.\)'} and have it do the right thing even if the value of @var{$x} happens to be (for example) @code{/} or @code{index}. This operator is a GNU extension. Portable shell scripts should use @code{@w{" $token"} : @w{' \(.*\)'}} instead of @code{+ "$token"}. @end table To make @command{expr} interpret keywords as strings, you must use the @code{quote} operator. @node Numeric expressions @subsection Numeric expressions @cindex numeric expressions @cindex expressions, numeric @command{expr} supports the usual numeric operators, in order of increasing precedence. The string operators (previous section) have lower precedence, the connectives (next section) have higher. @table @samp @item + - @kindex + @kindex - @cindex addition @cindex subtraction Addition and subtraction. Both arguments are converted to integers; an error occurs if this cannot be done. @item * / % @kindex * @kindex / @kindex % @cindex multiplication @cindex division @cindex remainder Multiplication, division, remainder. Both arguments are converted to integers; an error occurs if this cannot be done. @end table @node Relations for expr @subsection Relations for @command{expr} @cindex connectives, logical @cindex logical connectives @cindex relations, numeric or string @command{expr} supports the usual logical connectives and relations. These are higher precedence than either the string or numeric operators (previous sections). Here is the list, lowest-precedence operator first. @table @samp @item | @kindex | @cindex logical or operator @cindex or operator 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 its first argument is neither null nor zero. @item & @kindex & @cindex logical and operator @cindex and operator Return its first argument if neither argument is null or zero, otherwise 0. It does not evaluate its second argument if its first argument is null or zero. @item < <= = == != >= > @kindex < @kindex <= @kindex = @kindex == @kindex > @kindex >= @cindex comparison operators @vindex LC_COLLATE Compare the arguments and return 1 if the relation is true, 0 otherwise. @code{==} is a synonym for @code{=}. @command{expr} first tries to convert both arguments to integers and do a numeric comparison; if either conversion fails, it does a lexicographic comparison using the character collating sequence specified by the @env{LC_COLLATE} locale. @end table @node Examples of expr @subsection Examples of using @command{expr} @cindex examples of @command{expr} Here are a few examples, including quoting for shell metacharacters. To add 1 to the shell variable @code{foo}, in Bourne-compatible shells: @example foo=`expr $foo + 1` @end example To print the non-directory part of the file name stored in @code{$fname}, which need not contain a @code{/}: @example expr $fname : '.*/\(.*\)' '|' $fname @end example An example showing that @code{\+} is an operator: @example expr aaa : 'a\+' @result{} 3 @end example @example expr abc : 'a\(.\)c' @result{} b expr index abcdef cz @result{} 3 expr index index a @error{} expr: syntax error expr index quote index a @result{} 0 @end example @node Redirection @chapter Redirection @cindex redirection @cindex commands for redirection Unix shells commonly provide several forms of @dfn{redirection}---ways to change the input source or output destination of a command. But one useful redirection is performed by a separate command, not by the shell; it's described here. @menu * tee invocation:: Redirect output to multiple files. @end menu @node tee invocation @section @command{tee}: Redirect output to multiple files @pindex tee @cindex pipe fitting @cindex destinations, multiple output @cindex read from stdin and write to stdout and files The @command{tee} command copies standard input to standard output and also to any files given as arguments. This is useful when you want not only to send some data down a pipe, but also to save a copy. Synopsis: @example tee [@var{option}]@dots{} [@var{file}]@dots{} @end example If a file being written to does not already exist, it is created. If a file being written to already exists, the data it previously contained is overwritten unless the @option{-a} option is used. A @var{file} of @samp{-} causes @command{tee} to send another copy of input to standard output, but this is typically not that useful as the copies are interleaved. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @itemx --append @opindex -a @opindex --append Append standard input to the given files rather than overwriting them. @item -i @itemx --ignore-interrupts @opindex -i @opindex --ignore-interrupts Ignore interrupt signals. @end table @exitstatus @node File name manipulation @chapter File name manipulation @cindex file name manipulation @cindex manipulation of file names @cindex commands for 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 portability. @end menu @node basename invocation @section @command{basename}: Strip directory and suffix from a file name @pindex basename @cindex strip directory and suffix from file names @cindex directory, stripping from file names @cindex suffix, stripping from file names @cindex file names, stripping directory and suffix @cindex leading directory components, stripping @command{basename} removes any leading directory components from @var{name}. Synopsis: @example basename @var{name} [@var{suffix}] @end example If @var{suffix} is specified and is identical to the end of @var{name}, it is removed from @var{name} as well. Note that since trailing slashes are removed prior to suffix matching, @var{suffix} will do nothing if it contains slashes. @command{basename} prints the result on standard output. @c This test is used both here and in the section on dirname. @macro basenameAndDirname Together, @command{basename} and @command{dirname} are designed such that if @samp{ls "$name"} succeeds, then the command sequence @samp{cd "$(dirname "$name")"; ls "$(basename "$name")"} will, too. This works for everything except file names containing a trailing newline. @end macro @basenameAndDirname @acronym{POSIX} allows the implementation to define the results if @var{name} is empty or @samp{//}. In the former case, @acronym{GNU} @command{basename} returns the empty string. In the latter case, the result is @samp{//} on platforms where @var{//} is distinct from @var{/}, and @samp{/} on platforms where there is no difference. The only options are @option{--help} and @option{--version}. @xref{Common options}. Options must precede operands. @exitstatus Examples: @smallexample # Output "sort". basename /usr/bin/sort # Output "stdio". basename include/stdio.h .h @end smallexample @node dirname invocation @section @command{dirname}: Strip non-directory suffix from a file name @pindex dirname @cindex directory components, printing @cindex stripping non-directory suffix @cindex non-directory suffix, stripping @command{dirname} prints all but the final slash-delimited component of a string (presumably a file name). Synopsis: @example dirname @var{name} @end example If @var{name} is a single component, @command{dirname} prints @samp{.} (meaning the current directory). @basenameAndDirname @acronym{POSIX} allows the implementation to define the results if @var{name} is @samp{//}. With @acronym{GNU} @command{dirname}, the result is @samp{//} on platforms where @var{//} is distinct from @var{/}, and @samp{/} on platforms where there is no difference. The only options are @option{--help} and @option{--version}. @xref{Common options}. @exitstatus Examples: @smallexample # Output "/usr/bin". dirname /usr/bin/sort # Output ".". dirname stdio.h @end smallexample @node pathchk invocation @section @command{pathchk}: Check file name portability @pindex pathchk @cindex file names, checking validity and portability @cindex valid file names, checking for @cindex portable file names, checking for @command{pathchk} checks portability of file names. Synopsis: @example pathchk [@var{option}]@dots{} @var{name}@dots{} @end example For each @var{name}, @command{pathchk} prints a message if any of these conditions is true: @enumerate @item One of the existing directories in @var{name} does not have search (execute) permission, @item The length of @var{name} is larger than the maximum supported by the operating system. @item The length of one component of @var{name} is longer than its file system's maximum. @end enumerate A nonexistent @var{name} is not an error, so long a file with that name could be created under the above conditions. The program accepts the following options. Also see @ref{Common options}. Options must precede operands. @table @samp @item -p @opindex -p Instead of performing checks based on the underlying file system, print a message if any of these conditions is true: @enumerate @item A file name is empty. @item The length of a file name or one of its components exceeds the @acronym{POSIX} minimum limits for portability. @item A file name contains a character outside the portable file name character set, namely, the ASCII letters and digits, @samp{-}, @samp{.}, @samp{/}, and @samp{_}. @end enumerate @item -P @opindex -P Print a message if a file name is empty, or if it contains a component that begins with @samp{-}. @item --portability @opindex --portability Print a message if a file name is not portable to all @acronym{POSIX} hosts. This option is equivalent to @samp{-p -P}. @end table @cindex exit status of @command{pathchk} Exit status: @display 0 if all specified file names passed all checks, 1 otherwise. @end display @node Working context @chapter Working context @cindex working context @cindex commands for printing the working context This section describes commands that display or alter the context in which you are working: the current directory, the terminal settings, and so 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. @end menu @node pwd invocation @section @command{pwd}: Print working directory @pindex pwd @cindex print name of current directory @cindex current working directory, printing @cindex working directory, printing @cindex symbolic links and @command{pwd} @command{pwd} prints the fully resolved name of the current directory. That is, all components of the printed name will be actual directory names---none will be symbolic links. @cindex conflicts with shell built-ins @cindex built-in shell commands, conflicts with Because most shells have a built-in @command{pwd} command, using an unadorned @command{pwd} in a script or interactively may get you different functionality than that described here. The only options are a lone @option{--help} or @option{--version}. @xref{Common options}. @exitstatus @node stty invocation @section @command{stty}: Print or change terminal characteristics @pindex stty @cindex change or print terminal settings @cindex terminal settings @cindex line settings of terminal @command{stty} prints or changes terminal characteristics, such as baud rate. Synopses: @example stty [@var{option}] [@var{setting}]@dots{} stty [@var{option}] @end example If given no line settings, @command{stty} prints the baud rate, line discipline number (on systems that support it), and line settings that have been changed from the values set by @samp{stty sane}. By default, mode reading and setting are performed on the tty line connected to standard input, although this can be modified by the @option{--file} option. @command{stty} accepts many non-option arguments that change aspects of the terminal line operation, as described below. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @itemx --all @opindex -a @opindex --all Print all current settings in human-readable form. This option may not be used in combination with any line settings. @item -F @var{device} @itemx --file=@var{device} @opindex -F @opindex --file Set the line opened by the file name specified in @var{device} instead of the tty line connected to standard input. This option is necessary because opening a @acronym{POSIX} tty requires use of the @code{O_NONDELAY} flag to prevent a @acronym{POSIX} tty from blocking until the carrier detect line is high if the @code{clocal} flag is not set. Hence, it is not always possible to allow the shell to open the device in the traditional manner. @item -g @itemx --save @opindex -g @opindex --save @cindex machine-readable @command{stty} output Print all current settings in a form that can be used as an argument to another @command{stty} command to restore the current settings. This option may not be used in combination with any line settings. @end table Many settings can be turned off by preceding them with a @samp{-}. Such arguments are marked below with ``May be negated'' in their description. The descriptions themselves refer to the positive case, that is, when @emph{not} negated (unless stated otherwise, of course). Some settings are not available on all @acronym{POSIX} systems, since they use extensions. Such arguments are marked below with ``Non-@acronym{POSIX}'' in their description. On non-@acronym{POSIX} systems, those or other settings also may not be available, but it's not feasible to document all the variations: just try it and see. @exitstatus @menu * Control:: Control settings * Input:: Input settings * Output:: Output settings * Local:: Local settings * Combination:: Combination settings * Characters:: Special characters * Special:: Special settings @end menu @node Control @subsection Control settings @cindex control settings Control settings: @table @samp @item parenb @opindex parenb @cindex two-way parity Generate parity bit in output and expect parity bit in input. May be negated. @item parodd @opindex parodd @cindex odd parity @cindex even parity Set odd parity (even if negated). May be negated. @item cs5 @itemx cs6 @itemx cs7 @itemx cs8 @opindex cs@var{n} @cindex character size @cindex eight-bit characters Set character size to 5, 6, 7, or 8 bits. @item hup @itemx hupcl @opindex hup[cl] Send a hangup signal when the last process closes the tty. May be negated. @item cstopb @opindex cstopb @cindex stop bits Use two stop bits per character (one if negated). May be negated. @item cread @opindex cread Allow input to be received. May be negated. @item clocal @opindex clocal @cindex modem control Disable modem control signals. May be negated. @item crtscts @opindex crtscts @cindex hardware flow control @cindex flow control, hardware @cindex RTS/CTS flow control Enable RTS/CTS flow control. Non-@acronym{POSIX}. May be negated. @end table @node Input @subsection Input settings @cindex input settings @table @samp @item ignbrk @opindex ignbrk @cindex breaks, ignoring Ignore break characters. May be negated. @item brkint @opindex brkint @cindex breaks, cause interrupts Make breaks cause an interrupt signal. May be negated. @item ignpar @opindex ignpar @cindex parity, ignoring Ignore characters with parity errors. May be negated. @item parmrk @opindex parmrk @cindex parity errors, marking Mark parity errors (with a 255-0-character sequence). May be negated. @item inpck @opindex inpck Enable input parity checking. May be negated. @item istrip @opindex istrip @cindex eight-bit input Clear high (8th) bit of input characters. May be negated. @item inlcr @opindex inlcr @cindex newline, translating to return Translate newline to carriage return. May be negated. @item igncr @opindex igncr @cindex return, ignoring Ignore carriage return. May be negated. @item icrnl @opindex icrnl @cindex return, translating to newline Translate carriage return to newline. May be negated. @item iutf8 @opindex iutf8 @cindex input encoding, UTF-8 Assume input characters are UTF-8 encoded. May be negated. @item ixon @opindex ixon @kindex C-s/C-q flow control @cindex XON/XOFF flow control Enable XON/XOFF flow control (that is, @kbd{CTRL-S}/@kbd{CTRL-Q}). May be negated. @item ixoff @itemx tandem @opindex ixoff @opindex tandem @cindex software flow control @cindex flow control, software Enable sending of @code{stop} character when the system input buffer is almost full, and @code{start} character when it becomes almost empty again. May be negated. @item iuclc @opindex iuclc @cindex uppercase, translating to lowercase Translate uppercase characters to lowercase. Non-@acronym{POSIX}. May be negated. @item ixany @opindex ixany Allow any character to restart output (only the start character if negated). Non-@acronym{POSIX}. May be negated. @item imaxbel @opindex imaxbel @cindex beeping at input buffer full Enable beeping and not flushing input buffer if a character arrives when the input buffer is full. Non-@acronym{POSIX}. May be negated. @end table @node Output @subsection Output settings @cindex output settings These arguments specify output-related operations. @table @samp @item opost @opindex opost Postprocess output. May be negated. @item olcuc @opindex olcuc @cindex lowercase, translating to output Translate lowercase characters to uppercase. Non-@acronym{POSIX}. May be negated. @item ocrnl @opindex ocrnl @cindex return, translating to newline Translate carriage return to newline. Non-@acronym{POSIX}. May be negated. @item onlcr @opindex onlcr @cindex newline, translating to crlf Translate newline to carriage return-newline. Non-@acronym{POSIX}. May be negated. @item onocr @opindex onocr Do not print carriage returns in the first column. Non-@acronym{POSIX}. May be negated. @item onlret @opindex onlret Newline performs a carriage return. Non-@acronym{POSIX}. May be negated. @item ofill @opindex ofill @cindex pad instead of timing for delaying Use fill (padding) characters instead of timing for delays. Non-@acronym{POSIX}. May be negated. @item ofdel @opindex ofdel @cindex pad character Use delete characters for fill instead of null characters. Non-@acronym{POSIX}. May be negated. @item nl1 @itemx nl0 @opindex nl@var{n} Newline delay style. Non-@acronym{POSIX}. @item cr3 @itemx cr2 @itemx cr1 @itemx cr0 @opindex cr@var{n} Carriage return delay style. Non-@acronym{POSIX}. @item tab3 @itemx tab2 @itemx tab1 @itemx tab0 @opindex tab@var{n} Horizontal tab delay style. Non-@acronym{POSIX}. @item bs1 @itemx bs0 @opindex bs@var{n} Backspace delay style. Non-@acronym{POSIX}. @item vt1 @itemx vt0 @opindex vt@var{n} Vertical tab delay style. Non-@acronym{POSIX}. @item ff1 @itemx ff0 @opindex ff@var{n} Form feed delay style. Non-@acronym{POSIX}. @end table @node Local @subsection Local settings @cindex local settings @table @samp @item isig @opindex isig Enable @code{interrupt}, @code{quit}, and @code{suspend} special characters. May be negated. @item icanon @opindex icanon Enable @code{erase}, @code{kill}, @code{werase}, and @code{rprnt} special characters. May be negated. @item iexten @opindex iexten Enable non-@acronym{POSIX} special characters. May be negated. @item echo @opindex echo Echo input characters. May be negated. @item echoe @itemx crterase @opindex echoe @opindex crterase Echo @code{erase} characters as backspace-space-backspace. May be negated. @item echok @opindex echok @cindex newline echoing after @code{kill} Echo a newline after a @code{kill} character. May be negated. @item echonl @opindex echonl @cindex newline, echoing Echo newline even if not echoing other characters. May be negated. @item noflsh @opindex noflsh @cindex flushing, disabling Disable flushing after @code{interrupt} and @code{quit} special characters. May be negated. @item xcase @opindex xcase @cindex case translation Enable input and output of uppercase characters by preceding their lowercase equivalents with @samp{\}, when @code{icanon} is set. Non-@acronym{POSIX}. May be negated. @item tostop @opindex tostop @cindex background jobs, stopping at terminal write Stop background jobs that try to write to the terminal. Non-@acronym{POSIX}. May be negated. @item echoprt @itemx prterase @opindex echoprt @opindex prterase Echo erased characters backward, between @samp{\} and @samp{/}. Non-@acronym{POSIX}. May be negated. @item echoctl @itemx ctlecho @opindex echoctl @opindex ctlecho @cindex control characters, using @samp{^@var{c}} @cindex hat notation for control characters Echo control characters in hat notation (@samp{^@var{c}}) instead of literally. Non-@acronym{POSIX}. May be negated. @item echoke @itemx crtkill @opindex echoke @opindex crtkill Echo the @code{kill} special character by erasing each character on the line as indicated by the @code{echoprt} and @code{echoe} settings, instead of by the @code{echoctl} and @code{echok} settings. Non-@acronym{POSIX}. May be negated. @end table @node Combination @subsection Combination settings @cindex combination settings Combination settings: @table @samp @item evenp @opindex evenp @itemx parity @opindex parity Same as @code{parenb -parodd cs7}. May be negated. If negated, same as @code{-parenb cs8}. @item oddp @opindex oddp Same as @code{parenb parodd cs7}. May be negated. If negated, same as @code{-parenb cs8}. @item nl @opindex nl Same as @code{-icrnl -onlcr}. May be negated. If negated, same as @code{icrnl -inlcr -igncr onlcr -ocrnl -onlret}. @item ek @opindex ek Reset the @code{erase} and @code{kill} special characters to their default values. @item sane @opindex sane Same as: @c This is too long to write inline. @example cread -ignbrk brkint -inlcr -igncr icrnl -ixoff -iuclc -ixany imaxbel opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke @end example @noindent and also sets all special characters to their default values. @item cooked @opindex cooked Same as @code{brkint ignpar istrip icrnl ixon opost isig icanon}, plus sets the @code{eof} and @code{eol} characters to their default values if they are the same as the @code{min} and @code{time} characters. May be negated. If negated, same as @code{raw}. @item raw @opindex raw Same as: @example -ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany -imaxbel -opost -isig -icanon -xcase min 1 time 0 @end example @noindent May be negated. If negated, same as @code{cooked}. @item cbreak @opindex cbreak Same as @option{-icanon}. May be negated. If negated, same as @code{icanon}. @item pass8 @opindex pass8 @cindex eight-bit characters Same as @code{-parenb -istrip cs8}. May be negated. If negated, same as @code{parenb istrip cs7}. @item litout @opindex litout Same as @option{-parenb -istrip -opost cs8}. May be negated. If negated, same as @code{parenb istrip opost cs7}. @item decctlq @opindex decctlq Same as @option{-ixany}. Non-@acronym{POSIX}. May be negated. @item tabs @opindex tabs Same as @code{tab0}. Non-@acronym{POSIX}. May be negated. If negated, same as @code{tab3}. @item lcase @itemx LCASE @opindex lcase @opindex LCASE Same as @code{xcase iuclc olcuc}. Non-@acronym{POSIX}. May be negated. @item crt @opindex crt Same as @code{echoe echoctl echoke}. @item dec @opindex dec Same as @code{echoe echoctl echoke -ixany intr ^C erase ^? kill C-u}. @end table @node Characters @subsection Special characters @cindex special characters @cindex characters, special The special characters' default values vary from system to system. They are set with the syntax @samp{name value}, where the names are listed below and the value can be given either literally, in hat notation (@samp{^@var{c}}), or as an integer which may start with @samp{0x} to indicate hexadecimal, @samp{0} to indicate octal, or any other digit to indicate decimal. @cindex disabling special characters @kindex u@r{, and disabling special characters} For GNU stty, giving a value of @code{^-} or @code{undef} disables that special character. (This is incompatible with Ultrix @command{stty}, which uses a value of @samp{u} to disable a special character. GNU @command{stty} treats a value @samp{u} like any other, namely to set that special character to @key{U}.) @table @samp @item intr @opindex intr Send an interrupt signal. @item quit @opindex quit Send a quit signal. @item erase @opindex erase Erase the last character typed. @item kill @opindex kill Erase the current line. @item eof @opindex eof Send an end of file (terminate the input). @item eol @opindex eol End the line. @item eol2 @opindex eol2 Alternate character to end the line. Non-@acronym{POSIX}. @item swtch @opindex swtch Switch to a different shell layer. Non-@acronym{POSIX}. @item start @opindex start Restart the output after stopping it. @item stop @opindex stop Stop the output. @item susp @opindex susp Send a terminal stop signal. @item dsusp @opindex dsusp Send a terminal stop signal after flushing the input. Non-@acronym{POSIX}. @item rprnt @opindex rprnt Redraw the current line. Non-@acronym{POSIX}. @item werase @opindex werase Erase the last word typed. Non-@acronym{POSIX}. @item lnext @opindex lnext Enter the next character typed literally, even if it is a special character. Non-@acronym{POSIX}. @end table @node Special @subsection Special settings @cindex special settings @table @samp @item min @var{n} @opindex min Set the minimum number of characters that will satisfy a read until the time value has expired, when @option{-icanon} is set. @item time @var{n} @opindex time Set the number of tenths of a second before reads time out if the minimum number of characters have not been read, when @option{-icanon} is set. @item ispeed @var{n} @opindex ispeed Set the input speed to @var{n}. @item ospeed @var{n} @opindex ospeed Set the output speed to @var{n}. @item rows @var{n} @opindex rows Tell the tty kernel driver that the terminal has @var{n} rows. Non-@acronym{POSIX}. @item cols @var{n} @itemx columns @var{n} @opindex cols @opindex columns Tell the kernel that the terminal has @var{n} columns. Non-@acronym{POSIX}. @item size @opindex size @vindex LINES @vindex COLUMNS Print the number of rows and columns that the kernel thinks the terminal has. (Systems that don't support rows and columns in the kernel typically use the environment variables @env{LINES} and @env{COLUMNS} instead; however, GNU @command{stty} does not know anything about them.) Non-@acronym{POSIX}. @item line @var{n} @opindex line Use line discipline @var{n}. Non-@acronym{POSIX}. @item speed @opindex speed Print the terminal speed. @item @var{n} @cindex baud rate, setting @c FIXME: Is this still true that the baud rate can't be set @c higher than 38400? Set the input and output speeds to @var{n}. @var{n} can be one of: 0 50 75 110 134 134.5 150 200 300 600 1200 1800 2400 4800 9600 19200 38400 @code{exta} @code{extb}. @code{exta} is the same as 19200; @code{extb} is the same as 38400. 0 hangs up the line if @option{-clocal} is set. @end table @node printenv invocation @section @command{printenv}: Print all or some environment variables @pindex printenv @cindex printing all or some environment variables @cindex environment variables, printing @command{printenv} prints environment variable values. Synopsis: @example printenv [@var{option}] [@var{variable}]@dots{} @end example If no @var{variable}s are specified, @command{printenv} prints the value of every environment variable. Otherwise, it prints the value of each @var{variable} that is set, and nothing for those that are not set. The only options are a lone @option{--help} or @option{--version}. @xref{Common options}. @cindex exit status of @command{printenv} Exit status: @display 0 if all variables specified were found 1 if at least one specified variable was not found 2 if a write error occurred @end display @node tty invocation @section @command{tty}: Print file name of terminal on standard input @pindex tty @cindex print terminal file name @cindex terminal file name, printing @command{tty} prints the file name of the terminal connected to its standard input. It prints @samp{not a tty} if standard input is not a terminal. Synopsis: @example tty [@var{option}]@dots{} @end example The program accepts the following option. Also see @ref{Common options}. @table @samp @item -s @itemx --silent @itemx --quiet @opindex -s @opindex --silent @opindex --quiet Print nothing; only return an exit status. @end table @cindex exit status of @command{tty} Exit status: @display 0 if standard input is a terminal 1 if standard input is not a terminal 2 if given incorrect arguments 3 if a write error occurs @end display @node User information @chapter User information @cindex user information, commands for @cindex commands for printing 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. @end menu @node id invocation @section @command{id}: Print user identity @pindex id @cindex real user and group IDs, printing @cindex effective user and group IDs, printing @cindex printing real and effective user and group IDs @command{id} prints information about the given user, or the process running it if no user is specified. Synopsis: @example id [@var{option}]@dots{} [@var{username}] @end example By default, it prints the real user ID, real group ID, effective user ID if different from the real user ID, effective group ID if different from the real group ID, and supplemental group IDs. Each of these numeric values is preceded by an identifying string and followed by the corresponding user or group name in parentheses. The options cause @command{id} to print only part of the above information. Also see @ref{Common options}. @table @samp @item -g @itemx --group @opindex -g @opindex --group Print only the group ID. @item -G @itemx --groups @opindex -G @opindex --groups Print only the group ID and the supplementary groups. @item -n @itemx --name @opindex -n @opindex --name Print the user or group name instead of the ID number. Requires @option{-u}, @option{-g}, or @option{-G}. @item -r @itemx --real @opindex -r @opindex --real Print the real, instead of effective, user or group ID. Requires @option{-u}, @option{-g}, or @option{-G}. @item -u @itemx --user @opindex -u @opindex --user Print only the user ID. @end table @exitstatus @node logname invocation @section @command{logname}: Print current login name @pindex logname @cindex printing user's login name @cindex login name, printing @cindex user name, printing @flindex utmp @command{logname} prints the calling user's name, as found in a system-maintained file (often @file{/var/run/utmp} or @file{/etc/utmp}), and exits with a status of 0. If there is no entry for the calling process, @command{logname} prints an error message and exits with a status of 1. The only options are @option{--help} and @option{--version}. @xref{Common options}. @exitstatus @node whoami invocation @section @command{whoami}: Print effective user ID @pindex whoami @cindex effective user ID, printing @cindex printing the effective user ID @command{whoami} prints the user name associated with the current effective user ID. It is equivalent to the command @samp{id -un}. The only options are @option{--help} and @option{--version}. @xref{Common options}. @exitstatus @node groups invocation @section @command{groups}: Print group names a user is in @pindex groups @cindex printing groups a user is in @cindex supplementary groups, printing @command{groups} prints the names of the primary and any supplementary groups for each given @var{username}, or the current process if no names are given. If names are given, the name of each user is printed before the list of that user's groups. Synopsis: @example groups [@var{username}]@dots{} @end example The group lists are equivalent to the output of the command @samp{id -Gn}. The only options are @option{--help} and @option{--version}. @xref{Common options}. @exitstatus @node users invocation @section @command{users}: Print login names of users currently logged in @pindex users @cindex printing current usernames @cindex usernames, printing current @cindex login sessions, printing users with @command{users} prints on a single line a blank-separated list of user names of users currently logged in to the current host. Each user name corresponds to a login session, so if a user has more than one login session, that user's name will appear the same number of times in the output. Synopsis: @example users [@var{file}] @end example @flindex utmp @flindex wtmp With no @var{file} argument, @command{users} extracts its information from a system-maintained file (often @file{/var/run/utmp} or @file{/etc/utmp}). If a file argument is given, @command{users} uses that file instead. A common choice is @file{/var/log/wtmp}. The only options are @option{--help} and @option{--version}. @xref{Common options}. @exitstatus @node who invocation @section @command{who}: Print who is currently logged in @pindex who @cindex printing current user information @cindex information, about current users @command{who} prints information about users who are currently logged on. Synopsis: @example @command{who} [@var{option}] [@var{file}] [am i] @end example @cindex terminal lines, currently used @cindex login time @cindex remote hostname If given no non-option arguments, @command{who} prints the following information for each user currently logged on: login name, terminal line, login time, and remote hostname or X display. @flindex utmp @flindex wtmp If given one non-option argument, @command{who} uses that instead of a default system-maintained file (often @file{/var/run/utmp} or @file{/etc/utmp}) as the name of the file containing the record of users logged on. @file{/var/log/wtmp} is commonly given as an argument to @command{who} to look at who has previously logged on. @opindex am i @opindex who am i If given two non-option arguments, @command{who} prints only the entry for the user running it (determined from its standard input), preceded by the hostname. Traditionally, the two arguments given are @samp{am i}, as in @samp{who am i}. @vindex TZ Time stamps are listed according to the time zone rules specified by the @env{TZ} environment variable, or by the system default rules if @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone with @env{TZ}, libc, The GNU C Library}. The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @itemx --all @opindex -a @opindex --all Same as @samp{-b -d --login -p -r -t -T -u}. @item -b @itemx --boot @opindex -b @opindex --boot Print the date and time of last system boot. @item -d @itemx --dead @opindex -d @opindex --dead Print information corresponding to dead processes. @item -H @itemx --heading @opindex -H @opindex --heading Print column headings. @item -m @opindex -m Same as @samp{who am i}. @item -q @itemx --count @opindex -q @opindex --count Print only the login names and the number of users logged on. Overrides all other options. @item -s @opindex -s Ignored; for compatibility with other versions of @command{who}. @itemx -u @opindex -u @cindex idle time After the login time, print the number of hours and minutes that the user has been idle. @samp{.} means the user was active in the last minute. @samp{old} means the user has been idle for more than 24 hours. @item -l @itemx --login @opindex -l @opindex --login List only the entries that correspond to processes via which the system is waiting for a user to login. The user name is always @samp{LOGIN}. @itemx --lookup @opindex --lookup Attempt to canonicalize hostnames found in utmp through a DNS lookup. This is not the default because it can cause significant delays on systems with automatic dial-up internet access. @item -H @itemx --heading @opindex -H @opindex --heading Print a line of column headings. @item -w @itemx -T @itemx --mesg @itemx --message @itemx --writable @opindex -w @opindex -T @opindex --mesg @opindex --message @opindex --writable @cindex message status @pindex write@r{, allowed} After each login name print a character indicating the user's message status: @display @samp{+} allowing @code{write} messages @samp{-} disallowing @code{write} messages @samp{?} cannot find terminal device @end display @end table @exitstatus @node System context @chapter System context @cindex system context @cindex context, system @cindex commands for system context This section describes commands that print or change system-wide information. @menu * 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. @end menu @node date invocation @section @command{date}: Print or set system date and time @pindex date @cindex time, printing or setting @cindex printing the current time Synopses: @example date [@var{option}]@dots{} [+@var{format}] date [-u|--utc|--universal] @c this avoids a newline in the output [ MMDDhhmm[[CC]YY][.ss] ] @end example @vindex LC_TIME Invoking @command{date} with no @var{format} argument is equivalent to invoking it with a default format that depends on the @env{LC_TIME} locale category. In the default C locale, this format is @samp{'+%a %b %e %H:%M:%S %Z %Y'}, so the output looks like @samp{Thu Mar @ 3 13:47:51 PST 2005}. @vindex TZ Normally, @command{date} uses the time zone rules indicated by the @env{TZ} environment variable, or the system default rules if @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone with @env{TZ}, libc, The GNU C Library}. @findex strftime @r{and @command{date}} @cindex time formats @cindex formatting times If given an argument that starts with a @samp{+}, @command{date} prints the current date and time (or the date and time specified by the @option{--date} option, see below) in the format defined by that argument, which is similar to that of the @code{strftime} function. Except for conversion specifiers, which start with @samp{%}, characters in the format string are printed unchanged. The conversion specifiers are described below. @exitstatus @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. * Examples of date:: Examples. @end menu @node Time conversion specifiers @subsection Time conversion specifiers @cindex time conversion specifiers @cindex conversion specifiers, time @command{date} conversion specifiers related to times. @table @samp @item %H hour (@samp{00}@dots{}@samp{23}) @item %I hour (@samp{01}@dots{}@samp{12}) @item %k hour (@samp{ 0}@dots{}@samp{23}). This is a @acronym{GNU} extension. @item %l hour (@samp{ 1}@dots{}@samp{12}). This is a @acronym{GNU} extension. @item %M minute (@samp{00}@dots{}@samp{59}) @item %N nanoseconds (@samp{000000000}@dots{}@samp{999999999}). This is a @acronym{GNU} extension. @item %p locale's equivalent of either @samp{AM} or @samp{PM}; blank in many locales. Noon is treated as @samp{PM} and midnight as @samp{AM}. @item %P like @samp{%p}, except lower case. This is a @acronym{GNU} extension. @item %r locale's 12-hour clock time (e.g., @samp{11:11:04 PM}) @item %R 24-hour hour and minute. Same as @samp{%H:%M}. This is a @acronym{GNU} extension. @item %s @cindex epoch, seconds since @cindex seconds since the epoch @cindex beginning of time seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC. Leap seconds are not counted unless leap second support is available. @xref{%s-examples}, for examples. This is a @acronym{GNU} extension. @item %S second (@samp{00}@dots{}@samp{60}). This may be @samp{60} if leap seconds are supported. @item %T 24-hour hour, minute, and second. Same as @samp{%H:%M:%S}. @item %X locale's time representation (e.g., @samp{23:13:48}) @item %z @w{@acronym{RFC} 2822/@acronym{ISO} 8601} style numeric time zone (e.g., @samp{-0600} or @samp{+0530}), or nothing if no time zone is determinable. This value reflects the numeric time zone appropriate for the current time, using the time zone rules specified by the @env{TZ} environment variable. The time (and optionally, the time zone rules) can be overridden by the @option{--date} option. This is a @acronym{GNU} extension. @item %:z @w{@acronym{RFC} 3339/@acronym{ISO} 8601} style numeric time zone with @samp{:} (e.g., @samp{-06:00} or @samp{+05:30}), or nothing if no time zone is determinable. This is a @acronym{GNU} extension. @item %::z Numeric time zone to the nearest second with @samp{:} (e.g., @samp{-06:00:00} or @samp{+05:30:00}), or nothing if no time zone is determinable. This is a @acronym{GNU} extension. @item %:::z Numeric time zone with @samp{:} using the minimum necessary precision (e.g., @samp{-06}, @samp{+05:30}, or @samp{-04:56:02}), or nothing if no time zone is determinable. This is a @acronym{GNU} extension. @item %Z alphabetic time zone abbreviation (e.g., @samp{EDT}), or nothing if no time zone is determinable. See @samp{%z} for how it is determined. @end table @node Date conversion specifiers @subsection Date conversion specifiers @cindex date conversion specifiers @cindex conversion specifiers, date @command{date} conversion specifiers related to dates. @table @samp @item %a locale's abbreviated weekday name (e.g., @samp{Sun}) @item %A locale's full weekday name, variable length (e.g., @samp{Sunday}) @item %b locale's abbreviated month name (e.g., @samp{Jan}) @item %B locale's full month name, variable length (e.g., @samp{January}) @item %c locale's date and time (e.g., @samp{Thu Mar @ 3 23:05:25 2005}) @item %C century. This is like @samp{%Y}, except the last two digits are omitted. For example, it is @samp{20} if @samp{%Y} is @samp{2000}, and is @samp{-0} if @samp{%Y} is @samp{-001}. It is normally at least two characters, but it may be more. @item %d day of month (e.g., @samp{01}) @item %D date; same as @samp{%m/%d/%y} @item %e day of month, space padded; same as @samp{%_d} @item %F full date in @acronym{ISO} 8601 format; same as @samp{%Y-%m-%d}. This is a good choice for a date format, as it is standard and is easy to sort in the usual case where years are in the range 0000@dots{}9999. This is a @acronym{GNU} extension. @item %g year corresponding to the @acronym{ISO} week number, but without the century (range @samp{00} through @samp{99}). This has the same format and value as @samp{%y}, except that if the @acronym{ISO} week number (see @samp{%V}) belongs to the previous or next year, that year is used instead. This is a @acronym{GNU} extension. @item %G year corresponding to the @acronym{ISO} week number. This has the same format and value as @samp{%Y}, except that if the @acronym{ISO} week number (see @samp{%V}) belongs to the previous or next year, that year is used instead. It is normally useful only if @samp{%V} is also used; for example, the format @samp{%G-%m-%d} is probably a mistake, since it combines the ISO week number year with the conventional month and day. This is a @acronym{GNU} extension. @item %h same as @samp{%b} @item %j day of year (@samp{001}@dots{}@samp{366}) @item %m month (@samp{01}@dots{}@samp{12}) @item %u day of week (@samp{1}@dots{}@samp{7}) with @samp{1} corresponding to Monday @item %U week number of year, with Sunday as the first day of the week (@samp{00}@dots{}@samp{53}). Days in a new year preceding the first Sunday are in week zero. @item %V @acronym{ISO} week number, that is, the week number of year, with Monday as the first day of the week (@samp{01}@dots{}@samp{53}). If the week containing January 1 has four or more days in the new year, then it is considered week 1; otherwise, it is week 53 of the previous year, and the next week is week 1. (See the @acronym{ISO} 8601 standard.) @item %w day of week (@samp{0}@dots{}@samp{6}) with 0 corresponding to Sunday @item %W week number of year, with Monday as first day of week (@samp{00}@dots{}@samp{53}). Days in a new year preceding the first Monday are in week zero. @item %x locale's date representation (e.g., @samp{12/31/99}) @item %y last two digits of year (@samp{00}@dots{}@samp{99}) @item %Y year. This is normally at least four characters, but it may be more. Year @samp{0000} precedes year @samp{0001}, and year @samp{-001} precedes year @samp{0000}. @end table @node Literal conversion specifiers @subsection Literal conversion specifiers @cindex literal conversion specifiers @cindex conversion specifiers, literal @command{date} conversion specifiers that produce literal strings. @table @samp @item %% a literal % @item %n a newline @item %t a horizontal tab @end table @node Padding and other flags @subsection Padding and other flags @cindex numeric field padding @cindex padding of numeric fields @cindex fields, padding numeric Unless otherwise specified, @command{date} normally pads numeric fields with zeros, so that, for example, numeric months are always output as two digits. Seconds since the epoch are not padded, though, since there is no natural width for them. As a @acronym{GNU} extension, @command{date} recognizes any of the following optional flags after the @samp{%}: @table @samp @item - (hyphen) Do not pad the field; useful if the output is intended for human consumption. @item _ (underscore) Pad with spaces; useful if you need a fixed number of characters in the output, but zeros are too distracting. @item 0 (zero) Pad with zeros even if the conversion specifier would normally pad with spaces. @item ^ Use upper case characters if possible. @item # Use opposite case characters if possible. A field that is normally upper case becomes lower case, and vice versa. @end table @noindent Here are some examples of padding: @example date +%d/%m -d "Feb 1" @result{} 01/02 date +%-d/%-m -d "Feb 1" @result{} 1/2 date +%_d/%_m -d "Feb 1" @result{} 1/ 2 @end example As a @acronym{GNU} extension, you can specify the field width (after any flag, if present) as a decimal number. If the natural size of the output is of the field has less than the specified number of characters, the result is written right adjusted and padded to the given size. For example, @samp{%9B} prints the right adjusted month name in a field of width 9. An optional modifier can follow the optional flag and width specification. The modifiers are: @table @samp @item E Use the locale's alternate representation for date and time. This modifier applies to the @samp{%c}, @samp{%C}, @samp{%x}, @samp{%X}, @samp{%y} and @samp{%Y} conversion specifiers. In a Japanese locale, for example, @samp{%Ex} might yield a date format based on the Japanese Emperors' reigns. @item O Use the locale's alternate numeric symbols for numbers. This modifier applies only to numeric conversion specifiers. @end table If the format supports the modifier but no alternate representation is available, it is ignored. @node Setting the time @subsection Setting the time @cindex setting the time @cindex time setting @cindex appropriate privileges If given an argument that does not start with @samp{+}, @command{date} sets the system clock to the date and time specified by that argument (as described below). You must have appropriate privileges to set the system clock. The @option{--date} and @option{--set} options may not be used with such an argument. The @option{--universal} option may be used with such an argument to indicate that the specified date and time are relative to Coordinated Universal Time rather than to the local time zone. The argument must consist entirely of digits, which have the following meaning: @table @samp @item MM month @item DD day within month @item hh hour @item mm minute @item CC first two digits of year (optional) @item YY last two digits of year (optional) @item ss second (optional) @end table The @option{--set} option also sets the system clock; see the next section. @node Options for date @subsection Options for @command{date} @cindex @command{date} options @cindex options for @command{date} The program accepts the following options. Also see @ref{Common options}. @table @samp @item -d @var{datestr} @itemx --date=@var{datestr} @opindex -d @opindex --date @cindex parsing date strings @cindex date strings, parsing @cindex arbitrary date strings, parsing @opindex yesterday @opindex tomorrow @opindex next @var{day} @opindex last @var{day} Display the date and time specified in @var{datestr} instead of the current date and time. @var{datestr} can be in almost any common format. It can contain month names, time zones, @samp{am} and @samp{pm}, @samp{yesterday}, etc. For example, @option{--date="2004-02-27 14:19:13.489392193 +0530"} specifies the instant 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 minutes east of @acronym{UTC}. @xref{Date input formats}. @item -f @var{datefile} @itemx --file=@var{datefile} @opindex -f @opindex --file Parse each line in @var{datefile} as with @option{-d} and display the resulting date and time. If @var{datefile} is @samp{-}, use standard input. This is useful when you have many dates to process, because the system overhead of starting up the @command{date} executable many times can be considerable. @item -r @var{file} @itemx --reference=@var{file} @opindex -r @opindex --reference Display the date and time of the last modification of @var{file}, instead of the current date and time. @item -R @itemx --rfc-822 @itemx --rfc-2822 @opindex -R @opindex --rfc-822 @opindex --rfc-2822 Display the date and time using the format @samp{%a, %d %b %Y %H:%M:%S %z}, evaluated in the C locale so abbreviations are always in English. For example: @example Fri, 09 Sep 2005 13:51:39 -0700 @end example This format conforms to @uref{ftp://ftp.rfc-editor.org/in-notes/rfc2822.txt, Internet @acronym{RFCs} 2822} and @uref{ftp://ftp.rfc-editor.org/in-notes/rfc822.txt, 822}, the current and previous standards for Internet email. @item --rfc-3339=@var{timespec} @opindex --rfc-3339=@var{timespec} Display the date using a format specified by @uref{ftp://ftp.rfc-editor.org/in-notes/rfc3339.txt, Internet @acronym{RFC} 3339}. This is a subset of the @acronym{ISO} 8601 format, except that it also permits applications to use a space rather than a @samp{T} to separate dates from times. Unlike the other standard formats, @acronym{RFC} 3339 format is always suitable as input for the @option{--date} (@option{-d}) and @option{--file} (@option{-f}) options, regardless of the current locale. The argument @var{timespec} specifies how much of the time to include. It can be one of the following: @table @samp @item date Print just the full-date, e.g., @samp{2005-09-14}. This is equivalent to the format @samp{%Y-%m-%d}. @item seconds Print the full-date and full-time separated by a space, e.g., @samp{2005-09-14 00:56:06+05:30}. The output ends with a numeric time-offset; here the @samp{+05:30} means that local time is five hours and thirty minutes east of @acronym{UTC}. This is equivalent to the format @samp{%Y-%m-%d %H:%M:%S%:z}. @item ns Like @samp{seconds}, but also print nanoseconds, e.g., @samp{2005-09-14 00:56:06.998458565+05:30}. This is equivalent to the format @samp{%Y-%m-%d %H:%M:%S.%N%:z}. @end table @item -s @var{datestr} @itemx --set=@var{datestr} @opindex -s @opindex --set Set the date and time to @var{datestr}. See @option{-d} above. @item -u @itemx --utc @itemx --universal @opindex -u @opindex --utc @opindex --universal @cindex Coordinated Universal Time @cindex UTC @cindex Greenwich Mean Time @cindex GMT @vindex TZ Use Coordinated Universal Time (@acronym{UTC}) by operating as if the @env{TZ} environment variable were set to the string @samp{UTC0}. Coordinated Universal Time is often called ``Greenwich Mean Time'' (@sc{gmt}) for historical reasons. @end table @node Examples of date @subsection Examples of @command{date} @cindex examples of @command{date} Here are a few examples. Also see the documentation for the @option{-d} option in the previous section. @itemize @bullet @item To print the date of the day before yesterday: @example date --date='2 days ago' @end example @item To print the date of the day three months and one day hence: @example date --date='3 months 1 day' @end example @item To print the day of year of Christmas in the current year: @example date --date='25 Dec' +%j @end example @item To print the current full month name and the day of the month: @example date '+%B %d' @end example But this may not be what you want because for the first nine days of the month, the @samp{%d} expands to a zero-padded two-digit field, for example @samp{date -d 1may '+%B %d'} will print @samp{May 01}. @item To print a date without the leading zero for one-digit days of the month, you can use the (@acronym{GNU} extension) @samp{-} flag to suppress the padding altogether: @example date -d 1may '+%B %-d @end example @item To print the current date and time in the format required by many non-@acronym{GNU} versions of @command{date} when setting the system clock: @example date +%m%d%H%M%Y.%S @end example @item To set the system clock forward by two minutes: @example date --set='+2 minutes' @end example @item To print the date in @acronym{RFC} 2822 format, use @samp{date --rfc-2822}. Here is some example output: @example Fri, 09 Sep 2005 13:51:39 -0700 @end example @anchor{%s-examples} @item To convert a date string to the number of seconds since the epoch (which is 1970-01-01 00:00:00 UTC), use the @option{--date} option with the @samp{%s} format. That can be useful in sorting and/or graphing and/or comparing data by date. The following command outputs the number of the seconds since the epoch for the time two minutes after the epoch: @example date --date='1970-01-01 00:02:00 +0000' +%s 120 @end example If you do not specify time zone information in the date string, @command{date} uses your computer's idea of the time zone when interpreting the string. For example, if your computer's time zone is that of Cambridge, Massachusetts, which was then 5 hours (i.e., 18,000 seconds) behind UTC: @example # local time zone used date --date='1970-01-01 00:02:00' +%s 18120 @end example @item If you're sorting or graphing dated data, your raw date values may be represented as seconds since the epoch. But few people can look at the date @samp{946684800} and casually note ``Oh, that's the first second of the year 2000 in Greenwich, England.'' @example date --date='2000-01-01 UTC' +%s 946684800 @end example An alternative is to use the @option{--utc} (@option{-u}) option. Then you may omit @samp{UTC} from the date string. Although this produces the same result for @samp{%s} and many other format sequences, with a time zone offset different from zero, it would give a different result for zone-dependent formats like @samp{%z}. @example date -u --date=2000-01-01 +%s 946684800 @end example To convert such an unwieldy number of seconds back to a more readable form, use a command like this: @smallexample # local time zone used date -d '1970-01-01 UTC 946684800 seconds' +"%Y-%m-%d %T %z" 1999-12-31 19:00:00 -0500 @end smallexample Or if you do not mind depending on the @samp{@@} feature present since coreutils 5.3.0, you could shorten this to: @smallexample date -d @@946684800 +"%F %T %z" 1999-12-31 19:00:00 -0500 @end smallexample Often it is better to output UTC-relative date and time: @smallexample date -u -d '1970-01-01 946684800 seconds' +"%Y-%m-%d %T %z" 2000-01-01 00:00:00 +0000 @end smallexample @end itemize @node uname invocation @section @command{uname}: Print system information @pindex uname @cindex print system information @cindex system information, printing @command{uname} prints information about the machine and operating system it is run on. If no options are given, @command{uname} acts as if the @option{-s} option were given. Synopsis: @example uname [@var{option}]@dots{} @end example If multiple options or @option{-a} are given, the selected information is printed in this order: @example @var{kernel-name} @var{nodename} @var{kernel-release} @var{kernel-version} @var{machine} @var{processor} @var{hardware-platform} @var{operating-system} @end example The information may contain internal spaces, so such output cannot be parsed reliably. In the following example, @var{release} is @samp{2.2.18ss.e820-bda652a #4 SMP Tue Jun 5 11:24:08 PDT 2001}: @smallexample uname -a @result{} Linux dum 2.2.18 #4 SMP Tue Jun 5 11:24:08 PDT 2001 i686 unknown unknown GNU/Linux @end smallexample The program accepts the following options. Also see @ref{Common options}. @table @samp @item -a @itemx --all @opindex -a @opindex --all Print all of the below information, except omit the processor type and the hardware platform name if they are unknown. @item -i @itemx --hardware-platform @opindex -i @opindex --hardware-platform @cindex implementation, hardware @cindex hardware platform @cindex platform, hardware Print the hardware platform name (sometimes called the hardware implementation). Print @samp{unknown} if the kernel does not make this information easily available, as is the case with Linux kernels. @item -m @itemx --machine @opindex -m @opindex --machine @cindex machine type @cindex hardware class @cindex hardware type Print the machine hardware name (sometimes called the hardware class or hardware type). @item -n @itemx --nodename @opindex -n @opindex --nodename @cindex hostname @cindex node name @cindex network node name Print the network node hostname. @item -p @itemx --processor @opindex -p @opindex --processor @cindex host processor type Print the processor type (sometimes called the instruction set architecture or ISA). Print @samp{unknown} if the kernel does not make this information easily available, as is the case with Linux kernels. @item -o @itemx --operating-system @opindex -o @opindex --operating-system @cindex operating system name Print the name of the operating system. @item -r @itemx --kernel-release @opindex -r @opindex --kernel-release @cindex kernel release @cindex release of kernel Print the kernel release. @item -s @itemx --kernel-name @opindex -s @opindex --kernel-name @cindex kernel name @cindex name of kernel Print the kernel name. @acronym{POSIX} 1003.1-2001 (@pxref{Standards conformance}) calls this ``the implementation of the operating system'', because the @acronym{POSIX} specification itself has no notion of ``kernel''. The kernel name might be the same as the operating system name printed by the @option{-o} or @option{--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. @item -v @itemx --kernel-version @opindex -v @opindex --kernel-version @cindex kernel version @cindex version of kernel Print the kernel version. @end table @exitstatus @node hostname invocation @section @command{hostname}: Print or set system name @pindex hostname @cindex setting the hostname @cindex printing the hostname @cindex system name, printing @cindex appropriate privileges With no arguments, @command{hostname} prints the name of the current host system. With one argument, it sets the current host name to the specified string. You must have appropriate privileges to set the host name. Synopsis: @example hostname [@var{name}] @end example The only options are @option{--help} and @option{--version}. @xref{Common options}. @exitstatus @node hostid invocation @section @command{hostid}: Print numeric host identifier. @pindex hostid @cindex printing the host identifier @command{hostid} prints the numeric identifier of the current host in hexadecimal. This command accepts no arguments. The only options are @option{--help} and @option{--version}. @xref{Common options}. For example, here's what it prints on one system I use: @example $ hostid 1bac013d @end example On that system, the 32-bit quantity happens to be closely related to the system's Internet address, but that isn't always the case. @exitstatus @node Modified command invocation @chapter Modified command invocation @cindex modified command invocation @cindex invocation of commands, modified @cindex commands for invoking other commands This section describes commands that run other commands in some context different than the current one: a modified environment, as a different user, 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. @end menu @node chroot invocation @section @command{chroot}: Run a command with a different root directory @pindex chroot @cindex running a program in a specified root directory @cindex root directory, running a program in a specified @command{chroot} runs a command with a specified root directory. On many systems, only the super-user can do this. Synopses: @example chroot @var{newroot} [@var{command} [@var{args}]@dots{}] chroot @var{option} @end example Ordinarily, file names are looked up starting at the root of the directory structure, i.e., @file{/}. @command{chroot} changes the root to the directory @var{newroot} (which must exist) and then runs @var{command} with optional @var{args}. If @var{command} is not specified, the default is the value of the @env{SHELL} environment variable or @command{/bin/sh} if not set, invoked with the @option{-i} option. @var{command} must not be a special built-in utility (@pxref{Special built-in utilities}). The only options are @option{--help} and @option{--version}. @xref{Common options}. Options must precede operands. Here are a few tips to help avoid common problems in using chroot. To start with a simple example, make @var{command} refer to a statically linked binary. If you were to use a dynamically linked executable, then you'd have to arrange to have the shared libraries in the right place under your new root directory. For example, if you create a statically linked @command{ls} executable, and put it in @file{/tmp/empty}, you can run this command as root: @example $ chroot /tmp/empty /ls -Rl / @end example Then you'll see output like this: @example /: total 1023 -rwxr-xr-x 1 0 0 1041745 Aug 16 11:17 ls @end example If you want to use a dynamically linked executable, say @command{bash}, then first run @samp{ldd bash} to see what shared objects it needs. Then, in addition to copying the actual binary, also copy the listed files to the 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. @cindex exit status of @command{chroot} Exit status: @display 1 if @command{chroot} itself fails 126 if @var{command} is found but cannot be invoked 127 if @var{command} cannot be found the exit status of @var{command} otherwise @end display @node env invocation @section @command{env}: Run a command in a modified environment @pindex env @cindex environment, running a program in a modified @cindex modified environment, running a program in a @cindex running a program in a modified environment @command{env} runs a command with a modified environment. Synopses: @example env [@var{option}]@dots{} [@var{name}=@var{value}]@dots{} @c [@var{command} [@var{args}]@dots{}] env @end example Operands of the form @samp{@var{variable}=@var{value}} set the environment variable @var{variable} to value @var{value}. @var{value} may be empty (@samp{@var{variable}=}). Setting a variable to an empty value is different from unsetting it. These operands are evaluated left-to-right, so if two operands mention the same variable the earlier is ignored. Environment variable names can be empty, and can contain any characters other than @samp{=} and the null character (@acronym{ASCII} @sc{nul}). However, it is wise to limit yourself to names that consist solely of underscores, digits, and @acronym{ASCII} letters, and that begin with a non-digit, as applications like the shell do not work well with other names. @vindex PATH The first operand that does not contain the character @samp{=} specifies the program to invoke; it is searched for according to the @env{PATH} environment variable. Any remaining arguments are passed as arguments to that program. The program should not be a special built-in utility (@pxref{Special built-in utilities}). @cindex environment, printing If no command name is specified following the environment specifications, the resulting environment is printed. This is like specifying the @command{printenv} program. The program accepts the following options. Also see @ref{Common options}. Options must precede operands. @table @samp @item -u @var{name} @itemx --unset=@var{name} @opindex -u @opindex --unset Remove variable @var{name} from the environment, if it was in the environment. @item - @itemx -i @itemx --ignore-environment @opindex - @opindex -i @opindex --ignore-environment Start with an empty environment, ignoring the inherited environment. @end table @cindex exit status of @command{env} Exit status: @display 0 if no @var{command} is specified and the environment is output 1 if @command{env} itself fails 126 if @var{command} is found but cannot be invoked 127 if @var{command} cannot be found the exit status of @var{command} otherwise @end display @node nice invocation @section @command{nice}: Run a command with modified niceness @pindex nice @cindex niceness @cindex scheduling, affecting @cindex appropriate privileges @command{nice} prints or modifies a process's @dfn{niceness}, a parameter that affects whether the process is scheduled favorably. Synopsis: @example nice [@var{option}]@dots{} [@var{command} [@var{arg}]@dots{}] @end example If no arguments are given, @command{nice} prints the current niceness. Otherwise, @command{nice} runs the given @var{command} with its niceness adjusted. By default, its niceness is incremented by 10. Nicenesses range at least from @minus{}20 (resulting in the most favorable scheduling) through 19 (the least favorable). Some systems may have a wider range of nicenesses; conversely, other systems may enforce more restrictive limits. An attempt to set the niceness outside the supported range is treated as an attempt to use the minimum or maximum supported value. A niceness should not be confused with a scheduling priority, which lets applications determine the order in which threads are scheduled to run. Unlike a priority, a niceness is merely advice to the scheduler, which the scheduler is free to ignore. Also, as a point of terminology, @acronym{POSIX} defines the behavior of @command{nice} in terms of a @dfn{nice value}, which is the nonnegative difference between a niceness and the minimum niceness. Though @command{nice} conforms to @acronym{POSIX}, its documentation and diagnostics use the term ``niceness'' for compatibility with historical practice. @var{command} must not be a special built-in utility (@pxref{Special built-in utilities}). @cindex conflicts with shell built-ins @cindex built-in shell commands, conflicts with Because many shells have a built-in @command{nice} command, using an unadorned @command{nice} in a script or interactively may get you different functionality than that described here. The program accepts the following option. Also see @ref{Common options}. Options must precede operands. @table @samp @item -n @var{adjustment} @itemx --adjustment=@var{adjustment} @opindex -n @opindex --adjustment Add @var{adjustment} instead of 10 to the command's niceness. If @var{adjustment} is negative and you lack appropriate privileges, @command{nice} issues a warning but otherwise acts as if you specified a zero adjustment. For compatibility @command{nice} also supports an obsolete option syntax @option{-@var{adjustment}}. New scripts should use @option{-n @var{adjustment}} instead. @end table @cindex exit status of @command{nice} Exit status: @display 0 if no @var{command} is specified and the niceness is output 1 if @command{nice} itself fails 126 if @var{command} is found but cannot be invoked 127 if @var{command} cannot be found the exit status of @var{command} otherwise @end display It is sometimes useful to run a non-interactive program with reduced niceness. @example $ nice factor 4611686018427387903 @end example Since @command{nice} prints the current niceness, you can invoke it through itself to demonstrate how it works. The default behavior is to increase the niceness by @samp{10}: @example $ nice 0 $ nice nice 10 $ nice -n 10 nice 10 @end example The @var{adjustment} is relative to the current niceness. In the next example, the first @command{nice} invocation runs the second one with niceness 10, and it in turn runs the final one with a niceness that is 3 more: @example $ nice nice -n 3 nice 13 @end example Specifying a niceness larger than the supported range is the same as specifying the maximum supported value: @example $ nice -n 10000000000 nice 19 @end example Only a privileged user may run a process with lower niceness: @example $ nice -n -1 nice nice: cannot set niceness: Permission denied 0 $ sudo nice -n -1 nice -1 @end example @node nohup invocation @section @command{nohup}: Run a command immune to hangups @pindex nohup @cindex hangups, immunity to @cindex immunity to hangups @cindex logging out and continuing to run @flindex nohup.out @command{nohup} runs the given @var{command} with hangup signals ignored, so that the command can continue running in the background after you log out. Synopsis: @example nohup @var{command} [@var{arg}]@dots{} @end example If standard input is a terminal, it is redirected from @file{/dev/null} so that terminal sessions do not mistakenly consider the terminal to be used by the command. This is a @acronym{GNU} extension; programs intended to be portable to non-@acronym{GNU} hosts should use @samp{nohup @var{command} [@var{arg}]@dots{} 0.000003}} will end up being true. To work around that in the above example, use a slightly larger number as the @var{last} value: @example $ seq -s ' ' 0 0.000001 0.0000031 0.000000 0.000001 0.000002 0.000003 @end example In general, when using an @var{increment} with a fractional part, where (@var{last} - @var{first}) / @var{increment} is (mathematically) a whole number, specify a slightly larger (or smaller, if @var{increment} is negative) value for @var{last} to ensure that @var{last} is the final value printed by seq. @exitstatus @node File permissions @chapter File permissions @include perm.texi @include getdate.texi @c What's GNU? @c Arnold Robbins @node Opening the software toolbox @chapter Opening the Software Toolbox An earlier version of this chapter appeared in @uref{http://www.linuxjournal.com/article.php?sid=2762, the @cite{What's GNU?} column of @cite{Linux Journal}, 2 (June, 1994)}. It was written by Arnold Robbins. @menu * Toolbox introduction:: Toolbox introduction * I/O redirection:: I/O redirection * The who command:: The @command{who} command * The cut command:: The @command{cut} command * The sort command:: The @command{sort} command * The uniq command:: The @command{uniq} command * Putting the tools together:: Putting the tools together @end menu @node Toolbox introduction @unnumberedsec Toolbox Introduction This month's column is only peripherally related to the GNU Project, in that it describes a number of the GNU tools on your GNU/Linux system and how they might be used. What it's really about is the ``Software Tools'' philosophy of program development and usage. The software tools philosophy was an important and integral concept in the initial design and development of Unix (of which Linux and GNU are essentially clones). Unfortunately, in the modern day press of Internetworking and flashy GUIs, it seems to have fallen by the wayside. This is a shame, since it provides a powerful mental model for 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 several knife blades, a screwdriver, tweezers, toothpick, nail file, corkscrew, and perhaps a number of other things on it. For the everyday, small miscellaneous jobs where you need a simple, general purpose tool, it's just the thing. On the other hand, an experienced carpenter doesn't build a house using a Swiss Army knife. Instead, he has a toolbox chock full of specialized 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 catch him hammering nails with the handle of his screwdriver. The Unix developers at Bell Labs were all professional programmers and trained computer scientists. They had found that while a one-size-fits-all program might appeal to a user because there's only one program to use, in practice such programs are @enumerate a @item difficult to write, @item difficult to maintain and debug, and @item difficult to extend to meet new situations. @end enumerate Instead, they felt that programs should be specialized tools. In short, each program ``should do one thing well.'' No more and no less. Such programs are simpler to design, write, and get right---they only do one thing. Furthermore, they found that with the right machinery for hooking programs together, that the whole was greater than the sum of the parts. By combining several special purpose programs, you could accomplish a specific task that none of the programs was designed for, and accomplish it much more quickly and easily than if you had to write a special purpose program. We will see some (classic) examples of this further on in the column. (An important additional point was that, if necessary, take a detour and build any software tools you may need first, if you don't already have something appropriate in the toolbox.) @node I/O redirection @unnumberedsec I/O Redirection Hopefully, you are familiar with the basics of I/O redirection in the shell, in particular the concepts of ``standard input,'' ``standard output,'' and ``standard error''. Briefly, ``standard input'' is a data source, where data comes from. A program should not need to either know or care if the data source is a disk file, a keyboard, a magnetic tape, or even a punched card reader. Similarly, ``standard output'' is a data sink, where data goes to. The program should neither know nor care where this might be. Programs that only read their standard input, do something to the data, and then send it on, are called @dfn{filters}, by analogy to filters in a water pipeline. With the Unix shell, it's very easy to set up data pipelines: @smallexample program_to_create_data | filter1 | ... | filterN > final.pretty.data @end smallexample We start out by creating the raw data; each filter applies some successive transformation to the data, until by the time it comes out of the pipeline, it is in the desired form. This is fine and good for standard input and standard output. Where does the standard error come in to play? Well, think about @command{filter1} in the pipeline above. What happens if it encounters an error in the data it sees? If it writes an error message to standard output, it will just disappear down the pipeline into @command{filter2}'s input, and the user will probably never see it. So programs need a place where they can send error messages so that the user will notice them. This is standard error, and it is usually connected to your console or window, even if you have redirected standard output of your program away from your screen. For filter programs to work together, the format of the data has to be agreed upon. The most straightforward and easiest format to use is simply lines of text. Unix data files are generally just streams of bytes, with lines delimited by the @acronym{ASCII} @sc{lf} (Line Feed) character, conventionally called a ``newline'' in the Unix literature. (This is @code{'\n'} if you're a C programmer.) This is the format used by all the traditional filtering programs. (Many earlier operating systems had elaborate facilities and special purpose programs for managing binary data. Unix has always shied away from such things, under the philosophy that it's easiest to simply be able to view and edit your data 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. In the following discussion, we will only present those command line options that interest us. As you should always do, double check your system documentation for the full story. @node The who command @unnumberedsec The @command{who} Command The first program is the @command{who} command. By itself, it generates a list of the users who are currently logged in. Although I'm writing this on a single-user system, we'll pretend that several people are logged in: @example $ who @print{} arnold console Jan 22 19:57 @print{} miriam ttyp0 Jan 23 14:19(:0.0) @print{} bill ttyp1 Jan 21 09:32(:0.0) @print{} arnold ttyp2 Jan 23 20:48(:0.0) @end example Here, the @samp{$} is the usual shell prompt, at which I typed @samp{who}. There are three people logged in, and I am logged in twice. On traditional Unix systems, user names are never more than eight characters long. This little bit of trivia will be useful later. The output of @command{who} is nice, but the data is not all that exciting. @node The cut command @unnumberedsec The @command{cut} Command The next program we'll look at is the @command{cut} command. This program cuts out columns or fields of input data. For example, we can tell it to print just the login name and full name from the @file{/etc/passwd} file. The @file{/etc/passwd} file has seven fields, separated by colons: @example arnold:xyzzy:2076:10:Arnold D. Robbins:/home/arnold:/bin/bash @end example To get the first and fifth fields, we would use @command{cut} like this: @example $ cut -d: -f1,5 /etc/passwd @print{} root:Operator @dots{} @print{} arnold:Arnold D. Robbins @print{} miriam:Miriam A. Robbins @dots{} @end example With the @option{-c} option, @command{cut} will cut out specific characters (i.e., columns) in the input lines. This is useful for input data that has fixed width fields, and does not have a field separator. For example, list the Monday dates for the current month: @c Is using cal ok? Looked at gcal, but I don't like it. @example $ cal | cut -c 3-5 @print{}Mo @print{} @print{} 6 @print{} 13 @print{} 20 @print{} 27 @end example @node The sort command @unnumberedsec The @command{sort} Command Next we'll look at the @command{sort} command. This is one of the most powerful commands on a Unix-style system; one that you will often find yourself using when setting up fancy data plumbing. The @command{sort} command reads and sorts each file named on the command line. 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 character collating sequence or based on user-supplied ordering criteria. @node The uniq command @unnumberedsec The @command{uniq} Command Finally (at least for now), we'll look at the @command{uniq} program. When sorting data, you will often end up with duplicate lines, lines that are identical. Usually, all you need is one instance of each line. This is where @command{uniq} comes in. The @command{uniq} program reads its standard input. It prints only one copy of each repeated line. It does have several options. Later on, we'll use the @option{-c} option, which prints each unique line, preceded by a count of the number of times that line occurred in the input. @node Putting the tools together @unnumberedsec Putting the Tools Together Now, let's suppose this is a large ISP server system with dozens of users logged in. The management wants the system administrator to write a program that will generate a sorted list of logged in users. Furthermore, even if a user is logged in multiple times, his or her name should only show up in the output once. The administrator could sit down with the system documentation and write a C program that did this. It would take perhaps a couple of hundred lines of code and about two hours to write it, test it, and debug it. However, knowing the software toolbox, the administrator can instead start out by generating just a list of logged on users: @example $ who | cut -c1-8 @print{} arnold @print{} miriam @print{} bill @print{} arnold @end example Next, sort the list: @example $ who | cut -c1-8 | sort @print{} arnold @print{} arnold @print{} bill @print{} miriam @end example Finally, run the sorted list through @command{uniq}, to weed out duplicates: @example $ who | cut -c1-8 | sort | uniq @print{} arnold @print{} bill @print{} miriam @end example The @command{sort} command actually has a @option{-u} option that does what @command{uniq} does. However, @command{uniq} has other uses for which one cannot substitute @samp{sort -u}. The administrator puts this pipeline into a shell script, and makes it available for all the users on the system (@samp{#} is the system administrator, or @code{root}, prompt): @example # cat > /usr/local/bin/listusers who | cut -c1-8 | sort | uniq ^D # chmod +x /usr/local/bin/listusers @end example There are four major points to note here. First, with just four programs, on one command line, the administrator was able to save about two hours worth of work. Furthermore, the shell pipeline is just about as efficient as the C program would be, and it is much more efficient in terms of programmer time. People time is much more expensive than computer time, and in our modern ``there's never enough time to do everything'' society, saving two hours of programmer time is no mean feat. Second, it is also important to emphasize that with the @emph{combination} of the tools, it is possible to do a special purpose job never imagined by the authors of the individual programs. Third, it is also valuable to build up your pipeline in stages, as we did here. This allows you to view the data at each stage in the pipeline, which helps you acquire the confidence that you are indeed using these tools correctly. Finally, by bundling the pipeline in a shell script, other users can use your command, without having to remember the fancy plumbing you set up for them. In terms of how you run them, shell scripts and compiled programs are indistinguishable. After the previous warm-up exercise, we'll look at two additional, more complicated pipelines. For them, we need to introduce two more tools. The first is the @command{tr} command, which stands for ``transliterate.'' The @command{tr} command works on a character-by-character basis, changing characters. Normally it is used for things like mapping upper case to lower case: @example $ echo ThIs ExAmPlE HaS MIXED case! | tr '[:upper:]' '[:lower:]' @print{} this example has mixed case! @end example There are several options of interest: @table @code @item -c work on the complement of the listed characters, i.e., operations apply to characters not in the given set @item -d delete characters in the first set from the output @item -s squeeze repeated characters in the output into just one character. @end table We will be using all three options in a moment. The other command we'll look at is @command{comm}. The @command{comm} command takes two sorted input files as input data, and prints out the files' lines in three columns. The output columns are the data lines unique to the first file, the data lines unique to the second file, and the data lines that are common to both. The @option{-1}, @option{-2}, and @option{-3} command line options @emph{omit} the respective columns. (This is non-intuitive and takes a little getting used to.) For example: @example $ cat f1 @print{} 11111 @print{} 22222 @print{} 33333 @print{} 44444 $ cat f2 @print{} 00000 @print{} 22222 @print{} 33333 @print{} 55555 $ comm f1 f2 @print{} 00000 @print{} 11111 @print{} 22222 @print{} 33333 @print{} 44444 @print{} 55555 @end example The file name @file{-} tells @command{comm} to read standard input instead of a regular file. Now we're ready to build a fancy pipeline. The first application is a word frequency counter. This helps an author determine if he or she is over-using certain words. The first step is to change the case of all the letters in our input file to one case. ``The'' and ``the'' are the same word when doing counting. @example $ tr '[:upper:]' '[:lower:]' < whats.gnu | ... @end example The next step is to get rid of punctuation. Quoted words and unquoted words should be treated identically; it's easiest to just get the punctuation out of the way. @smallexample $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | ... @end smallexample The second @command{tr} command operates on the complement of the listed characters, which are all the letters, the digits, the underscore, and the blank. The @samp{\n} represents the newline character; it has to be left alone. (The @acronym{ASCII} tab character should also be included for good measure in a production script.) At this point, we have data consisting of words separated by blank space. The words only contain alphanumeric characters (and the underscore). The next step is break the data apart so that we have one word per line. This makes the counting operation much easier, as we will see shortly. @smallexample $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | > tr -s ' ' '\n' | ... @end smallexample This command turns blanks into newlines. The @option{-s} option squeezes multiple newline characters in the output into just one. This helps us avoid blank lines. (The @samp{>} is the shell's ``secondary prompt.'' This is what the shell prints when it notices you haven't finished typing in all 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: @smallexample $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | > tr -s ' ' '\n' | sort | uniq -c | ... @end smallexample At this point, the data might look something like this: @example 60 a 2 able 6 about 1 above 2 accomplish 1 acquire 1 actually 2 additional @end example The output is sorted by word, not by count! What we want is the most frequently used words first. Fortunately, this is easy to accomplish, with the help of two more @command{sort} options: @table @code @item -n do a numeric sort, not a textual one @item -r reverse the order of the sort @end table The final pipeline looks like this: @smallexample $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | > tr -s ' ' '\n' | sort | uniq -c | sort -n -r @print{} 156 the @print{} 60 a @print{} 58 to @print{} 51 of @print{} 51 and @dots{} @end smallexample Whew! That's a lot to digest. Yet, the same principles apply. With six commands, on two lines (really one long one split for convenience), we've created a program that does something interesting and useful, in much less time than we could have written a C program to do the same thing. A minor modification to the above pipeline can give us a simple spelling checker! To determine if you've spelled a word correctly, all you have to do is look it up in a dictionary. If it is not there, then chances are that your spelling is incorrect. So, we need a dictionary. The conventional location for a dictionary is @file{/usr/dict/words}. On my GNU/Linux system,@footnote{Redhat Linux 6.1, for the November 2000 revision of this article.} this is a is a sorted, 45,402 word dictionary. Now, how to compare our file with the dictionary? As before, we generate a sorted list of words, one per line: @smallexample $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | > tr -s ' ' '\n' | sort -u | ... @end smallexample Now, all we need is a list of words that are @emph{not} in the dictionary. Here is where the @command{comm} command comes in. @smallexample $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | > tr -s ' ' '\n' | sort -u | > comm -23 - /usr/dict/words @end smallexample The @option{-2} and @option{-3} options eliminate lines that are only in the dictionary (the second file), and lines that are in both files. Lines only in the first file (standard input, our stream of words), are words that are not in the dictionary. These are likely candidates for spelling errors. This pipeline was the first cut at a production spelling checker on Unix. There are some other tools that deserve brief mention. @table @command @item grep search files for text that matches a regular expression @item wc count lines, words, characters @item tee a T-fitting for data pipes, copies data to files and to standard output @item sed the stream editor, an advanced tool @item awk a data manipulation language, another advanced tool @end table The software tools philosophy also espoused the following bit of advice: ``Let someone else do the hard part.'' This means, take something that gives you most of what you need, and then massage it the rest of the way until it's in the form that you want. To summarize: @enumerate 1 @item Each program should do one thing well. No more, no less. @item Combining programs with appropriate plumbing leads to results where the whole is greater than the sum of the parts. It also leads to novel uses of programs that the authors might never have imagined. @item Programs should never print extraneous header or trailer data, since these could get sent on down a pipeline. (A point we didn't mention earlier.) @item Let someone else do the hard part. @item Know your toolbox! Use each program appropriately. If you don't have an appropriate tool, build one. @end enumerate As of this writing, all the programs we've discussed are available via anonymous @command{ftp} from: @* @uref{ftp://gnudist.gnu.org/textutils/textutils-1.22.tar.gz}. (There may be more recent versions available now.) None of what I have presented in this column is new. The Software Tools philosophy was first introduced in the book @cite{Software Tools}, by Brian 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 in 1976, using a preprocessor for FORTRAN named @command{ratfor} (RATional FORtran). At the time, C was not as ubiquitous as it is now; FORTRAN was. The last chapter presented a @command{ratfor} to FORTRAN processor, written in @command{ratfor}. @command{ratfor} looks an awful lot like C; if you know C, you won't have any problem following the code. In 1981, the book was updated and made available as @cite{Software Tools in Pascal} (Addison-Wesley, ISBN 0-201-10342-7). Both books are still in print and are well worth reading if you're a programmer. They certainly made a major change in how I view programming. The programs in both books are available from @uref{http://cm.bell-labs.com/who/bwk, Brian Kernighan's home page}. For a number of years, there was an active Software Tools Users Group, whose members had ported the original @command{ratfor} programs to essentially every computer system with a FORTRAN compiler. The popularity of the group waned in the middle 1980s as Unix began to spread beyond universities. With the current proliferation of GNU code and other clones of Unix programs, these programs now receive little attention; modern C versions are much more efficient and do more than these programs do. Nevertheless, as exposition of good programming style, and evangelism for a still-valuable philosophy, these books are unparalleled, and I recommend them highly. Acknowledgment: I would like to express my gratitude to Brian Kernighan of Bell Labs, the original Software Toolsmith, for reviewing this column. @include doclicense.texi @node Index @unnumbered Index @printindex cp @shortcontents @contents @bye @c Local variables: @c texinfo-column-for-description: 32 @c End: