3 @setfilename coreutils.info
4 @settitle @sc{gnu} Coreutils
9 @include constants.texi
11 @c Define new indices.
15 @c Put everything in one index (arbitrarily chosen to be the concept index).
25 * Coreutils: (coreutils). Core GNU (file, text, shell) utilities.
26 * Common options: (coreutils)Common options. Common options.
27 * File permissions: (coreutils)File permissions. Access modes.
28 * Date input formats: (coreutils)Date input formats.
31 @c FIXME: the following need documentation
32 @c * [: (coreutils)[ invocation. File/string tests.
33 @c * pinky: (coreutils)pinky invocation. FIXME.
34 @c * shasum: (coreutils)shasum invocation. Print or check message-digests.
35 @c * uptime: (coreutils)uptime invocation. FIXME.
37 @dircategory Individual utilities
39 * basename: (coreutils)basename invocation. Strip directory and suffix.
40 * cat: (coreutils)cat invocation. Concatenate and write files.
41 * chgrp: (coreutils)chgrp invocation. Change file groups.
42 * chmod: (coreutils)chmod invocation. Change file permissions.
43 * chown: (coreutils)chown invocation. Change file owners/groups.
44 * chroot: (coreutils)chroot invocation. Specify the root directory.
45 * cksum: (coreutils)cksum invocation. Print POSIX CRC checksum.
46 * comm: (coreutils)comm invocation. Compare sorted files by line.
47 * cp: (coreutils)cp invocation. Copy files.
48 * csplit: (coreutils)csplit invocation. Split by context.
49 * cut: (coreutils)cut invocation. Print selected parts of lines.
50 * date: (coreutils)date invocation. Print/set system date and time.
51 * dd: (coreutils)dd invocation. Copy and convert a file.
52 * df: (coreutils)df invocation. Report file system disk usage.
53 * dir: (coreutils)dir invocation. List directories briefly.
54 * dircolors: (coreutils)dircolors invocation. Color setup for ls.
55 * dirname: (coreutils)dirname invocation. Strip non-directory suffix.
56 * du: (coreutils)du invocation. Report on disk usage.
57 * echo: (coreutils)echo invocation. Print a line of text.
58 * env: (coreutils)env invocation. Modify the environment.
59 * expand: (coreutils)expand invocation. Convert tabs to spaces.
60 * expr: (coreutils)expr invocation. Evaluate expressions.
61 * factor: (coreutils)factor invocation. Print prime factors
62 * false: (coreutils)false invocation. Do nothing, unsuccessfully.
63 * fmt: (coreutils)fmt invocation. Reformat paragraph text.
64 * fold: (coreutils)fold invocation. Wrap long input lines.
65 * groups: (coreutils)groups invocation. Print group names a user is in.
66 * head: (coreutils)head invocation. Output the first part of files.
67 * hostid: (coreutils)hostid invocation. Print numeric host identifier.
68 * hostname: (coreutils)hostname invocation. Print or set system name.
69 * id: (coreutils)id invocation. Print user identity.
70 * install: (coreutils)install invocation. Copy and change attributes.
71 * join: (coreutils)join invocation. Join lines on a common field.
72 * kill: (coreutils)kill invocation. Send a signal to processes.
73 * link: (coreutils)link invocation. Make hard links between files.
74 * ln: (coreutils)ln invocation. Make links between files.
75 * logname: (coreutils)logname invocation. Print current login name.
76 * ls: (coreutils)ls invocation. List directory contents.
77 * md5sum: (coreutils)md5sum invocation. Print or check message-digests.
78 * mkdir: (coreutils)mkdir invocation. Create directories.
79 * mkfifo: (coreutils)mkfifo invocation. Create FIFOs (named pipes).
80 * mknod: (coreutils)mknod invocation. Create special files.
81 * mv: (coreutils)mv invocation. Rename files.
82 * nice: (coreutils)nice invocation. Modify scheduling priority.
83 * nl: (coreutils)nl invocation. Number lines and write files.
84 * nohup: (coreutils)nohup invocation. Immunize to hangups.
85 * od: (coreutils)od invocation. Dump files in octal, etc.
86 * paste: (coreutils)paste invocation. Merge lines of files.
87 * pathchk: (coreutils)pathchk invocation. Check file name portability.
88 * pr: (coreutils)pr invocation. Paginate or columnate files.
89 * printenv: (coreutils)printenv invocation. Print environment variables.
90 * printf: (coreutils)printf invocation. Format and print data.
91 * ptx: (coreutils)ptx invocation. Produce permuted indexes.
92 * pwd: (coreutils)pwd invocation. Print working directory.
93 * readlink: (coreutils)readlink invocation. Print referent of a symlink.
94 * rm: (coreutils)rm invocation. Remove files.
95 * rmdir: (coreutils)rmdir invocation. Remove empty directories.
96 * seq: (coreutils)seq invocation. Print numeric sequences
97 * shred: (coreutils)shred invocation. Remove files more securely.
98 * sleep: (coreutils)sleep invocation. Delay for a specified time.
99 * sort: (coreutils)sort invocation. Sort text files.
100 * split: (coreutils)split invocation. Split into fixed-size pieces.
101 * stat: (coreutils)stat invocation. Report file(system) status.
102 * stty: (coreutils)stty invocation. Print/change terminal settings.
103 * su: (coreutils)su invocation. Modify user and group ID.
104 * sum: (coreutils)sum invocation. Print traditional checksum.
105 * sync: (coreutils)sync invocation. Synchronize memory and disk.
106 * tac: (coreutils)tac invocation. Reverse files.
107 * tail: (coreutils)tail invocation. Output the last part of files.
108 * tee: (coreutils)tee invocation. Redirect to multiple files.
109 * test: (coreutils)test invocation. File/string tests.
110 * touch: (coreutils)touch invocation. Change file timestamps.
111 * tr: (coreutils)tr invocation. Translate characters.
112 * true: (coreutils)true invocation. Do nothing, successfully.
113 * tsort: (coreutils)tsort invocation. Topological sort.
114 * tty: (coreutils)tty invocation. Print terminal name.
115 * uname: (coreutils)uname invocation. Print system information.
116 * unexpand: (coreutils)unexpand invocation. Convert spaces to tabs.
117 * uniq: (coreutils)uniq invocation. Uniquify files.
118 * unlink: (coreutils)unlink invocation. Removal via unlink(2).
119 * users: (coreutils)users invocation. Print current user names.
120 * vdir: (coreutils)vdir invocation. List directories verbosely.
121 * wc: (coreutils)wc invocation. Line, word, and byte counts.
122 * who: (coreutils)who invocation. Print who is logged in.
123 * whoami: (coreutils)whoami invocation. Print effective user ID.
124 * yes: (coreutils)yes invocation. Print a string indefinitely.
128 This manual documents version @value{VERSION} of the @sc{gnu} core
129 utilities, including the standard programs for text and file manipulation.
131 Copyright @copyright{} 1994, 1995, 1996, 2000, 2001, 2002, 2003, 2004, 2005
132 Free Software Foundation, Inc.
135 Permission is granted to copy, distribute and/or modify this document
136 under the terms of the GNU Free Documentation License, Version 1.1 or
137 any later version published by the Free Software Foundation; with no
138 Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
139 Texts. A copy of the license is included in the section entitled ``GNU
140 Free Documentation License''.
145 @title @sc{gnu} @code{Coreutils}
146 @subtitle Core GNU utilities
147 @subtitle for version @value{VERSION}, @value{UPDATED}
148 @author David MacKenzie et al.
151 @vskip 0pt plus 1filll
163 @cindex core utilities
164 @cindex text utilities
165 @cindex shell utilities
166 @cindex file utilities
169 * Introduction:: Caveats, overview, and authors.
170 * Common options:: Common options.
171 * Output of entire files:: cat tac nl od
172 * Formatting file contents:: fmt pr fold
173 * Output of parts of files:: head tail split csplit
174 * Summarizing files:: wc sum cksum md5sum
175 * Operating on sorted files:: sort uniq comm ptx tsort
176 * Operating on fields within a line:: cut paste join
177 * Operating on characters:: tr expand unexpand
178 * Directory listing:: ls dir vdir d v dircolors
179 * Basic operations:: cp dd install mv rm shred
180 * Special file types:: ln mkdir rmdir mkfifo mknod
181 * Changing file attributes:: chgrp chmod chown touch
182 * Disk usage:: df du stat sync
183 * Printing text:: echo printf yes
184 * Conditions:: false true test expr
186 * File name manipulation:: dirname basename pathchk
187 * Working context:: pwd stty printenv tty
188 * User information:: id logname whoami groups users who
189 * System context:: date uname hostname
190 * Modified command invocation:: chroot env nice nohup su
191 * Process control:: kill
193 * Numeric operations:: factor seq
194 * File permissions:: Access modes.
195 * Date input formats:: Specifying date strings.
196 * Opening the software toolbox:: The software tools philosophy.
197 * GNU Free Documentation License:: The license for this documentation.
198 * Index:: General index.
201 --- The Detailed Node Listing ---
205 * Exit status:: Indicating program success or failure.
206 * Backup options:: Backup options
207 * Block size:: Block size
208 * Target directory:: Target directory
209 * Trailing slashes:: Trailing slashes
210 * Traversing symlinks:: Traversing symlinks to directories
211 * Treating / specially:: Treating / specially
212 * Standards conformance:: Standards conformance
214 Output of entire files
216 * cat invocation:: Concatenate and write files.
217 * tac invocation:: Concatenate and write files in reverse.
218 * nl invocation:: Number lines and write files.
219 * od invocation:: Write files in octal or other formats.
221 Formatting file contents
223 * fmt invocation:: Reformat paragraph text.
224 * pr invocation:: Paginate or columnate files for printing.
225 * fold invocation:: Wrap input lines to fit in specified width.
227 Output of parts of files
229 * head invocation:: Output the first part of files.
230 * tail invocation:: Output the last part of files.
231 * split invocation:: Split a file into fixed-size pieces.
232 * csplit invocation:: Split a file into context-determined pieces.
236 * wc invocation:: Print newline, word, and byte counts.
237 * sum invocation:: Print checksum and block counts.
238 * cksum invocation:: Print CRC checksum and byte counts.
239 * md5sum invocation:: Print or check message-digests.
241 Operating on sorted files
243 * sort invocation:: Sort text files.
244 * uniq invocation:: Uniquify files.
245 * comm invocation:: Compare two sorted files line by line.
246 * ptx invocation:: Produce a permuted index of file contents.
247 * tsort invocation:: Topological sort.
249 @command{ptx}: Produce permuted indexes
251 * General options in ptx:: Options which affect general program behavior.
252 * Charset selection in ptx:: Underlying character set considerations.
253 * Input processing in ptx:: Input fields, contexts, and keyword selection.
254 * Output formatting in ptx:: Types of output format, and sizing the fields.
255 * Compatibility in ptx:: The GNU extensions to @command{ptx}
257 Operating on fields within a line
259 * cut invocation:: Print selected parts of lines.
260 * paste invocation:: Merge lines of files.
261 * join invocation:: Join lines on a common field.
263 Operating on characters
265 * tr invocation:: Translate, squeeze, and/or delete characters.
266 * expand invocation:: Convert tabs to spaces.
267 * unexpand invocation:: Convert spaces to tabs.
269 @command{tr}: Translate, squeeze, and/or delete characters
271 * Character sets:: Specifying sets of characters.
272 * Translating:: Changing one set of characters to another.
273 * Squeezing:: Squeezing repeats and deleting.
277 * ls invocation:: List directory contents
278 * dir invocation:: Briefly list directory contents
279 * vdir invocation:: Verbosely list directory contents
280 * dircolors invocation:: Color setup for @command{ls}
282 @command{ls}: List directory contents
284 * Which files are listed:: Which files are listed
285 * What information is listed:: What information is listed
286 * Sorting the output:: Sorting the output
287 * More details about version sort:: More details about version sort
288 * General output formatting:: General output formatting
289 * Formatting the file names:: Formatting the file names
293 * cp invocation:: Copy files and directories
294 * dd invocation:: Convert and copy a file
295 * install invocation:: Copy files and set attributes
296 * mv invocation:: Move (rename) files
297 * rm invocation:: Remove files or directories
298 * shred invocation:: Remove files more securely
302 * link invocation:: Make a hard link via the link syscall
303 * ln invocation:: Make links between files
304 * mkdir invocation:: Make directories
305 * mkfifo invocation:: Make FIFOs (named pipes)
306 * mknod invocation:: Make block or character special files
307 * readlink invocation:: Print the referent of a symbolic link
308 * rmdir invocation:: Remove empty directories
309 * unlink invocation:: Remove files via unlink syscall
311 Changing file attributes
313 * chown invocation:: Change file owner and group
314 * chgrp invocation:: Change group ownership
315 * chmod invocation:: Change access permissions
316 * touch invocation:: Change file timestamps
320 * df invocation:: Report file system disk space usage
321 * du invocation:: Estimate file space usage
322 * stat invocation:: Report file or file system status
323 * sync invocation:: Synchronize data on disk with memory
327 * echo invocation:: Print a line of text
328 * printf invocation:: Format and print data
329 * yes invocation:: Print a string until interrupted
333 * false invocation:: Do nothing, unsuccessfully
334 * true invocation:: Do nothing, successfully
335 * test invocation:: Check file types and compare values
336 * expr invocation:: Evaluate expressions
338 @command{test}: Check file types and compare values
340 * File type tests:: File type tests
341 * Access permission tests:: Access permission tests
342 * File characteristic tests:: File characteristic tests
343 * String tests:: String tests
344 * Numeric tests:: Numeric tests
346 @command{expr}: Evaluate expression
348 * String expressions:: + : match substr index length
349 * Numeric expressions:: + - * / %
350 * Relations for expr:: | & < <= = == != >= >
351 * Examples of expr:: Examples of using @command{expr}
355 * tee invocation:: Redirect output to multiple files
357 File name manipulation
359 * basename invocation:: Strip directory and suffix from a file name
360 * dirname invocation:: Strip non-directory suffix from a file name
361 * pathchk invocation:: Check file name portability
365 * pwd invocation:: Print working directory
366 * stty invocation:: Print or change terminal characteristics
367 * printenv invocation:: Print all or some environment variables
368 * tty invocation:: Print file name of terminal on standard input
370 @command{stty}: Print or change terminal characteristics
372 * Control:: Control settings
373 * Input:: Input settings
374 * Output:: Output settings
375 * Local:: Local settings
376 * Combination:: Combination settings
377 * Characters:: Special characters
378 * Special:: Special settings
382 * id invocation:: Print user identity
383 * logname invocation:: Print current login name
384 * whoami invocation:: Print effective user ID
385 * groups invocation:: Print group names a user is in
386 * users invocation:: Print login names of users currently logged in
387 * who invocation:: Print who is currently logged in
391 * date invocation:: Print or set system date and time
392 * uname invocation:: Print system information
393 * hostname invocation:: Print or set system name
394 * hostid invocation:: Print numeric host identifier.
396 @command{date}: Print or set system date and time
398 * Time conversion specifiers:: %[HIklMNpPrRsSTXzZ]
399 * Date conversion specifiers:: %[aAbBcCdDeFgGhjmuUVwWxyY]
400 * Literal conversion specifiers:: %[%nt]
401 * Padding and other flags:: Pad with zeroes, spaces, etc.
402 * Setting the time:: Changing the system clock.
403 * Options for date:: Instead of the current time.
404 * Examples of date:: Examples.
406 Modified command invocation
408 * chroot invocation:: Run a command with a different root directory
409 * env invocation:: Run a command in a modified environment
410 * nice invocation:: Run a command with modified scheduling priority
411 * nohup invocation:: Run a command immune to hangups
412 * su invocation:: Run a command with substitute user and group ID
416 * kill invocation:: Sending a signal to processes.
420 * sleep invocation:: Delay for a specified time
424 * factor invocation:: Print prime factors
425 * seq invocation:: Print numeric sequences
429 * Mode Structure:: Structure of File Permissions
430 * Symbolic Modes:: Mnemonic permissions representation
431 * Numeric Modes:: Permissions as octal numbers
435 * General date syntax:: Common rules.
436 * Calendar date items:: 19 Dec 1994.
437 * Time of day items:: 9:20pm.
438 * Time zone items:: @sc{est}, @sc{pdt}, @sc{gmt}.
439 * Day of week items:: Monday and others.
440 * Relative items in date strings:: next tuesday, 2 years ago.
441 * Pure numbers in date strings:: 19931219, 1440.
442 * Seconds since the Epoch:: @@1078100502.
443 * Specifying time zone rules:: TZ="America/New_York", TZ="UTC0".
444 * Authors of get_date:: Bellovin, Eggert, Salz, Berets, et al.
446 Opening the software toolbox
448 * Toolbox introduction:: Toolbox introduction
449 * I/O redirection:: I/O redirection
450 * The who command:: The @command{who} command
451 * The cut command:: The @command{cut} command
452 * The sort command:: The @command{sort} command
453 * The uniq command:: The @command{uniq} command
454 * Putting the tools together:: Putting the tools together
456 GNU Free Documentation License
458 * How to use this License for your documents::
465 @chapter Introduction
467 This manual is a work in progress: many sections make no attempt to explain
468 basic concepts in a way suitable for novices. Thus, if you are interested,
469 please get involved in improving this manual. The entire @sc{gnu} community
472 @cindex @acronym{POSIX}
473 The @sc{gnu} utilities documented here are mostly compatible with the
474 @acronym{POSIX} standard.
475 @cindex bugs, reporting
476 Please report bugs to @email{bug-coreutils@@gnu.org}. Remember
477 to include the version number, machine architecture, input files, and
478 any other information needed to reproduce the bug: your input, what you
479 expected, what you got, and why it is wrong. Diffs are welcome, but
480 please include a description of the problem as well, since this is
481 sometimes difficult to infer. @xref{Bugs, , , gcc, Using and Porting GNU CC}.
487 @cindex MacKenzie, D.
490 This manual was originally derived from the Unix man pages in the
491 distributions, which were written by David MacKenzie and updated by Jim
492 Meyering. What you are reading now is the authoritative documentation
493 for these utilities; the man pages are no longer being maintained. The
494 original @command{fmt} man page was written by Ross Paterson. Fran@,{c}ois
495 Pinard did the initial conversion to Texinfo format. Karl Berry did the
496 indexing, some reorganization, and editing of the results. Brian
497 Youmans of the Free Software Foundation office staff combined the
498 manuals for textutils, fileutils, and sh-utils to produce the present
499 omnibus manual. Richard Stallman contributed his usual invaluable
500 insights to the overall process.
503 @chapter Common options
507 @itemx @w{@kbd{--backup}[=@var{method}]}
510 @vindex VERSION_CONTROL
511 @cindex backups, making
512 @xref{Backup options}.
513 Make a backup of each file that would otherwise be overwritten or removed.
516 @macro optBackupSuffix
517 @item -S @var{suffix}
518 @itemx --suffix=@var{suffix}
521 Append @var{suffix} to each backup file made with @option{-b}.
522 @xref{Backup options}.
525 @macro optTargetDirectory
526 @item -t @var{directory}
527 @itemx @w{@kbd{--target-directory}=@var{directory}}
529 @opindex --target-directory
530 @cindex target directory
531 @cindex destination directory
532 Specify the destination @var{directory}.
533 @xref{Target directory}.
536 @macro optNoTargetDirectory
538 @itemx --no-target-directory
540 @opindex --no-target-directory
541 @cindex target directory
542 @cindex destination directory
543 Do not treat the last operand specially when it is a directory or a
544 symbolic link to a directory. @xref{Target directory}.
551 Append an SI-style abbreviation to each size, such as @samp{MB} for
552 megabytes. Powers of 1000 are used, not 1024; @samp{MB} stands for
553 1,000,000 bytes. This option is equivalent to
554 @option{--block-size=si}. Use the @option{-h} or
555 @option{--human-readable} option if
556 you prefer powers of 1024.
559 @macro optHumanReadable
561 @itemx --human-readable
563 @opindex --human-readable
564 @cindex human-readable output
565 Append a size letter to each size, such as @samp{M} for mebibytes.
566 Powers of 1024 are used, not 1000; @samp{M} stands for 1,048,576 bytes.
567 Use the @option{--si} option if you prefer powers of 1000.
570 @macro optStripTrailingSlashes
571 @itemx @w{@kbd{--strip-trailing-slashes}}
572 @opindex --strip-trailing-slashes
573 @cindex stripping trailing slashes
574 Remove any trailing slashes from each @var{source} argument.
575 @xref{Trailing slashes}.
578 @cindex common options
580 Certain options are available in all of these programs. Rather than
581 writing identical descriptions for each of the programs, they are
582 described here. (In fact, every @sc{gnu} program accepts (or should accept)
585 @vindex POSIXLY_CORRECT
586 Normally options and operands can appear in any order, and programs act
587 as if all the options appear before any operands. For example,
588 @samp{sort -r passwd -t :} acts like @samp{sort -r -t : passwd}, since
589 @samp{:} is an option-argument of @option{-t}. However, if the
590 @env{POSIXLY_CORRECT} environment variable is set, options must appear
591 before operands, unless otherwise specified for a particular command.
593 A few programs can usefully have trailing operands with leading
594 @samp{-}. With such a program, options must precede operands even if
595 @env{POSIXLY_CORRECT} is not set, and this fact is noted in the
596 program description. For example, the @command{env} command's options
597 must appear before its operands, since in some cases the operands
598 specify a command that itself contains options.
600 Some of these programs recognize the @option{--help} and @option{--version}
601 options only when one of them is the sole command line argument.
608 Print a usage message listing all available options, then exit successfully.
612 @cindex version number, finding
613 Print the version number, then exit successfully.
617 @cindex option delimiter
618 Delimit the option list. Later arguments, if any, are treated as
619 operands even if they begin with @samp{-}. For example, @samp{sort --
620 -r} reads from the file named @file{-r}.
624 @cindex standard input
625 @cindex standard output
626 A single @samp{-} operand is not really an option, though it looks like one. It
627 stands for standard input, or for standard output if that is clear from
628 the context. For example, @samp{sort -} reads from standard input,
629 and is equivalent to plain @samp{sort}, and @samp{tee -} writes an
630 extra copy of its input to standard output. Unless otherwise
631 specified, @samp{-} can appear as any operand that requires a file
635 * Exit status:: Indicating program success or failure.
636 * Backup options:: -b -S, in some programs.
637 * Block size:: BLOCK_SIZE and --block-size, in some programs.
638 * Target directory:: Specifying a target directory, in some programs.
639 * Trailing slashes:: --strip-trailing-slashes, in some programs.
640 * Traversing symlinks:: -H, -L, or -P, in some programs.
641 * Treating / specially:: --preserve-root and --no-preserve-root.
642 * Special built-in utilities:: @command{break}, @command{:}, @command{eval}, @dots{}
643 * Standards conformance:: Conformance to the @acronym{POSIX} standard.
651 An exit status of zero indicates success,
652 and a nonzero value indicates failure.
655 Nearly every command invocation yields an integral @dfn{exit status}
656 that can be used to change how other commands work.
657 For the vast majority of commands, an exit status of zero indicates
658 success. Failure is indicated by a nonzero value---typically
659 @samp{1}, though it may differ on unusual platforms as @acronym{POSIX}
660 requires only that it be nonzero.
662 However, some of the programs documented here do produce
663 other exit status values and a few associate different
664 meanings with the values @samp{0} and @samp{1}.
665 Here are some of the exceptions:
666 @command{chroot}, @command{env}, @command{expr},
667 @command{nice}, @command{nohup}, @command{printenv},
668 @command{sort}, @command{su}, @command{test}, @command{tty}.
672 @section Backup options
674 @cindex backup options
676 Some @sc{gnu} programs (at least @command{cp}, @command{install},
677 @command{ln}, and @command{mv}) optionally make backups of files
678 before writing new versions.
679 These options control the details of these backups. The options are also
680 briefly mentioned in the descriptions of the particular programs.
685 @itemx @w{@kbd{--backup}[=@var{method}]}
688 @vindex VERSION_CONTROL
689 @cindex backups, making
690 Make a backup of each file that would otherwise be overwritten or removed.
691 Without this option, the original versions are destroyed.
692 Use @var{method} to determine the type of backups to make.
693 When this option is used but @var{method} is not specified,
694 then the value of the @env{VERSION_CONTROL}
695 environment variable is used. And if @env{VERSION_CONTROL} is not set,
696 the default backup type is @samp{existing}.
698 Note that the short form of this option, @option{-b} does not accept any
699 argument. Using @option{-b} is equivalent to using @option{--backup=existing}.
701 @vindex version-control @r{Emacs variable}
702 This option corresponds to the Emacs variable @samp{version-control};
703 the values for @var{method} are the same as those used in Emacs.
704 This option also accepts more descriptive names.
705 The valid @var{method}s are (unique abbreviations are accepted):
710 @opindex none @r{backup method}
715 @opindex numbered @r{backup method}
716 Always make numbered backups.
720 @opindex existing @r{backup method}
721 Make numbered backups of files that already have them, simple backups
726 @opindex simple @r{backup method}
727 Always make simple backups. Please note @samp{never} is not to be
728 confused with @samp{none}.
732 @item -S @var{suffix}
733 @itemx --suffix=@var{suffix}
736 @cindex backup suffix
737 @vindex SIMPLE_BACKUP_SUFFIX
738 Append @var{suffix} to each backup file made with @option{-b}. If this
739 option is not specified, the value of the @env{SIMPLE_BACKUP_SUFFIX}
740 environment variable is used. And if @env{SIMPLE_BACKUP_SUFFIX} is not
741 set, the default is @samp{~}, just as in Emacs.
750 Some @sc{gnu} programs (at least @command{df}, @command{du}, and
751 @command{ls}) display sizes in ``blocks''. You can adjust the block size
752 and method of display to make sizes easier to read. The block size
753 used for display is independent of any file system block size.
754 Fractional block counts are rounded up to the nearest integer.
756 @opindex --block-size=@var{size}
759 @vindex DF_BLOCK_SIZE
760 @vindex DU_BLOCK_SIZE
761 @vindex LS_BLOCK_SIZE
762 @vindex POSIXLY_CORRECT@r{, and block size}
764 The default block size is chosen by examining the following environment
765 variables in turn; the first one that is set determines the block size.
770 This specifies the default block size for the @command{df} command.
771 Similarly, @env{DU_BLOCK_SIZE} specifies the default for @command{du} and
772 @env{LS_BLOCK_SIZE} for @command{ls}.
775 This specifies the default block size for all three commands, if the
776 above command-specific environment variables are not set.
779 This specifies the default block size for all values that are normally
780 printed as blocks, if neither @env{BLOCK_SIZE} nor the above
781 command-specific environment variables are set. Unlike the other
782 environment variables, @env{BLOCKSIZE} does not affect values that are
783 normally printed as byte counts, e.g., the file sizes contained in
786 @item POSIXLY_CORRECT
787 If neither @env{@var{command}_BLOCK_SIZE}, nor @env{BLOCK_SIZE}, nor
788 @env{BLOCKSIZE} is set, but this variable is set, the block size
793 If none of the above environment variables are set, the block size
794 currently defaults to 1024 bytes in most contexts, but this number may
795 change in the future. For @command{ls} file sizes, the block size
798 @cindex human-readable output
801 A block size specification can be a positive integer specifying the number
802 of bytes per block, or it can be @code{human-readable} or @code{si} to
803 select a human-readable format. Integers may be followed by suffixes
804 that are upward compatible with the
805 @uref{http://www.bipm.fr/enus/3_SI/si-prefixes.html, SI prefixes}
806 for decimal multiples and with the
807 @uref{http://physics.nist.gov/cuu/Units/binary.html, IEC 60027-2
808 prefixes for binary multiples}.
810 With human-readable formats, output sizes are followed by a size letter
811 such as @samp{M} for megabytes. @code{BLOCK_SIZE=human-readable} uses
812 powers of 1024; @samp{M} stands for 1,048,576 bytes.
813 @code{BLOCK_SIZE=si} is similar, but uses powers of 1000 and appends
814 @samp{B}; @samp{MB} stands for 1,000,000 bytes.
817 A block size specification preceded by @samp{'} causes output sizes to
818 be displayed with thousands separators. The @env{LC_NUMERIC} locale
819 specifies the thousands separator and grouping. For example, in an
820 American English locale, @samp{--block-size="'1kB"} would cause a size
821 of 1234000 bytes to be displayed as @samp{1,234}. In the default C
822 locale, there is no thousands separator so a leading @samp{'} has no
825 An integer block size can be followed by a suffix to specify a
826 multiple of that size. A bare size letter,
827 or one followed by @samp{iB}, specifies
828 a multiple using powers of 1024. A size letter followed by @samp{B}
829 specifies powers of 1000 instead. For example, @samp{1M} and
830 @samp{1MiB} are equivalent to @samp{1048576}, whereas @samp{1MB} is
831 equivalent to @samp{1000000}.
833 A plain suffix without a preceding integer acts as if @samp{1} were
834 prepended, except that it causes a size indication to be appended to
835 the output. For example, @samp{--block-size="kB"} displays 3000 as
838 The following suffixes are defined. Large sizes like @code{1Y}
839 may be rejected by your computer due to limitations of its arithmetic.
843 @cindex kilobyte, definition of
844 kilobyte: @math{10^3 = 1000}.
848 @cindex kibibyte, definition of
849 kibibyte: @math{2^10 = 1024}. @samp{K} is special: the SI prefix is
850 @samp{k} and the IEC 60027-2 prefix is @samp{Ki}, but tradition and
851 @acronym{POSIX} use @samp{k} to mean @samp{KiB}.
853 @cindex megabyte, definition of
854 megabyte: @math{10^6 = 1,000,000}.
857 @cindex mebibyte, definition of
858 mebibyte: @math{2^20 = 1,048,576}.
860 @cindex gigabyte, definition of
861 gigabyte: @math{10^9 = 1,000,000,000}.
864 @cindex gibibyte, definition of
865 gibibyte: @math{2^30 = 1,073,741,824}.
867 @cindex terabyte, definition of
868 terabyte: @math{10^12 = 1,000,000,000,000}.
871 @cindex tebibyte, definition of
872 tebibyte: @math{2^40 = 1,099,511,627,776}.
874 @cindex petabyte, definition of
875 petabyte: @math{10^15 = 1,000,000,000,000,000}.
878 @cindex pebibyte, definition of
879 pebibyte: @math{2^50 = 1,125,899,906,842,624}.
881 @cindex exabyte, definition of
882 exabyte: @math{10^18 = 1,000,000,000,000,000,000}.
885 @cindex exbibyte, definition of
886 exbibyte: @math{2^60 = 1,152,921,504,606,846,976}.
888 @cindex zettabyte, definition of
889 zettabyte: @math{10^21 = 1,000,000,000,000,000,000,000}
892 @math{2^70 = 1,180,591,620,717,411,303,424}.
893 (@samp{Zi} is a GNU extension to IEC 60027-2.)
895 @cindex yottabyte, definition of
896 yottabyte: @math{10^24 = 1,000,000,000,000,000,000,000,000}.
899 @math{2^80 = 1,208,925,819,614,629,174,706,176}.
900 (@samp{Yi} is a GNU extension to IEC 60027-2.)
905 @opindex --block-size
906 @opindex --human-readable
909 Block size defaults can be overridden by an explicit
910 @option{--block-size=@var{size}} option. The @option{-k}
911 option is equivalent to @option{--block-size=1K}, which
912 is the default unless the @env{POSIXLY_CORRECT} environment variable is
913 set. The @option{-h} or @option{--human-readable} option is equivalent to
914 @option{--block-size=human-readable}. The @option{--si} option is
915 equivalent to @option{--block-size=si}.
917 @node Target directory
918 @section Target directory
920 @cindex target directory
922 The @command{cp}, @command{install}, @command{ln}, and @command{mv}
923 commands normally treat the last operand specially when it is a
924 directory or a symbolic link to a directory. For example, @samp{cp
925 source dest} is equivalent to @samp{cp source dest/source} if
926 @file{dest} is a directory. Sometimes this behavior is not exactly
927 what is wanted, so these commands support the following options to
928 allow more fine-grained control:
933 @itemx --no-target-directory
934 @opindex --no-target-directory
935 @cindex target directory
936 @cindex destination directory
937 Do not treat the last operand specially when it is a directory or a
938 symbolic link to a directory. This can help avoid race conditions in
939 programs that operate in a shared area. For example, when the command
940 @samp{mv /tmp/source /tmp/dest} succeeds, there is no guarantee that
941 @file{/tmp/source} was renamed to @file{/tmp/dest}: it could have been
942 renamed to @file{/tmp/dest/source} instead, if some other process
943 created @file{/tmp/dest} as a directory. However, if @file{mv
944 -T /tmp/source /tmp/dest} succeeds, there is no
945 question that @file{/tmp/source} was renamed to @file{/tmp/dest}.
947 In the opposite situation, where you want the last operand to be
948 treated as a directory and want a diagnostic otherwise, you can use
949 the @option{--target-directory} (@option{-t}) option.
951 @item -t @var{directory}
952 @itemx @w{@kbd{--target-directory}=@var{directory}}
953 @opindex --target-directory
954 @cindex target directory
955 @cindex destination directory
956 Use @var{directory} as the directory component of each destination
959 The interface for most programs is that after processing options and a
960 finite (possibly zero) number of fixed-position arguments, the remaining
961 argument list is either expected to be empty, or is a list of items
962 (usually files) that will all be handled identically. The @command{xargs}
963 program is designed to work well with this convention.
965 The commands in the @command{mv}-family are unusual in that they take
966 a variable number of arguments with a special case at the @emph{end}
967 (namely, the target directory). This makes it nontrivial to perform some
968 operations, e.g., ``move all files from here to ../d/'', because
969 @code{mv * ../d/} might exhaust the argument space, and @code{ls | xargs ...}
970 doesn't have a clean way to specify an extra final argument for each
971 invocation of the subject command. (It can be done by going through a
972 shell command, but that requires more human labor and brain power than
975 The @w{@kbd{--target-directory}} (@option{-t}) option allows the @command{cp},
976 @command{install}, @command{ln}, and @command{mv} programs to be used
977 conveniently with @command{xargs}. For example, you can move the files
978 from the current directory to a sibling directory, @code{d} like this:
981 ls | xargs mv -t ../d --
984 However, this doesn't move files whose names begin with @samp{.}.
985 If you use the @sc{gnu} @command{find} program, you can move those
986 files too, with this command:
989 find . -mindepth 1 -maxdepth 1 \
993 But both of the above approaches fail if there are no files in the
994 current directory, or if any file has a name containing a blank or
995 some other special characters.
996 The following example removes those limitations and requires both
997 @sc{gnu} @command{find} and @sc{gnu} @command{xargs}:
1000 find . -mindepth 1 -maxdepth 1 -print0 \
1001 | xargs --null --no-run-if-empty \
1008 The @option{--target-directory} (@option{-t}) and
1009 @option{--no-target-directory} (@option{-T})
1010 options cannot be combined.
1012 @node Trailing slashes
1013 @section Trailing slashes
1015 @cindex trailing slashes
1017 Some @sc{gnu} programs (at least @command{cp} and @command{mv}) allow you to
1018 remove any trailing slashes from each @var{source} argument before
1019 operating on it. The @w{@kbd{--strip-trailing-slashes}} option enables
1022 This is useful when a @var{source} argument may have a trailing slash and
1023 @c FIXME: mv's behavior in this case is system-dependent
1024 specify a symbolic link to a directory. This scenario is in fact rather
1025 common because some shells can automatically append a trailing slash when
1026 performing file name completion on such symbolic links. Without this
1027 option, @command{mv}, for example, (via the system's rename function) must
1028 interpret a trailing slash as a request to dereference the symbolic link
1029 and so must rename the indirectly referenced @emph{directory} and not
1030 the symbolic link. Although it may seem surprising that such behavior
1031 be the default, it is required by @acronym{POSIX} and is consistent with
1032 other parts of that standard.
1034 @node Traversing symlinks
1035 @section Traversing symlinks
1037 @cindex symbolic link to directory, controlling traversal of
1039 The following options modify how @command{chown} and @command{chgrp}
1040 @c FIXME: note that `du' has these options, too, but they have slightly
1041 @c different meaning.
1042 traverse a hierarchy when the @option{--recursive} (@option{-R})
1043 option is also specified.
1044 If more than one of the following options is specified, only the final
1046 These options specify whether processing a symbolic link to a directory
1047 entails operating on just the symbolic link or on all files in the
1048 hierarchy rooted at that directory.
1050 These options are independent of @option{--dereference} and
1051 @option{--no-dereference} (@option{-h}), which control whether to modify
1052 a symlink or its referent.
1059 @cindex symbolic link to directory, traverse each that is specified on the command line
1060 If @option{--recursive} (@option{-R}) is specified and
1061 a command line argument is a symbolic link to a directory, traverse it.
1068 @cindex symbolic link to directory, traverse each that is encountered
1069 In a recursive traversal, traverse every symbolic link to a directory
1070 that is encountered.
1077 @cindex symbolic link to directory, never traverse
1078 Do not traverse any symbolic links.
1079 This is the default if none of @option{-H}, @option{-L},
1080 or @option{-P} is specified.
1087 @node Treating / specially
1088 @section Treating / specially
1090 Certain commands can operate destructively on entire hierarchies.
1091 For example, if a user with appropriate privileges mistakenly runs
1092 @samp{rm -rf / tmp/junk} or @samp{cd /bin; rm -rf ../}, that may remove
1093 all files on the entire system. Since there are so few
1094 @footnote{If you know of one, please write to @email{bug-coreutils@@gnu.org}.}
1095 legitimate uses for such a command,
1096 @sc{gnu} @command{rm} provides the @option{--preserve-root} option
1097 to make it so @command{rm} declines to operate on any directory
1098 that resolves to @file{/}. The default is still to allow
1099 @samp{rm -rf /} to operate unimpeded.
1100 Another new option, @option{--no-preserve-root}, cancels the
1101 effect of any preceding @option{--preserve-root} option.
1102 Note that the @option{--preserve-root} behavior may become the default
1105 The commands @command{chgrp}, @command{chmod} and @command{chown}
1106 can also operate destructively on entire hierarchies, so they too
1107 support these options. Although, unlike @command{rm}, they don't
1108 actually unlink files, these commands are arguably more dangerous
1109 when operating recursively on @file{/}, since they often work much
1110 more quickly, and hence damage more files before an alert user can
1113 @node Special built-in utilities
1114 @section Special built-in utilities
1116 Some programs like @command{nice} can invoke other programs; for
1117 example, the command @samp{nice cat file} invokes the program
1118 @command{cat} by executing the command @samp{cat file}. However,
1119 @dfn{special built-in utilities} like @command{exit} cannot be invoked
1120 this way. For example, the command @samp{nice exit} does not have a
1121 well-defined behavior: it may generate an error message instead of
1124 Here is a list of the special built-in utilities that are standardized
1125 by @acronym{POSIX} 1003.1-2004.
1128 @t{.@: : break continue eval exec exit export readonly
1129 return set shift times trap unset}
1132 For example, because @samp{.}, @samp{:}, and @samp{exec} are special,
1133 the commands @samp{nice . foo.sh}, @samp{nice :}, and @samp{nice exec
1134 pwd} do not work as you might expect.
1136 Many shells extend this list. For example, Bash has several extra
1137 special built-in utilities like @command{history}, and
1138 @command{suspend}, and with Bash the command @samp{nice suspend}
1139 generates an error message instead of suspending.
1141 @node Standards conformance
1142 @section Standards conformance
1144 @vindex POSIXLY_CORRECT
1145 In a few cases, the @sc{gnu} utilities' default behavior is
1146 incompatible with the @acronym{POSIX} standard. To suppress these
1147 incompatibilities, define the @env{POSIXLY_CORRECT} environment
1148 variable. Unless you are checking for @acronym{POSIX} conformance, you
1149 probably do not need to define @env{POSIXLY_CORRECT}.
1151 Newer versions of @acronym{POSIX} are occasionally incompatible with older
1152 versions. For example, older versions of @acronym{POSIX} required the
1153 command @samp{sort +1} to sort based on the second and succeeding
1154 fields in each input line, but starting with @acronym{POSIX} 1003.1-2001
1155 the same command is required to sort the file named @file{+1}, and you
1156 must instead use the command @samp{sort -k 2} to get the field-based
1159 @vindex _POSIX2_VERSION
1160 The @sc{gnu} utilities normally conform to the version of @acronym{POSIX}
1161 that is standard for your system. To cause them to conform to a
1162 different version of @acronym{POSIX}, define the @env{_POSIX2_VERSION}
1163 environment variable to a value of the form @var{yyyymm} specifying
1164 the year and month the standard was adopted. Two values are currently
1165 supported for @env{_POSIX2_VERSION}: @samp{199209} stands for
1166 @acronym{POSIX} 1003.2-1992, and @samp{200112} stands for @acronym{POSIX}
1167 1003.1-2001. For example, if you have a newer system but are running software
1168 that assumes an older version of @acronym{POSIX} and uses @samp{sort +1}
1169 or @samp{tail +10}, you can work around any compatibility problems by setting
1170 @samp{_POSIX2_VERSION=199209} in your environment.
1172 @node Output of entire files
1173 @chapter Output of entire files
1175 @cindex output of entire files
1176 @cindex entire files, output of
1178 These commands read and write entire files, possibly transforming them
1182 * cat invocation:: Concatenate and write files.
1183 * tac invocation:: Concatenate and write files in reverse.
1184 * nl invocation:: Number lines and write files.
1185 * od invocation:: Write files in octal or other formats.
1188 @node cat invocation
1189 @section @command{cat}: Concatenate and write files
1192 @cindex concatenate and write files
1193 @cindex copying files
1195 @command{cat} copies each @var{file} (@samp{-} means standard input), or
1196 standard input if none are given, to standard output. Synopsis:
1199 cat [@var{option}] [@var{file}]@dots{}
1202 The program accepts the following options. Also see @ref{Common options}.
1210 Equivalent to @option{-vET}.
1216 @cindex binary and text I/O in cat
1217 On MS-DOS and MS-Windows only, read and write the files in binary mode.
1218 By default, @command{cat} on MS-DOS/MS-Windows uses binary mode only when
1219 standard output is redirected to a file or a pipe; this option overrides
1220 that. Binary file I/O is used so that the files retain their format
1221 (Unix text as opposed to DOS text and binary), because @command{cat} is
1222 frequently used as a file-copying program. Some options (see below)
1223 cause @command{cat} to read and write files in text mode because in those
1224 cases the original file contents aren't important (e.g., when lines are
1225 numbered by @command{cat}, or when line endings should be marked). This is
1226 so these options work as DOS/Windows users would expect; for example,
1227 DOS-style text files have their lines end with the CR-LF pair of
1228 characters, which won't be processed as an empty line by @option{-b} unless
1229 the file is read in text mode.
1232 @itemx --number-nonblank
1234 @opindex --number-nonblank
1235 Number all nonblank output lines, starting with 1. On MS-DOS and
1236 MS-Windows, this option causes @command{cat} to read and write files in
1241 Equivalent to @option{-vE}.
1246 @opindex --show-ends
1247 Display a @samp{$} after the end of each line. On MS-DOS and
1248 MS-Windows, this option causes @command{cat} to read and write files in
1255 Number all output lines, starting with 1. On MS-DOS and MS-Windows,
1256 this option causes @command{cat} to read and write files in text mode.
1259 @itemx --squeeze-blank
1261 @opindex --squeeze-blank
1262 @cindex squeezing blank lines
1263 Replace multiple adjacent blank lines with a single blank line. On
1264 MS-DOS and MS-Windows, this option causes @command{cat} to read and write
1269 Equivalent to @option{-vT}.
1274 @opindex --show-tabs
1275 Display TAB characters as @samp{^I}.
1279 Ignored; for Unix compatibility.
1282 @itemx --show-nonprinting
1284 @opindex --show-nonprinting
1285 Display control characters except for LFD and TAB using
1286 @samp{^} notation and precede characters that have the high bit set with
1287 @samp{M-}. On MS-DOS and MS-Windows, this option causes @command{cat} to
1288 read files and standard input in DOS binary mode, so the CR
1289 characters at the end of each line are also visible.
1298 # Output f's contents, then standard input, then g's contents.
1301 # Copy standard input to standard output.
1306 @node tac invocation
1307 @section @command{tac}: Concatenate and write files in reverse
1310 @cindex reversing files
1312 @command{tac} copies each @var{file} (@samp{-} means standard input), or
1313 standard input if none are given, to standard output, reversing the
1314 records (lines by default) in each separately. Synopsis:
1317 tac [@var{option}]@dots{} [@var{file}]@dots{}
1320 @dfn{Records} are separated by instances of a string (newline by
1321 default). By default, this separator string is attached to the end of
1322 the record that it follows in the file.
1324 The program accepts the following options. Also see @ref{Common options}.
1332 The separator is attached to the beginning of the record that it
1333 precedes in the file.
1339 Treat the separator string as a regular expression. Users of @command{tac}
1340 on MS-DOS/MS-Windows should note that, since @command{tac} reads files in
1341 binary mode, each line of a text file might end with a CR/LF pair
1342 instead of the Unix-style LF.
1344 @item -s @var{separator}
1345 @itemx --separator=@var{separator}
1347 @opindex --separator
1348 Use @var{separator} as the record separator, instead of newline.
1356 @section @command{nl}: Number lines and write files
1359 @cindex numbering lines
1360 @cindex line numbering
1362 @command{nl} writes each @var{file} (@samp{-} means standard input), or
1363 standard input if none are given, to standard output, with line numbers
1364 added to some or all of the lines. Synopsis:
1367 nl [@var{option}]@dots{} [@var{file}]@dots{}
1370 @cindex logical pages, numbering on
1371 @command{nl} decomposes its input into (logical) pages; by default, the
1372 line number is reset to 1 at the top of each logical page. @command{nl}
1373 treats all of the input files as a single document; it does not reset
1374 line numbers or logical pages between files.
1376 @cindex headers, numbering
1377 @cindex body, numbering
1378 @cindex footers, numbering
1379 A logical page consists of three sections: header, body, and footer.
1380 Any of the sections can be empty. Each can be numbered in a different
1381 style from the others.
1383 The beginnings of the sections of logical pages are indicated in the
1384 input file by a line containing exactly one of these delimiter strings:
1395 The two characters from which these strings are made can be changed from
1396 @samp{\} and @samp{:} via options (see below), but the pattern and
1397 length of each string cannot be changed.
1399 A section delimiter is replaced by an empty line on output. Any text
1400 that comes before the first section delimiter string in the input file
1401 is considered to be part of a body section, so @command{nl} treats a
1402 file that contains no section delimiters as a single body section.
1404 The program accepts the following options. Also see @ref{Common options}.
1408 @item -b @var{style}
1409 @itemx --body-numbering=@var{style}
1411 @opindex --body-numbering
1412 Select the numbering style for lines in the body section of each
1413 logical page. When a line is not numbered, the current line number
1414 is not incremented, but the line number separator character is still
1415 prepended to the line. The styles are:
1421 number only nonempty lines (default for body),
1423 do not number lines (default for header and footer),
1425 number only lines that contain a match for the basic regular
1426 expression @var{bre}.
1427 @xref{Regular Expressions, , Regular Expressions, grep, The GNU Grep Manual}.
1431 @itemx --section-delimiter=@var{cd}
1433 @opindex --section-delimiter
1434 @cindex section delimiters of pages
1435 Set the section delimiter characters to @var{cd}; default is
1436 @samp{\:}. If only @var{c} is given, the second remains @samp{:}.
1437 (Remember to protect @samp{\} or other metacharacters from shell
1438 expansion with quotes or extra backslashes.)
1440 @item -f @var{style}
1441 @itemx --footer-numbering=@var{style}
1443 @opindex --footer-numbering
1444 Analogous to @option{--body-numbering}.
1446 @item -h @var{style}
1447 @itemx --header-numbering=@var{style}
1449 @opindex --header-numbering
1450 Analogous to @option{--body-numbering}.
1452 @item -i @var{number}
1453 @itemx --page-increment=@var{number}
1455 @opindex --page-increment
1456 Increment line numbers by @var{number} (default 1).
1458 @item -l @var{number}
1459 @itemx --join-blank-lines=@var{number}
1461 @opindex --join-blank-lines
1462 @cindex empty lines, numbering
1463 @cindex blank lines, numbering
1464 Consider @var{number} (default 1) consecutive empty lines to be one
1465 logical line for numbering, and only number the last one. Where fewer
1466 than @var{number} consecutive empty lines occur, do not number them.
1467 An empty line is one that contains no characters, not even spaces
1470 @item -n @var{format}
1471 @itemx --number-format=@var{format}
1473 @opindex --number-format
1474 Select the line numbering format (default is @code{rn}):
1478 @opindex ln @r{format for @command{nl}}
1479 left justified, no leading zeros;
1481 @opindex rn @r{format for @command{nl}}
1482 right justified, no leading zeros;
1484 @opindex rz @r{format for @command{nl}}
1485 right justified, leading zeros.
1489 @itemx --no-renumber
1491 @opindex --no-renumber
1492 Do not reset the line number at the start of a logical page.
1494 @item -s @var{string}
1495 @itemx --number-separator=@var{string}
1497 @opindex --number-separator
1498 Separate the line number from the text line in the output with
1499 @var{string} (default is the TAB character).
1501 @item -v @var{number}
1502 @itemx --starting-line-number=@var{number}
1504 @opindex --starting-line-number
1505 Set the initial line number on each logical page to @var{number} (default 1).
1507 @item -w @var{number}
1508 @itemx --number-width=@var{number}
1510 @opindex --number-width
1511 Use @var{number} characters for line numbers (default 6).
1519 @section @command{od}: Write files in octal or other formats
1522 @cindex octal dump of files
1523 @cindex hex dump of files
1524 @cindex ASCII dump of files
1525 @cindex file contents, dumping unambiguously
1527 @command{od} writes an unambiguous representation of each @var{file}
1528 (@samp{-} means standard input), or standard input if none are given.
1532 od [@var{option}]@dots{} [@var{file}]@dots{}
1533 od [-abcdfilosx]@dots{} [@var{file}] [[+]@var{offset}[.][b]]
1534 od [@var{option}]@dots{} --traditional [@var{file}] [[+]@var{offset}[.][b] [[+]@var{label}[.][b]]]
1537 Each line of output consists of the offset in the input, followed by
1538 groups of data from the file. By default, @command{od} prints the offset in
1539 octal, and each group of file data is a C @code{short int}'s worth of input
1540 printed as a single octal number.
1542 If @var{offset} is given, it specifies how many input bytes to skip
1543 before formatting and writing. By default, it is interpreted as an
1544 octal number, but the optional trailing decimal point causes it to be
1545 interpretated as decimal. If no decimal is specified and the offset
1546 begins with @samp{0x} or @samp{0X} it is interpreted as a hexadecimal
1547 number. If there is a trailing @samp{b}, the number of bytes skipped
1548 will be @var{offset} multiplied by 512.
1550 If a command is of both the first and second forms, the second form is
1551 assumed if the last operand begins with @samp{+} or (if there are two
1552 operands) a digit. For example, in @samp{od foo 10} and @samp{od +10}
1553 the @samp{10} is an offset, whereas in @samp{od 10} the @samp{10} is a
1556 The program accepts the following options. Also see @ref{Common options}.
1560 @item -A @var{radix}
1561 @itemx --address-radix=@var{radix}
1563 @opindex --address-radix
1564 @cindex radix for file offsets
1565 @cindex file offset radix
1566 Select the base in which file offsets are printed. @var{radix} can
1567 be one of the following:
1577 none (do not print offsets).
1580 The default is octal.
1582 @item -j @var{bytes}
1583 @itemx --skip-bytes=@var{bytes}
1585 @opindex --skip-bytes
1586 Skip @var{bytes} input bytes before formatting and writing. If
1587 @var{bytes} begins with @samp{0x} or @samp{0X}, it is interpreted in
1588 hexadecimal; otherwise, if it begins with @samp{0}, in octal; otherwise,
1589 in decimal. Appending @samp{b} multiplies @var{bytes} by 512, @samp{k}
1590 by 1024, and @samp{m} by 1048576.
1592 @item -N @var{bytes}
1593 @itemx --read-bytes=@var{bytes}
1595 @opindex --read-bytes
1596 Output at most @var{bytes} bytes of the input. Prefixes and suffixes on
1597 @code{bytes} are interpreted as for the @option{-j} option.
1600 @itemx --strings[=@var{n}]
1603 @cindex string constants, outputting
1604 Instead of the normal output, output only @dfn{string constants}: at
1605 least @var{n} consecutive @acronym{ASCII} graphic characters,
1606 followed by a null (zero) byte.
1608 If @var{n} is omitted with @option{--strings}, the default is 3.
1611 @itemx --format=@var{type}
1614 Select the format in which to output the file data. @var{type} is a
1615 string of one or more of the below type indicator characters. If you
1616 include more than one type indicator character in a single @var{type}
1617 string, or use this option more than once, @command{od} writes one copy
1618 of each output line using each of the data types that you specified,
1619 in the order that you specified.
1621 Adding a trailing ``z'' to any type specification appends a display
1622 of the @acronym{ASCII} character representation of the printable characters
1623 to the output line generated by the type specification.
1629 @acronym{ASCII} character or backslash escape,
1642 The type @code{a} outputs things like @samp{sp} for space, @samp{nl} for
1643 newline, and @samp{nul} for a null (zero) byte. Type @code{c} outputs
1644 @samp{ }, @samp{\n}, and @code{\0}, respectively.
1647 Except for types @samp{a} and @samp{c}, you can specify the number
1648 of bytes to use in interpreting each number in the given data type
1649 by following the type indicator character with a decimal integer.
1650 Alternately, you can specify the size of one of the C compiler's
1651 built-in data types by following the type indicator character with
1652 one of the following characters. For integers (@samp{d}, @samp{o},
1653 @samp{u}, @samp{x}):
1666 For floating point (@code{f}):
1678 @itemx --output-duplicates
1680 @opindex --output-duplicates
1681 Output consecutive lines that are identical. By default, when two or
1682 more consecutive output lines would be identical, @command{od} outputs only
1683 the first line, and puts just an asterisk on the following line to
1684 indicate the elision.
1687 @itemx --width[=@var{n}]
1690 Dump @code{n} input bytes per output line. This must be a multiple of
1691 the least common multiple of the sizes associated with the specified
1694 If this option is not given at all, the default is 16. If @var{n} is
1695 omitted, the default is 32.
1699 The next several options are shorthands for format specifications.
1700 @sc{gnu} @command{od} accepts any combination of shorthands and format
1701 specification options. These options accumulate.
1707 Output as named characters. Equivalent to @samp{-t a}.
1711 Output as octal bytes. Equivalent to @samp{-t o1}.
1715 Output as @acronym{ASCII} characters or backslash escapes. Equivalent to
1720 Output as unsigned decimal two-byte units. Equivalent to @samp{-t u2}.
1724 Output as floats. Equivalent to @samp{-t fF}.
1728 Output as decimal ints. Equivalent to @samp{-t dI}.
1732 Output as decimal long ints. Equivalent to @samp{-t dL}.
1736 Output as octal two-byte units. Equivalent to @option{-t o2}.
1740 Output as decimal two-byte units. Equivalent to @option{-t d2}.
1744 Output as hexadecimal two-byte units. Equivalent to @samp{-t x2}.
1747 @opindex --traditional
1748 Recognize the non-option label argument that traditional @command{od}
1749 accepted. The following syntax:
1752 od --traditional [@var{file}] [[+]@var{offset}[.][b] [[+]@var{label}[.][b]]]
1756 can be used to specify at most one file and optional arguments
1757 specifying an offset and a pseudo-start address, @var{label}.
1758 The @var{label} argument is interpreted
1759 just like @var{offset}, but it specifies an initial pseudo-address. The
1760 pseudo-addresses are displayed in parentheses following any normal
1768 @node Formatting file contents
1769 @chapter Formatting file contents
1771 @cindex formatting file contents
1773 These commands reformat the contents of files.
1776 * fmt invocation:: Reformat paragraph text.
1777 * pr invocation:: Paginate or columnate files for printing.
1778 * fold invocation:: Wrap input lines to fit in specified width.
1782 @node fmt invocation
1783 @section @command{fmt}: Reformat paragraph text
1786 @cindex reformatting paragraph text
1787 @cindex paragraphs, reformatting
1788 @cindex text, reformatting
1790 @command{fmt} fills and joins lines to produce output lines of (at most)
1791 a given number of characters (75 by default). Synopsis:
1794 fmt [@var{option}]@dots{} [@var{file}]@dots{}
1797 @command{fmt} reads from the specified @var{file} arguments (or standard
1798 input if none are given), and writes to standard output.
1800 By default, blank lines, spaces between words, and indentation are
1801 preserved in the output; successive input lines with different
1802 indentation are not joined; tabs are expanded on input and introduced on
1805 @cindex line-breaking
1806 @cindex sentences and line-breaking
1807 @cindex Knuth, Donald E.
1808 @cindex Plass, Michael F.
1809 @command{fmt} prefers breaking lines at the end of a sentence, and tries to
1810 avoid line breaks after the first word of a sentence or before the last
1811 word of a sentence. A @dfn{sentence break} is defined as either the end
1812 of a paragraph or a word ending in any of @samp{.?!}, followed by two
1813 spaces or end of line, ignoring any intervening parentheses or quotes.
1814 Like @TeX{}, @command{fmt} reads entire ``paragraphs'' before choosing line
1815 breaks; the algorithm is a variant of that given by Donald E. Knuth
1816 and Michael F. Plass in ``Breaking Paragraphs Into Lines'',
1817 @cite{Software---Practice & Experience} @b{11}, 11 (November 1981),
1820 The program accepts the following options. Also see @ref{Common options}.
1825 @itemx --crown-margin
1827 @opindex --crown-margin
1828 @cindex crown margin
1829 @dfn{Crown margin} mode: preserve the indentation of the first two
1830 lines within a paragraph, and align the left margin of each subsequent
1831 line with that of the second line.
1834 @itemx --tagged-paragraph
1836 @opindex --tagged-paragraph
1837 @cindex tagged paragraphs
1838 @dfn{Tagged paragraph} mode: like crown margin mode, except that if
1839 indentation of the first line of a paragraph is the same as the
1840 indentation of the second, the first line is treated as a one-line
1846 @opindex --split-only
1847 Split lines only. Do not join short lines to form longer ones. This
1848 prevents sample lines of code, and other such ``formatted'' text from
1849 being unduly combined.
1852 @itemx --uniform-spacing
1854 @opindex --uniform-spacing
1855 Uniform spacing. Reduce spacing between words to one space, and spacing
1856 between sentences to two spaces.
1859 @itemx -w @var{width}
1860 @itemx --width=@var{width}
1861 @opindex -@var{width}
1864 Fill output lines up to @var{width} characters (default 75). @command{fmt}
1865 initially tries to make lines about 7% shorter than this, to give it
1866 room to balance line lengths.
1868 @item -p @var{prefix}
1869 @itemx --prefix=@var{prefix}
1870 Only lines beginning with @var{prefix} (possibly preceded by whitespace)
1871 are subject to formatting. The prefix and any preceding whitespace are
1872 stripped for the formatting and then re-attached to each formatted output
1873 line. One use is to format certain kinds of program comments, while
1874 leaving the code unchanged.
1882 @section @command{pr}: Paginate or columnate files for printing
1885 @cindex printing, preparing files for
1886 @cindex multicolumn output, generating
1887 @cindex merging files in parallel
1889 @command{pr} writes each @var{file} (@samp{-} means standard input), or
1890 standard input if none are given, to standard output, paginating and
1891 optionally outputting in multicolumn format; optionally merges all
1892 @var{file}s, printing all in parallel, one per column. Synopsis:
1895 pr [@var{option}]@dots{} [@var{file}]@dots{}
1899 By default, a 5-line header is printed at each page: two blank lines;
1900 a line with the date, the file name, and the page count; and two more
1901 blank lines. A footer of five blank lines is also printed.
1902 With the @option{-F}
1903 option, a 3-line header is printed: the leading two blank lines are
1904 omitted; no footer is used. The default @var{page_length} in both cases is 66
1905 lines. The default number of text lines changes from 56 (without @option{-F})
1906 to 63 (with @option{-F}). The text line of the header takes the form
1907 @samp{@var{date} @var{string} @var{page}}, with spaces inserted around
1908 @var{string} so that the line takes up the full @var{page_width}. Here,
1909 @var{date} is the date (see the @option{-D} or @option{--date-format}
1910 option for details), @var{string} is the centered header string, and
1911 @var{page} identifies the page number. The @env{LC_MESSAGES} locale
1912 category affects the spelling of @var{page}; in the default C locale, it
1913 is @samp{Page @var{number}} where @var{number} is the decimal page
1916 Form feeds in the input cause page breaks in the output. Multiple form
1917 feeds produce empty pages.
1919 Columns are of equal width, separated by an optional string (default
1920 is @samp{space}). For multicolumn output, lines will always be truncated to
1921 @var{page_width} (default 72), unless you use the @option{-J} option.
1923 column output no line truncation occurs by default. Use @option{-W} option to
1924 truncate lines in that case.
1926 The following changes were made in version 1.22i and apply to later
1927 versions of @command{pr}:
1928 @c FIXME: this whole section here sounds very awkward to me. I
1929 @c made a few small changes, but really it all needs to be redone. - Brian
1930 @c OK, I fixed another sentence or two, but some of it I just don't understand.
1935 Some small @var{letter options} (@option{-s}, @option{-w}) have been
1936 redefined for better @acronym{POSIX} compliance. The output of some further
1937 cases has been adapted to other Unix systems. These changes are not
1938 compatible with earlier versions of the program.
1941 Some @var{new capital letter} options (@option{-J}, @option{-S}, @option{-W})
1942 have been introduced to turn off unexpected interferences of small letter
1943 options. The @option{-N} option and the second argument @var{last_page}
1944 of @samp{+FIRST_PAGE} offer more flexibility. The detailed handling of
1945 form feeds set in the input files requires the @option{-T} option.
1948 Capital letter options override small letter ones.
1951 Some of the option-arguments (compare @option{-s}, @option{-e},
1952 @option{-i}, @option{-n}) cannot be specified as separate arguments from the
1953 preceding option letter (already stated in the @acronym{POSIX} specification).
1956 The program accepts the following options. Also see @ref{Common options}.
1960 @item +@var{first_page}[:@var{last_page}]
1961 @itemx --pages=@var{first_page}[:@var{last_page}]
1962 @c The two following @opindex lines evoke warnings because they contain `:'
1963 @c The `info' spec does not permit that. If we use those lines, we end
1964 @c up with truncated index entries that don't work.
1965 @c @opindex +@var{first_page}[:@var{last_page}]
1966 @c @opindex --pages=@var{first_page}[:@var{last_page}]
1967 @opindex +@var{page_range}
1968 @opindex --pages=@var{page_range}
1969 Begin printing with page @var{first_page} and stop with @var{last_page}.
1970 Missing @samp{:@var{last_page}} implies end of file. While estimating
1971 the number of skipped pages each form feed in the input file results
1972 in a new page. Page counting with and without @samp{+@var{first_page}}
1973 is identical. By default, counting starts with the first page of input
1974 file (not first page printed). Line numbering may be altered by @option{-N}
1978 @itemx --columns=@var{column}
1979 @opindex -@var{column}
1981 @cindex down columns
1982 With each single @var{file}, produce @var{column} columns of output
1983 (default is 1) and print columns down, unless @option{-a} is used. The
1984 column width is automatically decreased as @var{column} increases; unless
1985 you use the @option{-W/-w} option to increase @var{page_width} as well.
1986 This option might well cause some lines to be truncated. The number of
1987 lines in the columns on each page are balanced. The options @option{-e}
1988 and @option{-i} are on for multiple text-column output. Together with
1989 @option{-J} option column alignment and line truncation is turned off.
1990 Lines of full length are joined in a free field format and @option{-S}
1991 option may set field separators. @option{-@var{column}} may not be used
1992 with @option{-m} option.
1998 @cindex across columns
1999 With each single @var{file}, print columns across rather than down. The
2000 @option{-@var{column}} option must be given with @var{column} greater than one.
2001 If a line is too long to fit in a column, it is truncated.
2004 @itemx --show-control-chars
2006 @opindex --show-control-chars
2007 Print control characters using hat notation (e.g., @samp{^G}); print
2008 other nonprinting characters in octal backslash notation. By default,
2009 nonprinting characters are not changed.
2012 @itemx --double-space
2014 @opindex --double-space
2015 @cindex double spacing
2016 Double space the output.
2018 @item -D @var{format}
2019 @itemx --date-format=@var{format}
2020 @cindex time formats
2021 @cindex formatting times
2022 Format header dates using @var{format}, using the same conventions as
2023 for the the command @samp{date +@var{format}}; @xref{date invocation}.
2024 Except for directives, which start with
2025 @samp{%}, characters in @var{format} are printed unchanged. You can use
2026 this option to specify an arbitrary string in place of the header date,
2027 e.g., @option{--date-format="Monday morning"}.
2029 @vindex POSIXLY_CORRECT
2032 format defaults to @samp{%Y-%m-%d %H:%M} (for example, @samp{2001-12-04
2033 23:59}); but if the @env{POSIXLY_CORRECT} environment variable is set
2034 and the @env{LC_TIME} locale category specifies the @acronym{POSIX}
2035 locale, the default is @samp{%b %e %H:%M %Y} (for example,
2036 @samp{Dec@ @ 4 23:59 2001}.
2039 Time stamps are listed according to the time zone rules specified by
2040 the @env{TZ} environment variable, or by the system default rules if
2041 @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
2042 with @env{TZ}, libc, The GNU C Library}.
2044 @item -e[@var{in-tabchar}[@var{in-tabwidth}]]
2045 @itemx --expand-tabs[=@var{in-tabchar}[@var{in-tabwidth}]]
2047 @opindex --expand-tabs
2049 Expand @var{tab}s to spaces on input. Optional argument @var{in-tabchar} is
2050 the input tab character (default is the TAB character). Second optional
2051 argument @var{in-tabwidth} is the input tab character's width (default
2059 @opindex --form-feed
2060 Use a form feed instead of newlines to separate output pages. The default
2061 page length of 66 lines is not altered. But the number of lines of text
2062 per page changes from default 56 to 63 lines.
2064 @item -h @var{HEADER}
2065 @itemx --header=@var{HEADER}
2068 Replace the file name in the header with the centered string @var{header}.
2069 When using the shell, @var{header} should be quoted and should be
2070 separated from @option{-h} by a space.
2072 @item -i[@var{out-tabchar}[@var{out-tabwidth}]]
2073 @itemx --output-tabs[=@var{out-tabchar}[@var{out-tabwidth}]]
2075 @opindex --output-tabs
2077 Replace spaces with @var{tab}s on output. Optional argument @var{out-tabchar}
2078 is the output tab character (default is the TAB character). Second optional
2079 argument @var{out-tabwidth} is the output tab character's width (default
2085 @opindex --join-lines
2086 Merge lines of full length. Used together with the column options
2087 @option{-@var{column}}, @option{-a -@var{column}} or @option{-m}. Turns off
2088 @option{-W/-w} line truncation;
2089 no column alignment used; may be used with
2090 @option{--sep-string[=@var{string}]}. @option{-J} has been introduced
2091 (together with @option{-W} and @option{--sep-string})
2092 to disentangle the old (@acronym{POSIX}-compliant) options @option{-w} and
2093 @option{-s} along with the three column options.
2096 @item -l @var{page_length}
2097 @itemx --length=@var{page_length}
2100 Set the page length to @var{page_length} (default 66) lines, including
2101 the lines of the header [and the footer]. If @var{page_length} is less
2102 than or equal to 10 (or <= 3 with @option{-F}), the header and footer are
2103 omitted, and all form feeds set in input files are eliminated, as if
2104 the @option{-T} option had been given.
2110 Merge and print all @var{file}s in parallel, one in each column. If a
2111 line is too long to fit in a column, it is truncated, unless the @option{-J}
2112 option is used. @option{--sep-string[=@var{string}]} may be used.
2114 some @var{file}s (form feeds set) produce empty columns, still marked
2115 by @var{string}. The result is a continuous line numbering and column
2116 marking throughout the whole merged file. Completely empty merged pages
2117 show no separators or line numbers. The default header becomes
2118 @samp{@var{date} @var{page}} with spaces inserted in the middle; this
2119 may be used with the @option{-h} or @option{--header} option to fill up
2120 the middle blank part.
2122 @item -n[@var{number-separator}[@var{digits}]]
2123 @itemx --number-lines[=@var{number-separator}[@var{digits}]]
2125 @opindex --number-lines
2126 Provide @var{digits} digit line numbering (default for @var{digits} is
2127 5). With multicolumn output the number occupies the first @var{digits}
2128 column positions of each text column or only each line of @option{-m}
2129 output. With single column output the number precedes each line just as
2130 @option{-m} does. Default counting of the line numbers starts with the
2131 first line of the input file (not the first line printed, compare the
2132 @option{--page} option and @option{-N} option).
2133 Optional argument @var{number-separator} is the character appended to
2134 the line number to separate it from the text followed. The default
2135 separator is the TAB character. In a strict sense a TAB is always
2136 printed with single column output only. The @var{TAB}-width varies
2137 with the @var{TAB}-position, e.g., with the left @var{margin} specified
2138 by @option{-o} option. With multicolumn output priority is given to
2139 @samp{equal width of output columns} (a @acronym{POSIX} specification).
2140 The @var{TAB}-width is fixed to the value of the first column and does
2141 not change with different values of left @var{margin}. That means a
2142 fixed number of spaces is always printed in the place of the
2143 @var{number-separator tab}. The tabification depends upon the output
2146 @item -N @var{line_number}
2147 @itemx --first-line-number=@var{line_number}
2149 @opindex --first-line-number
2150 Start line counting with the number @var{line_number} at first line of
2151 first page printed (in most cases not the first line of the input file).
2153 @item -o @var{margin}
2154 @itemx --indent=@var{margin}
2157 @cindex indenting lines
2159 Indent each line with a margin @var{margin} spaces wide (default is zero).
2160 The total page width is the size of the margin plus the @var{page_width}
2161 set with the @option{-W/-w} option. A limited overflow may occur with
2162 numbered single column output (compare @option{-n} option).
2165 @itemx --no-file-warnings
2167 @opindex --no-file-warnings
2168 Do not print a warning message when an argument @var{file} cannot be
2169 opened. (The exit status will still be nonzero, however.)
2171 @item -s[@var{char}]
2172 @itemx --separator[=@var{char}]
2174 @opindex --separator
2175 Separate columns by a single character @var{char}. The default for
2176 @var{char} is the TAB character without @option{-w} and @samp{no
2177 character} with @option{-w}. Without @option{-s} the default separator
2178 @samp{space} is set. @option{-s[char]} turns off line truncation of all
2179 three column options (@option{-COLUMN}|@option{-a -COLUMN}|@option{-m}) unless
2180 @option{-w} is set. This is a @acronym{POSIX}-compliant formulation.
2183 @item -S@var{string}
2184 @itemx --sep-string[=@var{string}]
2186 @opindex --sep-string
2187 Use @var{string} to separate output columns. The @option{-S} option doesn't
2188 affect the @option{-W/-w} option, unlike the @option{-s} option which does. It
2189 does not affect line truncation or column alignment.
2190 Without @option{-S}, and with @option{-J}, @command{pr} uses the default output
2192 Without @option{-S} or @option{-J}, @command{pr} uses a @samp{space}
2193 (same as @option{-S"@w{ }"}). @option{--sep-string} with no
2194 @samp{=@var{string}} is equivalent to @option{--sep-string=""}.
2197 @itemx --omit-header
2199 @opindex --omit-header
2200 Do not print the usual header [and footer] on each page, and do not fill
2201 out the bottom of pages (with blank lines or a form feed). No page
2202 structure is produced, but form feeds set in the input files are retained.
2203 The predefined pagination is not changed. @option{-t} or @option{-T} may be
2204 useful together with other options; e.g.: @option{-t -e4}, expand TAB characters
2205 in the input file to 4 spaces but don't make any other changes. Use of
2206 @option{-t} overrides @option{-h}.
2209 @itemx --omit-pagination
2211 @opindex --omit-pagination
2212 Do not print header [and footer]. In addition eliminate all form feeds
2213 set in the input files.
2216 @itemx --show-nonprinting
2218 @opindex --show-nonprinting
2219 Print nonprinting characters in octal backslash notation.
2221 @item -w @var{page_width}
2222 @itemx --width=@var{page_width}
2225 Set page width to @var{page_width} characters for multiple text-column
2226 output only (default for @var{page_width} is 72). @option{-s[CHAR]} turns
2227 off the default page width and any line truncation and column alignment.
2228 Lines of full length are merged, regardless of the column options
2229 set. No @var{page_width} setting is possible with single column output.
2230 A @acronym{POSIX}-compliant formulation.
2232 @item -W @var{page_width}
2233 @itemx --page_width=@var{page_width}
2235 @opindex --page_width
2236 Set the page width to @var{page_width} characters. That's valid with and
2237 without a column option. Text lines are truncated, unless @option{-J}
2238 is used. Together with one of the three column options
2239 (@option{-@var{column}}, @option{-a -@var{column}} or @option{-m}) column
2240 alignment is always used. The separator options @option{-S} or @option{-s}
2241 don't affect the @option{-W} option. Default is 72 characters. Without
2242 @option{-W @var{page_width}} and without any of the column options NO line
2243 truncation is used (defined to keep downward compatibility and to meet
2244 most frequent tasks). That's equivalent to @option{-W 72 -J}. The header
2245 line is never truncated.
2252 @node fold invocation
2253 @section @command{fold}: Wrap input lines to fit in specified width
2256 @cindex wrapping long input lines
2257 @cindex folding long input lines
2259 @command{fold} writes each @var{file} (@option{-} means standard input), or
2260 standard input if none are given, to standard output, breaking long
2264 fold [@var{option}]@dots{} [@var{file}]@dots{}
2267 By default, @command{fold} breaks lines wider than 80 columns. The output
2268 is split into as many lines as necessary.
2270 @cindex screen columns
2271 @command{fold} counts screen columns by default; thus, a tab may count more
2272 than one column, backspace decreases the column count, and carriage
2273 return sets the column to zero.
2275 The program accepts the following options. Also see @ref{Common options}.
2283 Count bytes rather than columns, so that tabs, backspaces, and carriage
2284 returns are each counted as taking up one column, just like other
2291 Break at word boundaries: the line is broken after the last blank before
2292 the maximum line length. If the line contains no such blanks, the line
2293 is broken at the maximum line length as usual.
2295 @item -w @var{width}
2296 @itemx --width=@var{width}
2299 Use a maximum line length of @var{width} columns instead of 80.
2301 For compatibility @command{fold} supports an obsolete option syntax
2302 @option{-@var{width}}. New scripts should use @option{-w @var{width}}
2310 @node Output of parts of files
2311 @chapter Output of parts of files
2313 @cindex output of parts of files
2314 @cindex parts of files, output of
2316 These commands output pieces of the input.
2319 * head invocation:: Output the first part of files.
2320 * tail invocation:: Output the last part of files.
2321 * split invocation:: Split a file into fixed-size pieces.
2322 * csplit invocation:: Split a file into context-determined pieces.
2325 @node head invocation
2326 @section @command{head}: Output the first part of files
2329 @cindex initial part of files, outputting
2330 @cindex first part of files, outputting
2332 @command{head} prints the first part (10 lines by default) of each
2333 @var{file}; it reads from standard input if no files are given or
2334 when given a @var{file} of @option{-}. Synopsis:
2337 head [@var{option}]@dots{} [@var{file}]@dots{}
2340 If more than one @var{file} is specified, @command{head} prints a
2341 one-line header consisting of:
2344 ==> @var{file name} <==
2348 before the output for each @var{file}.
2350 The program accepts the following options. Also see @ref{Common options}.
2355 @itemx --bytes=@var{n}
2358 Print the first @var{n} bytes, instead of initial lines. Appending
2359 @samp{b} multiplies @var{n} by 512, @samp{k} by 1024, and @samp{m}
2361 However, if @var{n} starts with a @samp{-},
2362 print all but the last @var{n} bytes of each file.
2365 @itemx --lines=@var{n}
2368 Output the first @var{n} lines.
2369 However, if @var{n} starts with a @samp{-},
2370 print all but the last @var{n} lines of each file.
2378 Never print file name headers.
2384 Always print file name headers.
2388 For compatibility @command{head} also supports an obsolete option syntax
2389 @option{-@var{count}@var{options}}, which is recognized only if it is
2390 specified first. @var{count} is a decimal number optionally followed
2391 by a size letter (@samp{b}, @samp{k}, @samp{m}) as in @option{-c}, or
2392 @samp{l} to mean count by lines, or other option letters (@samp{cqv}).
2393 New scripts should use @option{-c @var{count}} or @option{-n
2394 @var{count}} instead.
2399 @node tail invocation
2400 @section @command{tail}: Output the last part of files
2403 @cindex last part of files, outputting
2405 @command{tail} prints the last part (10 lines by default) of each
2406 @var{file}; it reads from standard input if no files are given or
2407 when given a @var{file} of @samp{-}. Synopsis:
2410 tail [@var{option}]@dots{} [@var{file}]@dots{}
2413 If more than one @var{file} is specified, @command{tail} prints a
2414 one-line header consisting of:
2417 ==> @var{file name} <==
2421 before the output for each @var{file}.
2423 @cindex BSD @command{tail}
2424 @sc{gnu} @command{tail} can output any amount of data (some other versions of
2425 @command{tail} cannot). It also has no @option{-r} option (print in
2426 reverse), since reversing a file is really a different job from printing
2427 the end of a file; BSD @command{tail} (which is the one with @option{-r}) can
2428 only reverse files that are at most as large as its buffer, which is
2429 typically 32 KiB@. A more reliable and versatile way to reverse files is
2430 the @sc{gnu} @command{tac} command.
2432 If any option-argument is a number @var{n} starting with a @samp{+},
2433 @command{tail} begins printing with the @var{n}th item from the start of
2434 each file, instead of from the end.
2436 The program accepts the following options. Also see @ref{Common options}.
2440 @item -c @var{bytes}
2441 @itemx --bytes=@var{bytes}
2444 Output the last @var{bytes} bytes, instead of final lines. Appending
2445 @samp{b} multiplies @var{bytes} by 512, @samp{k} by 1024, and @samp{m}
2449 @itemx --follow[=@var{how}]
2452 @cindex growing files
2453 @vindex name @r{follow option}
2454 @vindex descriptor @r{follow option}
2455 Loop forever trying to read more characters at the end of the file,
2456 presumably because the file is growing. This option is ignored if
2457 no @var{file} operand is specified and standard input is a pipe.
2458 If more than one file is given, @command{tail} prints a header whenever it
2459 gets output from a different file, to indicate which file that output is
2462 There are two ways to specify how you'd like to track files with this option,
2463 but that difference is noticeable only when a followed file is removed or
2465 If you'd like to continue to track the end of a growing file even after
2466 it has been unlinked, use @option{--follow=descriptor}. This is the default
2467 behavior, but it is not useful if you're tracking a log file that may be
2468 rotated (removed or renamed, then reopened). In that case, use
2469 @option{--follow=name} to track the named file by reopening it periodically
2470 to see if it has been removed and recreated by some other program.
2472 No matter which method you use, if the tracked file is determined to have
2473 shrunk, @command{tail} prints a message saying the file has been truncated
2474 and resumes tracking the end of the file from the newly-determined endpoint.
2476 When a file is removed, @command{tail}'s behavior depends on whether it is
2477 following the name or the descriptor. When following by name, tail can
2478 detect that a file has been removed and gives a message to that effect,
2479 and if @option{--retry} has been specified it will continue checking
2480 periodically to see if the file reappears.
2481 When following a descriptor, tail does not detect that the file has
2482 been unlinked or renamed and issues no message; even though the file
2483 may no longer be accessible via its original name, it may still be
2486 The option values @samp{descriptor} and @samp{name} may be specified only
2487 with the long form of the option, not with @option{-f}.
2491 This option is the same as @option{--follow=name --retry}. That is, tail
2492 will attempt to reopen a file when it is removed. Should this fail, tail
2493 will keep trying until it becomes accessible again.
2497 This option is meaningful only when following by name.
2498 Without this option, when tail encounters a file that doesn't
2499 exist or is otherwise inaccessible, it reports that fact and
2500 never checks it again.
2502 @itemx --sleep-interval=@var{number}
2503 @opindex --sleep-interval
2504 Change the number of seconds to wait between iterations (the default is 1.0).
2505 During one iteration, every specified file is checked to see if it has
2507 Historical implementations of @command{tail} have required that
2508 @var{number} be an integer. However, GNU @command{tail} accepts
2509 an arbitrary floating point number (using a period before any
2512 @itemx --pid=@var{pid}
2514 When following by name or by descriptor, you may specify the process ID,
2515 @var{pid}, of the sole writer of all @var{file} arguments. Then, shortly
2516 after that process terminates, tail will also terminate. This will
2517 work properly only if the writer and the tailing process are running on
2518 the same machine. For example, to save the output of a build in a file
2519 and to watch the file grow, if you invoke @command{make} and @command{tail}
2520 like this then the tail process will stop when your build completes.
2521 Without this option, you would have had to kill the @code{tail -f}
2525 $ make >& makerr & tail --pid=$! -f makerr
2528 If you specify a @var{pid} that is not in use or that does not correspond
2529 to the process that is writing to the tailed files, then @command{tail}
2530 may terminate long before any @var{file}s stop growing or it may not
2531 terminate until long after the real writer has terminated.
2532 Note that @option{--pid} cannot be supported on some systems; @command{tail}
2533 will print a warning if this is the case.
2535 @itemx --max-unchanged-stats=@var{n}
2536 @opindex --max-unchanged-stats
2537 When tailing a file by name, if there have been @var{n} (default
2538 n=@value{DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS}) consecutive
2539 iterations for which the file has not changed, then
2540 @code{open}/@code{fstat} the file to determine if that file name is
2541 still associated with the same device/inode-number pair as before.
2542 When following a log file that is rotated, this is approximately the
2543 number of seconds between when tail prints the last pre-rotation lines
2544 and when it prints the lines that have accumulated in the new log file.
2545 This option is meaningful only when following by name.
2548 @itemx --lines=@var{n}
2551 Output the last @var{n} lines.
2559 Never print file name headers.
2565 Always print file name headers.
2569 For compatibility @command{tail} also supports an obsolete option
2570 syntax @option{-@var{count}[bcl][f]}, which is recognized only if it
2571 is specified first and does not conflict with the usage described
2572 above. @var{count} is an optional decimal number optionally
2573 followed by a size letter (@samp{b}, @samp{c}, @samp{l}) to mean count
2574 by 512-byte blocks, bytes, or lines, optionally followed by @samp{f}
2575 which has the same meaning as @option{-f}.
2576 New scripts should use @option{-c @var{count}[b]},
2577 @option{-n @var{count}}, and/or @option{-f} instead.
2579 @vindex _POSIX2_VERSION
2580 On older systems, the leading @samp{-} can be replaced by @samp{+} in
2581 the obsolete option syntax with the same meaning as in counts, and
2582 obsolete usage overrides normal usage when the two conflict.
2583 This obsolete behavior can be enabled or disabled with the
2584 @env{_POSIX2_VERSION} environment variable (@pxref{Standards
2585 conformance}), but portable scripts should avoid commands whose
2586 behavior depends on this variable.
2587 For example, use @samp{tail -- - main.c} or @samp{tail main.c} rather than
2588 the ambiguous @samp{tail - main.c}, @samp{tail -c4} or @samp{tail -c 10
2589 4} rather than the ambiguous @samp{tail -c 4}, and @samp{tail ./+4}
2590 or @samp{tail -n +4} rather than the ambiguous @samp{tail +4}.
2595 @node split invocation
2596 @section @command{split}: Split a file into fixed-size pieces
2599 @cindex splitting a file into pieces
2600 @cindex pieces, splitting a file into
2602 @command{split} creates output files containing consecutive sections of
2603 @var{input} (standard input if none is given or @var{input} is
2604 @samp{-}). Synopsis:
2607 split [@var{option}] [@var{input} [@var{prefix}]]
2610 By default, @command{split} puts 1000 lines of @var{input} (or whatever is
2611 left over for the last section), into each output file.
2613 @cindex output file name prefix
2614 The output files' names consist of @var{prefix} (@samp{x} by default)
2615 followed by a group of characters (@samp{aa}, @samp{ab}, @dots{} by
2616 default), such that concatenating the output files in traditional
2617 sorted order by file name produces
2618 the original input file. If the output file names are exhausted,
2619 @command{split} reports an error without deleting the output files
2622 The program accepts the following options. Also see @ref{Common options}.
2626 @item -a @var{length}
2627 @itemx --suffix-length=@var{length}
2629 @opindex --suffix-length
2630 Use suffixes of length @var{length}. The default @var{length} is 2.
2632 @item -l @var{lines}
2633 @itemx --lines=@var{lines}
2636 Put @var{lines} lines of @var{input} into each output file.
2638 For compatibility @command{split} also supports an obsolete
2639 option syntax @option{-@var{lines}}. New scripts should use @option{-l
2640 @var{lines}} instead.
2642 @item -b @var{bytes}
2643 @itemx --bytes=@var{bytes}
2646 Put the first @var{bytes} bytes of @var{input} into each output file.
2647 Appending @samp{b} multiplies @var{bytes} by 512, @samp{k} by 1024, and
2648 @samp{m} by 1048576.
2650 @item -C @var{bytes}
2651 @itemx --line-bytes=@var{bytes}
2653 @opindex --line-bytes
2654 Put into each output file as many complete lines of @var{input} as
2655 possible without exceeding @var{bytes} bytes. For lines longer than
2656 @var{bytes} bytes, put @var{bytes} bytes into each output file until
2657 less than @var{bytes} bytes of the line are left, then continue
2658 normally. @var{bytes} has the same format as for the @option{--bytes}
2662 @itemx --numeric-suffixes
2664 @opindex --numeric-suffixes
2665 Use digits in suffixes rather than lower-case letters.
2669 Write a diagnostic to standard error just before each output file is opened.
2676 @node csplit invocation
2677 @section @command{csplit}: Split a file into context-determined pieces
2680 @cindex context splitting
2681 @cindex splitting a file into pieces by context
2683 @command{csplit} creates zero or more output files containing sections of
2684 @var{input} (standard input if @var{input} is @samp{-}). Synopsis:
2687 csplit [@var{option}]@dots{} @var{input} @var{pattern}@dots{}
2690 The contents of the output files are determined by the @var{pattern}
2691 arguments, as detailed below. An error occurs if a @var{pattern}
2692 argument refers to a nonexistent line of the input file (e.g., if no
2693 remaining line matches a given regular expression). After every
2694 @var{pattern} has been matched, any remaining input is copied into one
2697 By default, @command{csplit} prints the number of bytes written to each
2698 output file after it has been created.
2700 The types of pattern arguments are:
2705 Create an output file containing the input up to but not including line
2706 @var{n} (a positive integer). If followed by a repeat count, also
2707 create an output file containing the next @var{n} lines of the input
2708 file once for each repeat.
2710 @item /@var{regexp}/[@var{offset}]
2711 Create an output file containing the current line up to (but not
2712 including) the next line of the input file that contains a match for
2713 @var{regexp}. The optional @var{offset} is an integer.
2714 If it is given, the input up to (but not including) the
2715 matching line plus or minus @var{offset} is put into the output file,
2716 and the line after that begins the next section of input.
2718 @item %@var{regexp}%[@var{offset}]
2719 Like the previous type, except that it does not create an output
2720 file, so that section of the input file is effectively ignored.
2722 @item @{@var{repeat-count}@}
2723 Repeat the previous pattern @var{repeat-count} additional
2724 times. The @var{repeat-count} can either be a positive integer or an
2725 asterisk, meaning repeat as many times as necessary until the input is
2730 The output files' names consist of a prefix (@samp{xx} by default)
2731 followed by a suffix. By default, the suffix is an ascending sequence
2732 of two-digit decimal numbers from @samp{00} to @samp{99}. In any case,
2733 concatenating the output files in sorted order by file name produces the
2734 original input file.
2736 By default, if @command{csplit} encounters an error or receives a hangup,
2737 interrupt, quit, or terminate signal, it removes any output files
2738 that it has created so far before it exits.
2740 The program accepts the following options. Also see @ref{Common options}.
2744 @item -f @var{prefix}
2745 @itemx --prefix=@var{prefix}
2748 @cindex output file name prefix
2749 Use @var{prefix} as the output file name prefix.
2751 @item -b @var{suffix}
2752 @itemx --suffix=@var{suffix}
2755 @cindex output file name suffix
2756 Use @var{suffix} as the output file name suffix. When this option is
2757 specified, the suffix string must include exactly one
2758 @code{printf(3)}-style conversion specification, possibly including
2759 format specification flags, a field width, a precision specifications,
2760 or all of these kinds of modifiers. The format letter must convert a
2761 binary integer argument to readable form; thus, only @samp{d}, @samp{i},
2762 @samp{u}, @samp{o}, @samp{x}, and @samp{X} conversions are allowed. The
2763 entire @var{suffix} is given (with the current output file number) to
2764 @code{sprintf(3)} to form the file name suffixes for each of the
2765 individual output files in turn. If this option is used, the
2766 @option{--digits} option is ignored.
2768 @item -n @var{digits}
2769 @itemx --digits=@var{digits}
2772 Use output file names containing numbers that are @var{digits} digits
2773 long instead of the default 2.
2778 @opindex --keep-files
2779 Do not remove output files when errors are encountered.
2782 @itemx --elide-empty-files
2784 @opindex --elide-empty-files
2785 Suppress the generation of zero-length output files. (In cases where
2786 the section delimiters of the input file are supposed to mark the first
2787 lines of each of the sections, the first output file will generally be a
2788 zero-length file unless you use this option.) The output file sequence
2789 numbers always run consecutively starting from 0, even when this option
2800 Do not print counts of output file sizes.
2807 @node Summarizing files
2808 @chapter Summarizing files
2810 @cindex summarizing files
2812 These commands generate just a few numbers representing entire
2816 * wc invocation:: Print newline, word, and byte counts.
2817 * sum invocation:: Print checksum and block counts.
2818 * cksum invocation:: Print CRC checksum and byte counts.
2819 * md5sum invocation:: Print or check message-digests.
2824 @section @command{wc}: Print newline, word, and byte counts
2828 @cindex character count
2832 @command{wc} counts the number of bytes, characters, whitespace-separated
2833 words, and newlines in each given @var{file}, or standard input if none
2834 are given or for a @var{file} of @samp{-}. Synopsis:
2837 wc [@var{option}]@dots{} [@var{file}]@dots{}
2840 @cindex total counts
2841 @command{wc} prints one line of counts for each file, and if the file was
2842 given as an argument, it prints the file name following the counts. If
2843 more than one @var{file} is given, @command{wc} prints a final line
2844 containing the cumulative counts, with the file name @file{total}. The
2845 counts are printed in this order: newlines, words, characters, bytes.
2846 Each count is printed right-justified in a field with at least one
2847 space between fields so that the numbers and file names normally line
2848 up nicely in columns. The width of the count fields varies depending
2849 on the inputs, so you should not depend on a particular field width.
2850 However, as a @acronym{GNU} extension, if only one count is printed,
2851 it is guaranteed to be printed without leading spaces.
2853 By default, @command{wc} prints three counts: the newline, words, and byte
2854 counts. Options can specify that only certain counts be printed.
2855 Options do not undo others previously given, so
2862 prints both the byte counts and the word counts.
2864 With the @option{--max-line-length} option, @command{wc} prints the length
2865 of the longest line per file, and if there is more than one file it
2866 prints the maximum (not the sum) of those lengths.
2868 The program accepts the following options. Also see @ref{Common options}.
2876 Print only the byte counts.
2882 Print only the character counts.
2888 Print only the word counts.
2894 Print only the newline counts.
2897 @itemx --max-line-length
2899 @opindex --max-line-length
2900 Print only the maximum line lengths.
2907 @node sum invocation
2908 @section @command{sum}: Print checksum and block counts
2911 @cindex 16-bit checksum
2912 @cindex checksum, 16-bit
2914 @command{sum} computes a 16-bit checksum for each given @var{file}, or
2915 standard input if none are given or for a @var{file} of @samp{-}. Synopsis:
2918 sum [@var{option}]@dots{} [@var{file}]@dots{}
2921 @command{sum} prints the checksum for each @var{file} followed by the
2922 number of blocks in the file (rounded up). If more than one @var{file}
2923 is given, file names are also printed (by default). (With the
2924 @option{--sysv} option, corresponding file names are printed when there is
2925 at least one file argument.)
2927 By default, @sc{gnu} @command{sum} computes checksums using an algorithm
2928 compatible with BSD @command{sum} and prints file sizes in units of
2931 The program accepts the following options. Also see @ref{Common options}.
2937 @cindex BSD @command{sum}
2938 Use the default (BSD compatible) algorithm. This option is included for
2939 compatibility with the System V @command{sum}. Unless @option{-s} was also
2940 given, it has no effect.
2946 @cindex System V @command{sum}
2947 Compute checksums using an algorithm compatible with System V
2948 @command{sum}'s default, and print file sizes in units of 512-byte blocks.
2952 @command{sum} is provided for compatibility; the @command{cksum} program (see
2953 next section) is preferable in new applications.
2958 @node cksum invocation
2959 @section @command{cksum}: Print CRC checksum and byte counts
2962 @cindex cyclic redundancy check
2963 @cindex CRC checksum
2965 @command{cksum} computes a cyclic redundancy check (CRC) checksum for each
2966 given @var{file}, or standard input if none are given or for a
2967 @var{file} of @samp{-}. Synopsis:
2970 cksum [@var{option}]@dots{} [@var{file}]@dots{}
2973 @command{cksum} prints the CRC checksum for each file along with the number
2974 of bytes in the file, and the file name unless no arguments were given.
2976 @command{cksum} is typically used to ensure that files
2977 transferred by unreliable means (e.g., netnews) have not been corrupted,
2978 by comparing the @command{cksum} output for the received files with the
2979 @command{cksum} output for the original files (typically given in the
2982 The CRC algorithm is specified by the @acronym{POSIX} standard. It is not
2983 compatible with the BSD or System V @command{sum} algorithms (see the
2984 previous section); it is more robust.
2986 The only options are @option{--help} and @option{--version}. @xref{Common
2992 @node md5sum invocation
2993 @section @command{md5sum}: Print or check message-digests
2996 @cindex 128-bit checksum
2997 @cindex checksum, 128-bit
2998 @cindex fingerprint, 128-bit
2999 @cindex message-digest, 128-bit
3001 @command{md5sum} computes a 128-bit checksum (or @dfn{fingerprint} or
3002 @dfn{message-digest}) for each specified @var{file}.
3003 If a @var{file} is specified as @samp{-} or if no files are given
3004 @command{md5sum} computes the checksum for the standard input.
3005 @command{md5sum} can also determine whether a file and checksum are
3006 consistent. Synopses:
3009 md5sum [@var{option}]@dots{} [@var{file}]@dots{}
3010 md5sum [@var{option}]@dots{} --check [@var{file}]
3013 For each @var{file}, @samp{md5sum} outputs the MD5 checksum, a flag
3014 indicating a binary or text input file, and the file name.
3015 If @var{file} is omitted or specified as @samp{-}, standard input is read.
3017 The program accepts the following options. Also see @ref{Common options}.
3025 @cindex binary input files
3026 Treat all input files as binary. This option has no effect on Unix
3027 systems, since they don't distinguish between binary and text files.
3028 This option is useful on systems that have different internal and
3029 external character representations. On MS-DOS and MS-Windows, this is
3034 Read file names and checksum information from the single @var{file}
3035 (or from stdin if no @var{file} was specified) and report whether
3036 each named file and the corresponding checksum data are consistent.
3037 The input to this mode of @command{md5sum} is usually the output of
3038 a prior, checksum-generating run of @samp{md5sum}.
3039 Each valid line of input consists of an MD5 checksum, a binary/text
3040 flag, and then a file name.
3041 Binary files are marked with @samp{*}, text with @samp{ }.
3042 For each such line, @command{md5sum} reads the named file and computes its
3043 MD5 checksum. Then, if the computed message digest does not match the
3044 one on the line with the file name, the file is noted as having
3045 failed the test. Otherwise, the file passes the test.
3046 By default, for each valid line, one line is written to standard
3047 output indicating whether the named file passed the test.
3048 After all checks have been performed, if there were any failures,
3049 a warning is issued to standard error.
3050 Use the @option{--status} option to inhibit that output.
3051 If any listed file cannot be opened or read, if any valid line has
3052 an MD5 checksum inconsistent with the associated file, or if no valid
3053 line is found, @command{md5sum} exits with nonzero status. Otherwise,
3054 it exits successfully.
3058 @cindex verifying MD5 checksums
3059 This option is useful only when verifying checksums.
3060 When verifying checksums, don't generate the default one-line-per-file
3061 diagnostic and don't output the warning summarizing any failures.
3062 Failures to open or read a file still evoke individual diagnostics to
3064 If all listed files are readable and are consistent with the associated
3065 MD5 checksums, exit successfully. Otherwise exit with a status code
3066 indicating there was a failure.
3072 @cindex text input files
3073 Treat all input files as text files. This is the reverse of
3080 @cindex verifying MD5 checksums
3081 When verifying checksums, warn about improperly formatted MD5 checksum lines.
3082 This option is useful only if all but a few lines in the checked input
3090 @node Operating on sorted files
3091 @chapter Operating on sorted files
3093 @cindex operating on sorted files
3094 @cindex sorted files, operations on
3096 These commands work with (or produce) sorted files.
3099 * sort invocation:: Sort text files.
3100 * uniq invocation:: Uniquify files.
3101 * comm invocation:: Compare two sorted files line by line.
3102 * ptx invocation:: Produce a permuted index of file contents.
3103 * tsort invocation:: Topological sort.
3104 * tsort background:: Where tsort came from.
3108 @node sort invocation
3109 @section @command{sort}: Sort text files
3112 @cindex sorting files
3114 @command{sort} sorts, merges, or compares all the lines from the given
3115 files, or standard input if none are given or for a @var{file} of
3116 @samp{-}. By default, @command{sort} writes the results to standard
3120 sort [@var{option}]@dots{} [@var{file}]@dots{}
3123 @command{sort} has three modes of operation: sort (the default), merge,
3124 and check for sortedness. The following options change the operation
3133 @cindex checking for sortedness
3134 Check whether the given files are already sorted: if they are not all
3135 sorted, print an error message and exit with a status of 1.
3136 Otherwise, exit successfully.
3142 @cindex merging sorted files
3143 Merge the given files by sorting them as a group. Each input file must
3144 always be individually sorted. It always works to sort instead of
3145 merge; merging is provided because it is faster, in the case where it
3150 @cindex sort stability
3151 @cindex sort's last-resort comparison
3152 A pair of lines is compared as follows:
3153 @command{sort} compares each pair of fields, in the
3154 order specified on the command line, according to the associated
3155 ordering options, until a difference is found or no fields are left.
3156 If no key fields are specified, @command{sort} uses a default key of
3157 the entire line. Finally, as a last resort when all keys compare
3158 equal, @command{sort} compares entire lines as if no ordering options
3159 other than @option{--reverse} (@option{-r}) were specified. The
3160 @option{--stable} (@option{-s}) option disables this @dfn{last-resort
3161 comparison} so that lines in which all fields compare equal are left
3162 in their original relative order. The @option{--unique}
3163 (@option{-u}) option also disables the last-resort comparison.
3167 Unless otherwise specified, all comparisons use the character collating
3168 sequence specified by the @env{LC_COLLATE} locale.@footnote{If you
3169 use a non-@acronym{POSIX} locale (e.g., by setting @env{LC_ALL}
3170 to @samp{en_US}), then @command{sort} may produce output that is sorted
3171 differently than you're accustomed to. In that case, set the @env{LC_ALL}
3172 environment variable to @samp{C}. Note that setting only @env{LC_COLLATE}
3173 has two problems. First, it is ineffective if @env{LC_ALL} is also set.
3174 Second, it has undefined behavior if @env{LC_CTYPE} (or @env{LANG}, if
3175 @env{LC_CTYPE} is unset) is set to an incompatible value. For example,
3176 you get undefined behavior if @env{LC_CTYPE} is @code{ja_JP.PCK} but
3177 @env{LC_COLLATE} is @code{en_US.UTF-8}.}
3179 @sc{gnu} @command{sort} (as specified for all @sc{gnu} utilities) has no
3180 limit on input line length or restrictions on bytes allowed within lines.
3181 In addition, if the final byte of an input file is not a newline, @sc{gnu}
3182 @command{sort} silently supplies one. A line's trailing newline is not
3183 part of the line for comparison purposes.
3185 @cindex exit status of @command{sort}
3189 0 if no error occurred
3190 1 if invoked with @option{-c} and the input is not properly sorted
3191 2 if an error occurred
3195 If the environment variable @env{TMPDIR} is set, @command{sort} uses its
3196 value as the directory for temporary files instead of @file{/tmp}. The
3197 @option{--temporary-directory} (@option{-T}) option in turn overrides
3198 the environment variable.
3201 The following options affect the ordering of output lines. They may be
3202 specified globally or as part of a specific key field. If no key
3203 fields are specified, global options apply to comparison of entire
3204 lines; otherwise the global options are inherited by key fields that do
3205 not specify any special options of their own. In pre-@acronym{POSIX}
3206 versions of @command{sort}, global options affect only later key fields,
3207 so portable shell scripts should specify global options first.
3212 @itemx --ignore-leading-blanks
3214 @opindex --ignore-leading-blanks
3215 @cindex blanks, ignoring leading
3217 Ignore leading blanks when finding sort keys in each line.
3218 The @env{LC_CTYPE} locale determines character types.
3221 @itemx --dictionary-order
3223 @opindex --dictionary-order
3224 @cindex dictionary order
3225 @cindex phone directory order
3226 @cindex telephone directory order
3228 Sort in @dfn{phone directory} order: ignore all characters except
3229 letters, digits and blanks when sorting.
3230 The @env{LC_CTYPE} locale determines character types.
3233 @itemx --ignore-case
3235 @opindex --ignore-case
3236 @cindex ignoring case
3237 @cindex case folding
3239 Fold lowercase characters into the equivalent uppercase characters when
3240 comparing so that, for example, @samp{b} and @samp{B} sort as equal.
3241 The @env{LC_CTYPE} locale determines character types.
3244 @itemx --general-numeric-sort
3246 @opindex --general-numeric-sort
3247 @cindex general numeric sort
3249 Sort numerically, using the standard C function @code{strtod} to convert
3250 a prefix of each line to a double-precision floating point number.
3251 This allows floating point numbers to be specified in scientific notation,
3252 like @code{1.0e-34} and @code{10e100}.
3253 The @env{LC_NUMERIC} locale determines the decimal-point character.
3254 Do not report overflow, underflow, or conversion errors.
3255 Use the following collating sequence:
3259 Lines that do not start with numbers (all considered to be equal).
3261 NaNs (``Not a Number'' values, in IEEE floating point arithmetic)
3262 in a consistent but machine-dependent order.
3266 Finite numbers in ascending numeric order (with @math{-0} and @math{+0} equal).
3271 Use this option only if there is no alternative; it is much slower than
3272 @option{--numeric-sort} (@option{-n}) and it can lose information when
3273 converting to floating point.
3276 @itemx --ignore-nonprinting
3278 @opindex --ignore-nonprinting
3279 @cindex nonprinting characters, ignoring
3280 @cindex unprintable characters, ignoring
3282 Ignore nonprinting characters.
3283 The @env{LC_CTYPE} locale determines character types.
3284 This option has no effect if the stronger @option{--dictionary-order}
3285 (@option{-d}) option is also given.
3290 @opindex --month-sort
3291 @cindex months, sorting by
3293 An initial string, consisting of any amount of blanks, followed
3294 by a month name abbreviation, is folded to UPPER case and
3295 compared in the order @samp{JAN} < @samp{FEB} < @dots{} < @samp{DEC}.
3296 Invalid names compare low to valid names. The @env{LC_TIME} locale
3297 category determines the month spellings.
3300 @itemx --numeric-sort
3302 @opindex --numeric-sort
3303 @cindex numeric sort
3305 Sort numerically: the number begins each line; specifically, it consists
3306 of optional blanks, an optional @samp{-} sign, and zero or more
3307 digits possibly separated by thousands separators, optionally followed
3308 by a decimal-point character and zero or more digits. A string of
3309 no digits is interpreted as @samp{0}. The @env{LC_NUMERIC}
3310 locale specifies the decimal-point character and thousands separator.
3312 Numeric sort uses what might be considered an unconventional method to
3313 compare strings representing floating point numbers. Rather than first
3314 converting each string to the C @code{double} type and then comparing
3315 those values, @command{sort} aligns the decimal-point characters in the
3316 two strings and compares the strings a character at a time. One benefit
3317 of using this approach is its speed. In practice this is much more
3318 efficient than performing the two corresponding string-to-double (or
3319 even string-to-integer) conversions and then comparing doubles. In
3320 addition, there is no corresponding loss of precision. Converting each
3321 string to @code{double} before comparison would limit precision to about
3322 16 digits on most systems.
3324 Neither a leading @samp{+} nor exponential notation is recognized.
3325 To compare such strings numerically, use the
3326 @option{--general-numeric-sort} (@option{-g}) option.
3332 @cindex reverse sorting
3333 Reverse the result of comparison, so that lines with greater key values
3334 appear earlier in the output instead of later.
3342 @item -k @var{pos1}[,@var{pos2}]
3343 @itemx --key=@var{pos1}[,@var{pos2}]
3347 Specify a sort field that consists of the part of the line between
3348 @var{pos1} and @var{pos2} (or the end of the line, if @var{pos2} is
3349 omitted), @emph{inclusive}. Fields and character positions are numbered
3350 starting with 1. So to sort on the second field, you'd use
3351 @option{--key=2,2} (@option{-k 2,2}). See below for more examples.
3353 @item -o @var{output-file}
3354 @itemx --output=@var{output-file}
3357 @cindex overwriting of input, allowed
3358 Write output to @var{output-file} instead of standard output.
3359 Normally, @command{sort} reads all input before opening
3360 @var{output-file}, so you can safely sort a file in place by using
3361 commands like @code{sort -o F F} and @code{cat F | sort -o F}.
3362 However, @command{sort} with @option{--merge} (@option{-m}) can open
3363 the output file before reading all input, so a command like @code{cat
3364 F | sort -m -o F - G} is not safe as @command{sort} might start
3365 writing @file{F} before @command{cat} is done reading it.
3367 @vindex POSIXLY_CORRECT
3368 On newer systems, @option{-o} cannot appear after an input file if
3369 @env{POSIXLY_CORRECT} is set, e.g., @samp{sort F -o F}. Portable
3370 scripts should specify @option{-o @var{output-file}} before any input
3377 @cindex sort stability
3378 @cindex sort's last-resort comparison
3380 Make @command{sort} stable by disabling its last-resort comparison.
3381 This option has no effect if no fields or global ordering options
3382 other than @option{--reverse} (@option{-R}) are specified.
3385 @itemx --buffer-size=@var{size}
3387 @opindex --buffer-size
3388 @cindex size for main memory sorting
3389 Use a main-memory sort buffer of the given @var{size}. By default,
3390 @var{size} is in units of 1024 bytes. Appending @samp{%} causes
3391 @var{size} to be interpreted as a percentage of physical memory.
3392 Appending @samp{K} multiplies @var{size} by 1024 (the default),
3393 @samp{M} by 1,048,576, @samp{G} by 1,073,741,824, and so on for
3394 @samp{T}, @samp{P}, @samp{E}, @samp{Z}, and @samp{Y}. Appending
3395 @samp{b} causes @var{size} to be interpreted as a byte count, with no
3398 This option can improve the performance of @command{sort} by causing it
3399 to start with a larger or smaller sort buffer than the default.
3400 However, this option affects only the initial buffer size. The buffer
3401 grows beyond @var{size} if @command{sort} encounters input lines larger
3404 @item -t @var{separator}
3405 @itemx --field-separator=@var{separator}
3407 @opindex --field-separator
3408 @cindex field separator character
3409 Use character @var{separator} as the field separator when finding the
3410 sort keys in each line. By default, fields are separated by the empty
3411 string between a non-blank character and a blank character.
3412 That is, given the input line @w{@samp{ foo bar}}, @command{sort} breaks it
3413 into fields @w{@samp{ foo}} and @w{@samp{ bar}}. The field separator is
3414 not considered to be part of either the field preceding or the field
3415 following, so with @samp{sort @w{-t " "}} the same input line has
3416 three fields: an empty field, @samp{foo}, and @samp{bar}.
3417 However, fields that extend to the end of the line,
3418 as @option{-k 2}, or fields consisting of a range, as @option{-k 2,3},
3419 retain the field separators present between the endpoints of the range.
3421 To specify a null character (@acronym{ASCII} @sc{nul}) as
3422 the field separator, use the two-character string @samp{\0}, e.g.,
3423 @samp{sort -t '\0'}.
3425 @item -T @var{tempdir}
3426 @itemx --temporary-directory=@var{tempdir}
3428 @opindex --temporary-directory
3429 @cindex temporary directory
3431 Use directory @var{tempdir} to store temporary files, overriding the
3432 @env{TMPDIR} environment variable. If this option is given more than
3433 once, temporary files are stored in all the directories given. If you
3434 have a large sort or merge that is I/O-bound, you can often improve
3435 performance by using this option to specify directories on different
3436 disks and controllers.
3442 @cindex uniquifying output
3444 Normally, output only the first of a sequence of lines that compare
3445 equal. For the @option{--check} (@option{-c}) option,
3446 check that no pair of consecutive lines compares equal.
3448 This option also disables the default last-resort comparison.
3450 The commands @code{sort -u} and @code{sort | uniq} are equivalent, but
3451 this equivalence does not extend to arbitrary @command{sort} options.
3452 For example, @code{sort -n -u} inspects only the value of the initial
3453 numeric string when checking for uniqueness, whereas @code{sort -n |
3454 uniq} inspects the entire line. @xref{uniq invocation}.
3457 @itemx --zero-terminated
3459 @opindex --zero-terminated
3460 @cindex sort zero-terminated lines
3461 Treat the input as a set of lines, each terminated by a null character
3462 (@acronym{ASCII} @sc{nul}) instead of a line feed
3463 (@acronym{ASCII} @sc{lf}).
3464 This option can be useful in conjunction with @samp{perl -0} or
3465 @samp{find -print0} and @samp{xargs -0} which do the same in order to
3466 reliably handle arbitrary file names (even those containing blanks
3467 or other special characters).
3471 Historical (BSD and System V) implementations of @command{sort} have
3472 differed in their interpretation of some options, particularly
3473 @option{-b}, @option{-f}, and @option{-n}. @sc{gnu} sort follows the @acronym{POSIX}
3474 behavior, which is usually (but not always!) like the System V behavior.
3475 According to @acronym{POSIX}, @option{-n} no longer implies @option{-b}. For
3476 consistency, @option{-M} has been changed in the same way. This may
3477 affect the meaning of character positions in field specifications in
3478 obscure cases. The only fix is to add an explicit @option{-b}.
3480 A position in a sort field specified with the @option{-k}
3481 option has the form @samp{@var{f}.@var{c}}, where @var{f} is the number
3482 of the field to use and @var{c} is the number of the first character
3483 from the beginning of the field. In a start position, an omitted
3484 @samp{.@var{c}} stands for the field's first character. In an end
3485 position, an omitted or zero @samp{.@var{c}} stands for the field's
3486 last character. If the start field falls after the end of the line
3487 or after the end field, the field is empty. If the
3488 @option{-b} option was specified, the @samp{.@var{c}} part of a field
3489 specification is counted from the first nonblank character of the field.
3491 A sort key position may also have any of the option letters @samp{Mbdfinr}
3492 appended to it, in which case the global ordering options are not used
3493 for that particular field. The @option{-b} option may be independently
3494 attached to either or both of the start and
3495 end positions of a field specification, and if it is inherited
3496 from the global options it will be attached to both.
3497 If input lines can contain leading or adjacent blanks and @option{-t}
3498 is not used, then @option{-k} is typically combined with @option{-b},
3499 @option{-g}, @option{-M}, or @option{-n}; otherwise the varying
3500 numbers of leading blanks in fields can cause confusing results.
3502 Keys can span multiple fields.
3504 @vindex _POSIX2_VERSION
3505 On older systems, @command{sort} supports an obsolete origin-zero
3506 syntax @samp{+@var{pos1} [-@var{pos2}]} for specifying sort keys.
3507 This obsolete behavior can be enabled or disabled with the
3508 @env{_POSIX2_VERSION} environment variable (@pxref{Standards
3509 conformance}), but portable scripts should avoid commands whose
3510 behavior depends on this variable.
3511 For example, use @samp{sort ./+2} or @samp{sort -k 3} rather than
3512 the ambiguous @samp{sort +2}.
3514 Here are some examples to illustrate various combinations of options.
3519 Sort in descending (reverse) numeric order.
3526 Sort alphabetically, omitting the first and second fields
3527 and the blanks at the start of the third field.
3528 This uses a single key composed of the characters beginning
3529 at the start of the first nonblank character in field three
3530 and extending to the end of each line.
3537 Sort numerically on the second field and resolve ties by sorting
3538 alphabetically on the third and fourth characters of field five.
3539 Use @samp{:} as the field delimiter.
3542 sort -t : -k 2,2n -k 5.3,5.4
3545 Note that if you had written @option{-k 2n} instead of @option{-k 2,2n}
3546 @command{sort} would have used all characters beginning in the second field
3547 and extending to the end of the line as the primary @emph{numeric}
3548 key. For the large majority of applications, treating keys spanning
3549 more than one field as numeric will not do what you expect.
3551 Also note that the @samp{n} modifier was applied to the field-end
3552 specifier for the first key. It would have been equivalent to
3553 specify @option{-k 2n,2} or @option{-k 2n,2n}. All modifiers except
3554 @samp{b} apply to the associated @emph{field}, regardless of whether
3555 the modifier character is attached to the field-start and/or the
3556 field-end part of the key specifier.
3559 Sort the password file on the fifth field and ignore any
3560 leading blanks. Sort lines with equal values in field five
3561 on the numeric user ID in field three. Fields are separated
3565 sort -t : -k 5b,5 -k 3,3n /etc/passwd
3566 sort -t : -n -k 5b,5 -k 3,3 /etc/passwd
3567 sort -t : -b -k 5,5 -k 3,3n /etc/passwd
3570 These three commands have equivalent effect. The first specifies that
3571 the first key's start position ignores leading blanks and the second
3572 key is sorted numerically. The other two commands rely on global
3573 options being inherited by sort keys that lack modifiers. The inheritance
3574 works in this case because @option{-k 5b,5b} and @option{-k 5b,5} are
3575 equivalent, as the location of a field-end lacking a @samp{.@var{c}}
3576 character position is not affected by whether initial blanks are
3580 Sort a set of log files, primarily by IPv4 address and secondarily by
3581 time stamp. If two lines' primary and secondary keys are identical,
3582 output the lines in the same order that they were input. The log
3583 files contain lines that look like this:
3586 4.150.156.3 - - [01/Apr/2004:06:31:51 +0000] message 1
3587 211.24.3.231 - - [24/Apr/2004:20:17:39 +0000] message 2
3590 Fields are separated by exactly one space. Sort IPv4 addresses
3591 lexicographically, e.g., 212.61.52.2 sorts before 212.129.233.201
3592 because 61 is less than 129.
3595 sort -s -t ' ' -k 4.9n -k 4.5M -k 4.2n -k 4.14,4.21 file*.log |
3596 sort -s -t '.' -k 1,1n -k 2,2n -k 3,3n -k 4,4n
3599 This example cannot be done with a single @command{sort} invocation,
3600 since IPv4 address components are separated by @samp{.} while dates
3601 come just after a space. So it is broken down into two invocations of
3602 @command{sort}: the first sorts by time stamp and the second by IPv4
3603 address. The time stamp is sorted by year, then month, then day, and
3604 finally by hour-minute-second field, using @option{-k} to isolate each
3605 field. Except for hour-minute-second there's no need to specify the
3606 end of each key field, since the @samp{n} and @samp{M} modifiers sort
3607 based on leading prefixes that cannot cross field boundaries. The
3608 IPv4 addresses are sorted lexicographically. The second sort uses
3609 @samp{-s} so that ties in the primary key are broken by the secondary
3610 key; the first sort uses @samp{-s} so that the combination of the two
3614 Generate a tags file in case-insensitive sorted order.
3617 find src -type f -print0 | sort -z -f | xargs -0 etags --append
3620 The use of @option{-print0}, @option{-z}, and @option{-0} in this case means
3621 that file names that contain blanks or other special characters are
3623 by the sort operation.
3625 @c This example is a bit contrived and needs more explanation.
3627 @c Sort records separated by an arbitrary string by using a pipe to convert
3628 @c each record delimiter string to @samp{\0}, then using sort's -z option,
3629 @c and converting each @samp{\0} back to the original record delimiter.
3632 @c printf 'c\n\nb\n\na\n'|perl -0pe 's/\n\n/\n\0/g'|sort -z|perl -0pe 's/\0/\n/g'
3638 @node uniq invocation
3639 @section @command{uniq}: Uniquify files
3642 @cindex uniquify files
3644 @command{uniq} writes the unique lines in the given @file{input}, or
3645 standard input if nothing is given or for an @var{input} name of
3649 uniq [@var{option}]@dots{} [@var{input} [@var{output}]]
3652 By default, @command{uniq} prints its input lines, except that
3653 it discards all but the first of adjacent repeated lines, so that
3654 no output lines are repeated. Optionally, it can instead discard
3655 lines that are not repeated, or all repeated lines.
3657 The input need not be sorted, but repeated input lines are detected
3658 only if they are adjacent. If you want to discard non-adjacent
3659 duplicate lines, perhaps you want to use @code{sort -u}.
3660 @xref{sort invocation}.
3663 Comparisons use the character collating sequence specified by the
3664 @env{LC_COLLATE} locale category.
3666 If no @var{output} file is specified, @command{uniq} writes to standard
3669 The program accepts the following options. Also see @ref{Common options}.
3674 @itemx --skip-fields=@var{n}
3676 @opindex --skip-fields
3677 Skip @var{n} fields on each line before checking for uniqueness. Use
3678 a null string for comparison if a line has fewer than @var{n} fields. Fields
3679 are sequences of non-space non-tab characters that are separated from
3680 each other by at least one space or tab.
3682 For compatibility @command{uniq} supports an obsolete option syntax
3683 @option{-@var{n}}. New scripts should use @option{-f @var{n}} instead.
3686 @itemx --skip-chars=@var{n}
3688 @opindex --skip-chars
3689 Skip @var{n} characters before checking for uniqueness. Use a null string
3690 for comparison if a line has fewer than @var{n} characters. If you use both
3691 the field and character skipping options, fields are skipped over first.
3693 @vindex _POSIX2_VERSION
3694 On older systems, @command{uniq} supports an obsolete option syntax
3696 This obsolete behavior can be enabled or disabled with the
3697 @env{_POSIX2_VERSION} environment variable (@pxref{Standards
3698 conformance}), but portable scripts should avoid commands whose
3699 behavior depends on this variable.
3700 For example, use @samp{uniq ./+10} or @samp{uniq -s 10} rather than
3701 the ambiguous @samp{uniq +10}.
3707 Print the number of times each line occurred along with the line.
3710 @itemx --ignore-case
3712 @opindex --ignore-case
3713 Ignore differences in case when comparing lines.
3719 @cindex repeated lines, outputting
3720 Discard lines that are not repeated. When used by itself, this option
3721 causes @command{uniq} to print the first copy of each repeated line,
3725 @itemx --all-repeated[=@var{delimit-method}]
3727 @opindex --all-repeated
3728 @cindex all repeated lines, outputting
3729 Do not discard the second and subsequent repeated input lines,
3730 but discard lines that are not repeated.
3731 This option is useful mainly in conjunction with other options e.g.,
3732 to ignore case or to compare only selected fields.
3733 The optional @var{delimit-method} tells how to delimit
3734 groups of repeated lines, and must be one of the following:
3739 Do not delimit groups of repeated lines.
3740 This is equivalent to @option{--all-repeated} (@option{-D}).
3743 Output a newline before each group of repeated lines.
3746 Separate groups of repeated lines with a single newline.
3747 This is the same as using @samp{prepend}, except that
3748 there is no newline before the first group, and hence
3749 may be better suited for output direct to users.
3752 Note that when groups are delimited and the input stream contains
3753 two or more consecutive blank lines, then the output is ambiguous.
3754 To avoid that, filter the input through @samp{tr -s '\n'} to replace
3755 each sequence of consecutive newlines with a single newline.
3757 This is a @sc{gnu} extension.
3758 @c FIXME: give an example showing *how* it's useful
3764 @cindex unique lines, outputting
3765 Discard the first repeated line. When used by itself, this option
3766 causes @command{uniq} to print unique lines, and nothing else.
3769 @itemx --check-chars=@var{n}
3771 @opindex --check-chars
3772 Compare at most @var{n} characters on each line (after skipping any specified
3773 fields and characters). By default the entire rest of the lines are
3781 @node comm invocation
3782 @section @command{comm}: Compare two sorted files line by line
3785 @cindex line-by-line comparison
3786 @cindex comparing sorted files
3788 @command{comm} writes to standard output lines that are common, and lines
3789 that are unique, to two input files; a file name of @samp{-} means
3790 standard input. Synopsis:
3793 comm [@var{option}]@dots{} @var{file1} @var{file2}
3797 Before @command{comm} can be used, the input files must be sorted using the
3798 collating sequence specified by the @env{LC_COLLATE} locale.
3799 If an input file ends in a non-newline
3800 character, a newline is silently appended. The @command{sort} command with
3801 no options always outputs a file that is suitable input to @command{comm}.
3803 @cindex differing lines
3804 @cindex common lines
3805 With no options, @command{comm} produces three-column output. Column one
3806 contains lines unique to @var{file1}, column two contains lines unique
3807 to @var{file2}, and column three contains lines common to both files.
3808 Columns are separated by a single TAB character.
3809 @c FIXME: when there's an option to supply an alternative separator
3810 @c string, append `by default' to the above sentence.
3815 The options @option{-1}, @option{-2}, and @option{-3} suppress printing of
3816 the corresponding columns. Also see @ref{Common options}.
3818 Unlike some other comparison utilities, @command{comm} has an exit
3819 status that does not depend on the result of the comparison.
3820 Upon normal completion @command{comm} produces an exit code of zero.
3821 If there is an error it exits with nonzero status.
3824 @node tsort invocation
3825 @section @command{tsort}: Topological sort
3828 @cindex topological sort
3830 @command{tsort} performs a topological sort on the given @var{file}, or
3831 standard input if no input file is given or for a @var{file} of
3832 @samp{-}. For more details and some history, see @ref{tsort background}.
3836 tsort [@var{option}] [@var{file}]
3839 @command{tsort} reads its input as pairs of strings, separated by blanks,
3840 indicating a partial ordering. The output is a total ordering that
3841 corresponds to the given partial ordering.
3855 will produce the output
3866 Consider a more realistic example.
3867 You have a large set of functions all in one file, and they may all be
3868 declared static except one. Currently that one (say @code{main}) is the
3869 first function defined in the file, and the ones it calls directly follow
3870 it, followed by those they call, etc. Let's say that you are determined
3871 to take advantage of prototypes, so you have to choose between declaring
3872 all of those functions (which means duplicating a lot of information from
3873 the definitions) and rearranging the functions so that as many as possible
3874 are defined before they are used. One way to automate the latter process
3875 is to get a list for each function of the functions it calls directly.
3876 Many programs can generate such lists. They describe a call graph.
3877 Consider the following list, in which a given line indicates that the
3878 function on the left calls the one on the right directly.
3884 tail_file pretty_name
3885 tail_file write_header
3887 tail_forever recheck
3888 tail_forever pretty_name
3889 tail_forever write_header
3890 tail_forever dump_remainder
3893 tail_lines start_lines
3894 tail_lines dump_remainder
3895 tail_lines file_lines
3896 tail_lines pipe_lines
3898 tail_bytes start_bytes
3899 tail_bytes dump_remainder
3900 tail_bytes pipe_bytes
3901 file_lines dump_remainder
3905 then you can use @command{tsort} to produce an ordering of those
3906 functions that satisfies your requirement.
3909 example$ tsort call-graph | tac
3929 @command{tsort} detects any cycles in the input and writes the first cycle
3930 encountered to standard error.
3932 Note that for a given partial ordering, generally there is no unique
3933 total ordering. In the context of the call graph above, the function
3934 @code{parse_options} may be placed anywhere in the list as long as it
3935 precedes @code{main}.
3937 The only options are @option{--help} and @option{--version}. @xref{Common
3940 @node tsort background
3941 @section @command{tsort}: Background
3943 @command{tsort} exists because very early versions of the Unix linker processed
3944 an archive file exactly once, and in order. As @command{ld} read each object
3945 in the archive, it decided whether it was needed in the program based on
3946 whether it defined any symbols which were undefined at that point in
3949 This meant that dependencies within the archive had to be handled
3950 specially. For example, @code{scanf} probably calls @code{read}. That means
3951 that in a single pass through an archive, it was important for @code{scanf.o}
3952 to appear before read.o, because otherwise a program which calls
3953 @code{scanf} but not @code{read} might end up with an unexpected unresolved
3954 reference to @code{read}.
3956 The way to address this problem was to first generate a set of
3957 dependencies of one object file on another. This was done by a shell
3958 script called @command{lorder}. The GNU tools don't provide a version of
3959 lorder, as far as I know, but you can still find it in BSD
3962 Then you ran @command{tsort} over the @command{lorder} output, and you used the
3963 resulting sort to define the order in which you added objects to the archive.
3965 This whole procedure has been obsolete since about 1980, because
3966 Unix archives now contain a symbol table (traditionally built by
3967 @command{ranlib}, now generally built by @command{ar} itself), and the Unix
3968 linker uses the symbol table to effectively make multiple passes over
3971 Anyhow, that's where tsort came from. To solve an old problem with
3972 the way the linker handled archive files, which has since been solved
3978 @node ptx invocation
3979 @section @command{ptx}: Produce permuted indexes
3983 @command{ptx} reads a text file and essentially produces a permuted index, with
3984 each keyword in its context. The calling sketch is either one of:
3987 ptx [@var{option} @dots{}] [@var{file} @dots{}]
3988 ptx -G [@var{option} @dots{}] [@var{input} [@var{output}]]
3991 The @option{-G} (or its equivalent: @option{--traditional}) option disables
3992 all @sc{gnu} extensions and reverts to traditional mode, thus introducing some
3993 limitations and changing several of the program's default option values.
3994 When @option{-G} is not specified, @sc{gnu} extensions are always enabled.
3995 @sc{gnu} extensions to @command{ptx} are documented wherever appropriate in this
3996 document. For the full list, see @xref{Compatibility in ptx}.
3998 Individual options are explained in the following sections.
4000 When @sc{gnu} extensions are enabled, there may be zero, one or several
4001 @var{file}s after the options. If there is no @var{file}, the program
4002 reads the standard input. If there is one or several @var{file}s, they
4003 give the name of input files which are all read in turn, as if all the
4004 input files were concatenated. However, there is a full contextual
4005 break between each file and, when automatic referencing is requested,
4006 file names and line numbers refer to individual text input files. In
4007 all cases, the program outputs the permuted index to the standard
4010 When @sc{gnu} extensions are @emph{not} enabled, that is, when the program
4011 operates in traditional mode, there may be zero, one or two parameters
4012 besides the options. If there are no parameters, the program reads the
4013 standard input and outputs the permuted index to the standard output.
4014 If there is only one parameter, it names the text @var{input} to be read
4015 instead of the standard input. If two parameters are given, they give
4016 respectively the name of the @var{input} file to read and the name of
4017 the @var{output} file to produce. @emph{Be very careful} to note that,
4018 in this case, the contents of file given by the second parameter is
4019 destroyed. This behavior is dictated by System V @command{ptx}
4020 compatibility; @sc{gnu} Standards normally discourage output parameters not
4021 introduced by an option.
4023 Note that for @emph{any} file named as the value of an option or as an
4024 input text file, a single dash @kbd{-} may be used, in which case
4025 standard input is assumed. However, it would not make sense to use this
4026 convention more than once per program invocation.
4029 * General options in ptx:: Options which affect general program behavior.
4030 * Charset selection in ptx:: Underlying character set considerations.
4031 * Input processing in ptx:: Input fields, contexts, and keyword selection.
4032 * Output formatting in ptx:: Types of output format, and sizing the fields.
4033 * Compatibility in ptx::
4037 @node General options in ptx
4038 @subsection General options
4044 Print a short note about the copyright and copying conditions, then
4045 exit without further processing.
4048 @itemx --traditional
4049 As already explained, this option disables all @sc{gnu} extensions to
4050 @command{ptx} and switches to traditional mode.
4053 Print a short help on standard output, then exit without further
4057 Print the program version on standard output, then exit without further
4065 @node Charset selection in ptx
4066 @subsection Charset selection
4068 @c FIXME: People don't necessarily know what an IBM-PC was these days.
4069 As it is set up now, the program assumes that the input file is coded
4070 using 8-bit ISO 8859-1 code, also known as Latin-1 character set,
4071 @emph{unless} it is compiled for MS-DOS, in which case it uses the
4072 character set of the IBM-PC@. (@sc{gnu} @command{ptx} is not known to work on
4073 smaller MS-DOS machines anymore.) Compared to 7-bit @acronym{ASCII}, the set
4074 of characters which are letters is different; this alters the behavior
4075 of regular expression matching. Thus, the default regular expression
4076 for a keyword allows foreign or diacriticized letters. Keyword sorting,
4077 however, is still crude; it obeys the underlying character set ordering
4083 @itemx --ignore-case
4084 Fold lower case letters to upper case for sorting.
4089 @node Input processing in ptx
4090 @subsection Word selection and input processing
4095 @item --break-file=@var{file}
4097 This option provides an alternative (to @option{-W}) method of describing
4098 which characters make up words. It introduces the name of a
4099 file which contains a list of characters which can@emph{not} be part of
4100 one word; this file is called the @dfn{Break file}. Any character which
4101 is not part of the Break file is a word constituent. If both options
4102 @option{-b} and @option{-W} are specified, then @option{-W} has precedence and
4103 @option{-b} is ignored.
4105 When @sc{gnu} extensions are enabled, the only way to avoid newline as a
4106 break character is to write all the break characters in the file with no
4107 newline at all, not even at the end of the file. When @sc{gnu} extensions
4108 are disabled, spaces, tabs and newlines are always considered as break
4109 characters even if not included in the Break file.
4112 @itemx --ignore-file=@var{file}
4114 The file associated with this option contains a list of words which will
4115 never be taken as keywords in concordance output. It is called the
4116 @dfn{Ignore file}. The file contains exactly one word in each line; the
4117 end of line separation of words is not subject to the value of the
4120 There is a default Ignore file used by @command{ptx} when this option is
4121 not specified, usually found in @file{/usr/local/lib/eign} if this has
4122 not been changed at installation time. If you want to deactivate the
4123 default Ignore file, specify @code{/dev/null} instead.
4126 @itemx --only-file=@var{file}
4128 The file associated with this option contains a list of words which will
4129 be retained in concordance output; any word not mentioned in this file
4130 is ignored. The file is called the @dfn{Only file}. The file contains
4131 exactly one word in each line; the end of line separation of words is
4132 not subject to the value of the @option{-S} option.
4134 There is no default for the Only file. When both an Only file and an
4135 Ignore file are specified, a word is considered a keyword only
4136 if it is listed in the Only file and not in the Ignore file.
4141 On each input line, the leading sequence of non-white space characters will be
4142 taken to be a reference that has the purpose of identifying this input
4143 line in the resulting permuted index. For more information about reference
4144 production, see @xref{Output formatting in ptx}.
4145 Using this option changes the default value for option @option{-S}.
4147 Using this option, the program does not try very hard to remove
4148 references from contexts in output, but it succeeds in doing so
4149 @emph{when} the context ends exactly at the newline. If option
4150 @option{-r} is used with @option{-S} default value, or when @sc{gnu} extensions
4151 are disabled, this condition is always met and references are completely
4152 excluded from the output contexts.
4154 @item -S @var{regexp}
4155 @itemx --sentence-regexp=@var{regexp}
4157 This option selects which regular expression will describe the end of a
4158 line or the end of a sentence. In fact, this regular expression is not
4159 the only distinction between end of lines or end of sentences, and input
4160 line boundaries have no special significance outside this option. By
4161 default, when @sc{gnu} extensions are enabled and if @option{-r} option is not
4162 used, end of sentences are used. In this case, this @var{regex} is
4163 imported from @sc{gnu} Emacs:
4166 [.?!][]\"')@}]*\\($\\|\t\\| \\)[ \t\n]*
4169 Whenever @sc{gnu} extensions are disabled or if @option{-r} option is used, end
4170 of lines are used; in this case, the default @var{regexp} is just:
4176 Using an empty @var{regexp} is equivalent to completely disabling end of
4177 line or end of sentence recognition. In this case, the whole file is
4178 considered to be a single big line or sentence. The user might want to
4179 disallow all truncation flag generation as well, through option @option{-F
4180 ""}. @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
4183 When the keywords happen to be near the beginning of the input line or
4184 sentence, this often creates an unused area at the beginning of the
4185 output context line; when the keywords happen to be near the end of the
4186 input line or sentence, this often creates an unused area at the end of
4187 the output context line. The program tries to fill those unused areas
4188 by wrapping around context in them; the tail of the input line or
4189 sentence is used to fill the unused area on the left of the output line;
4190 the head of the input line or sentence is used to fill the unused area
4191 on the right of the output line.
4193 As a matter of convenience to the user, many usual backslashed escape
4194 sequences from the C language are recognized and converted to the
4195 corresponding characters by @command{ptx} itself.
4197 @item -W @var{regexp}
4198 @itemx --word-regexp=@var{regexp}
4200 This option selects which regular expression will describe each keyword.
4201 By default, if @sc{gnu} extensions are enabled, a word is a sequence of
4202 letters; the @var{regexp} used is @samp{\w+}. When @sc{gnu} extensions are
4203 disabled, a word is by default anything which ends with a space, a tab
4204 or a newline; the @var{regexp} used is @samp{[^ \t\n]+}.
4206 An empty @var{regexp} is equivalent to not using this option.
4207 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
4210 As a matter of convenience to the user, many usual backslashed escape
4211 sequences, as found in the C language, are recognized and converted to
4212 the corresponding characters by @command{ptx} itself.
4217 @node Output formatting in ptx
4218 @subsection Output formatting
4220 Output format is mainly controlled by the @option{-O} and @option{-T} options
4221 described in the table below. When neither @option{-O} nor @option{-T} are
4222 selected, and if @sc{gnu} extensions are enabled, the program chooses an
4223 output format suitable for a dumb terminal. Each keyword occurrence is
4224 output to the center of one line, surrounded by its left and right
4225 contexts. Each field is properly justified, so the concordance output
4226 can be readily observed. As a special feature, if automatic
4227 references are selected by option @option{-A} and are output before the
4228 left context, that is, if option @option{-R} is @emph{not} selected, then
4229 a colon is added after the reference; this nicely interfaces with @sc{gnu}
4230 Emacs @code{next-error} processing. In this default output format, each
4231 white space character, like newline and tab, is merely changed to
4232 exactly one space, with no special attempt to compress consecutive
4233 spaces. This might change in the future. Except for those white space
4234 characters, every other character of the underlying set of 256
4235 characters is transmitted verbatim.
4237 Output format is further controlled by the following options.
4241 @item -g @var{number}
4242 @itemx --gap-size=@var{number}
4244 Select the size of the minimum white space gap between the fields on the
4247 @item -w @var{number}
4248 @itemx --width=@var{number}
4250 Select the maximum output width of each final line. If references are
4251 used, they are included or excluded from the maximum output width
4252 depending on the value of option @option{-R}. If this option is not
4253 selected, that is, when references are output before the left context,
4254 the maximum output width takes into account the maximum length of all
4255 references. If this option is selected, that is, when references are
4256 output after the right context, the maximum output width does not take
4257 into account the space taken by references, nor the gap that precedes
4261 @itemx --auto-reference
4263 Select automatic references. Each input line will have an automatic
4264 reference made up of the file name and the line ordinal, with a single
4265 colon between them. However, the file name will be empty when standard
4266 input is being read. If both @option{-A} and @option{-r} are selected, then
4267 the input reference is still read and skipped, but the automatic
4268 reference is used at output time, overriding the input reference.
4271 @itemx --right-side-refs
4273 In the default output format, when option @option{-R} is not used, any
4274 references produced by the effect of options @option{-r} or @option{-A} are
4275 placed to the far right of output lines, after the right context. With
4276 default output format, when the @option{-R} option is specified, references
4277 are rather placed at the beginning of each output line, before the left
4278 context. For any other output format, option @option{-R} is
4279 ignored, with one exception: with @option{-R} the width of references
4280 is @emph{not} taken into account in total output width given by @option{-w}.
4282 This option is automatically selected whenever @sc{gnu} extensions are
4285 @item -F @var{string}
4286 @itemx --flac-truncation=@var{string}
4288 This option will request that any truncation in the output be reported
4289 using the string @var{string}. Most output fields theoretically extend
4290 towards the beginning or the end of the current line, or current
4291 sentence, as selected with option @option{-S}. But there is a maximum
4292 allowed output line width, changeable through option @option{-w}, which is
4293 further divided into space for various output fields. When a field has
4294 to be truncated because it cannot extend beyond the beginning or the end of
4295 the current line to fit in, then a truncation occurs. By default,
4296 the string used is a single slash, as in @option{-F /}.
4298 @var{string} may have more than one character, as in @option{-F ...}.
4299 Also, in the particular case when @var{string} is empty (@option{-F ""}),
4300 truncation flagging is disabled, and no truncation marks are appended in
4303 As a matter of convenience to the user, many usual backslashed escape
4304 sequences, as found in the C language, are recognized and converted to
4305 the corresponding characters by @command{ptx} itself.
4307 @item -M @var{string}
4308 @itemx --macro-name=@var{string}
4310 Select another @var{string} to be used instead of @samp{xx}, while
4311 generating output suitable for @command{nroff}, @command{troff} or @TeX{}.
4314 @itemx --format=roff
4316 Choose an output format suitable for @command{nroff} or @command{troff}
4317 processing. Each output line will look like:
4320 .xx "@var{tail}" "@var{before}" "@var{keyword_and_after}" "@var{head}" "@var{ref}"
4323 so it will be possible to write a @samp{.xx} roff macro to take care of
4324 the output typesetting. This is the default output format when @sc{gnu}
4325 extensions are disabled. Option @option{-M} can be used to change
4326 @samp{xx} to another macro name.
4328 In this output format, each non-graphical character, like newline and
4329 tab, is merely changed to exactly one space, with no special attempt to
4330 compress consecutive spaces. Each quote character: @kbd{"} is doubled
4331 so it will be correctly processed by @command{nroff} or @command{troff}.
4336 Choose an output format suitable for @TeX{} processing. Each output
4337 line will look like:
4340 \xx @{@var{tail}@}@{@var{before}@}@{@var{keyword}@}@{@var{after}@}@{@var{head}@}@{@var{ref}@}
4344 so it will be possible to write a @code{\xx} definition to take care of
4345 the output typesetting. Note that when references are not being
4346 produced, that is, neither option @option{-A} nor option @option{-r} is
4347 selected, the last parameter of each @code{\xx} call is inhibited.
4348 Option @option{-M} can be used to change @samp{xx} to another macro
4351 In this output format, some special characters, like @kbd{$}, @kbd{%},
4352 @kbd{&}, @kbd{#} and @kbd{_} are automatically protected with a
4353 backslash. Curly brackets @kbd{@{}, @kbd{@}} are protected with a
4354 backslash and a pair of dollar signs (to force mathematical mode). The
4355 backslash itself produces the sequence @code{\backslash@{@}}.
4356 Circumflex and tilde diacritical marks produce the sequence @code{^\@{ @}} and
4357 @code{~\@{ @}} respectively. Other diacriticized characters of the
4358 underlying character set produce an appropriate @TeX{} sequence as far
4359 as possible. The other non-graphical characters, like newline and tab,
4360 and all other characters which are not part of @acronym{ASCII}, are merely
4361 changed to exactly one space, with no special attempt to compress
4362 consecutive spaces. Let me know how to improve this special character
4363 processing for @TeX{}.
4368 @node Compatibility in ptx
4369 @subsection The @sc{gnu} extensions to @command{ptx}
4371 This version of @command{ptx} contains a few features which do not exist in
4372 System V @command{ptx}. These extra features are suppressed by using the
4373 @option{-G} command line option, unless overridden by other command line
4374 options. Some @sc{gnu} extensions cannot be recovered by overriding, so the
4375 simple rule is to avoid @option{-G} if you care about @sc{gnu} extensions.
4376 Here are the differences between this program and System V @command{ptx}.
4381 This program can read many input files at once, it always writes the
4382 resulting concordance on standard output. On the other hand, System V
4383 @command{ptx} reads only one file and sends the result to standard output
4384 or, if a second @var{file} parameter is given on the command, to that
4387 Having output parameters not introduced by options is a dangerous
4388 practice which @sc{gnu} avoids as far as possible. So, for using @command{ptx}
4389 portably between @sc{gnu} and System V, you should always use it with a
4390 single input file, and always expect the result on standard output. You
4391 might also want to automatically configure in a @option{-G} option to
4392 @command{ptx} calls in products using @command{ptx}, if the configurator finds
4393 that the installed @command{ptx} accepts @option{-G}.
4396 The only options available in System V @command{ptx} are options @option{-b},
4397 @option{-f}, @option{-g}, @option{-i}, @option{-o}, @option{-r}, @option{-t} and
4398 @option{-w}. All other options are @sc{gnu} extensions and are not repeated in
4399 this enumeration. Moreover, some options have a slightly different
4400 meaning when @sc{gnu} extensions are enabled, as explained below.
4403 By default, concordance output is not formatted for @command{troff} or
4404 @command{nroff}. It is rather formatted for a dumb terminal. @command{troff}
4405 or @command{nroff} output may still be selected through option @option{-O}.
4408 Unless @option{-R} option is used, the maximum reference width is
4409 subtracted from the total output line width. With @sc{gnu} extensions
4410 disabled, width of references is not taken into account in the output
4411 line width computations.
4414 All 256 bytes, even null bytes, are always read and processed from
4415 input file with no adverse effect, even if @sc{gnu} extensions are disabled.
4416 However, System V @command{ptx} does not accept 8-bit characters, a few
4417 control characters are rejected, and the tilde @kbd{~} is also rejected.
4420 Input line length is only limited by available memory, even if @sc{gnu}
4421 extensions are disabled. However, System V @command{ptx} processes only
4422 the first 200 characters in each line.
4425 The break (non-word) characters default to be every character except all
4426 letters of the underlying character set, diacriticized or not. When @sc{gnu}
4427 extensions are disabled, the break characters default to space, tab and
4431 The program makes better use of output line width. If @sc{gnu} extensions
4432 are disabled, the program rather tries to imitate System V @command{ptx},
4433 but still, there are some slight disposition glitches this program does
4434 not completely reproduce.
4437 The user can specify both an Ignore file and an Only file. This is not
4438 allowed with System V @command{ptx}.
4443 @node Operating on fields within a line
4444 @chapter Operating on fields within a line
4447 * cut invocation:: Print selected parts of lines.
4448 * paste invocation:: Merge lines of files.
4449 * join invocation:: Join lines on a common field.
4453 @node cut invocation
4454 @section @command{cut}: Print selected parts of lines
4457 @command{cut} writes to standard output selected parts of each line of each
4458 input file, or standard input if no files are given or for a file name of
4462 cut [@var{option}]@dots{} [@var{file}]@dots{}
4465 In the table which follows, the @var{byte-list}, @var{character-list},
4466 and @var{field-list} are one or more numbers or ranges (two numbers
4467 separated by a dash) separated by commas. Bytes, characters, and
4468 fields are numbered starting at 1. Incomplete ranges may be
4469 given: @option{-@var{m}} means @samp{1-@var{m}}; @samp{@var{n}-} means
4470 @samp{@var{n}} through end of line or last field. The list elements
4471 can be repeated, can overlap, and can be specified in any order; but
4472 the selected input is written in the same order that it is read, and
4473 is written exactly once.
4475 The program accepts the following options. Also see @ref{Common
4480 @item -b @var{byte-list}
4481 @itemx --bytes=@var{byte-list}
4484 Select for printing only the bytes in positions listed in
4485 @var{byte-list}. Tabs and backspaces are treated like any other
4486 character; they take up 1 byte. If an output delimiter is specified,
4487 (see the description of @option{--output-delimiter}), then output that
4488 string between ranges of selected bytes.
4490 @item -c @var{character-list}
4491 @itemx --characters=@var{character-list}
4493 @opindex --characters
4494 Select for printing only the characters in positions listed in
4495 @var{character-list}. The same as @option{-b} for now, but
4496 internationalization will change that. Tabs and backspaces are
4497 treated like any other character; they take up 1 character. If an
4498 output delimiter is specified, (see the description of
4499 @option{--output-delimiter}), then output that string between ranges
4502 @item -f @var{field-list}
4503 @itemx --fields=@var{field-list}
4506 Select for printing only the fields listed in @var{field-list}.
4507 Fields are separated by a TAB character by default. Also print any
4508 line that contains no delimiter character, unless the
4509 @option{--only-delimited} (@option{-s}) option is specified
4511 @item -d @var{input_delim_byte}
4512 @itemx --delimiter=@var{input_delim_byte}
4514 @opindex --delimiter
4515 For @option{-f}, fields are separated in the input by the first character
4516 in @var{input_delim_byte} (default is TAB).
4520 Do not split multi-byte characters (no-op for now).
4523 @itemx --only-delimited
4525 @opindex --only-delimited
4526 For @option{-f}, do not print lines that do not contain the field separator
4527 character. Normally, any line without a field separator is printed verbatim.
4529 @item --output-delimiter=@var{output_delim_string}
4530 @opindex --output-delimiter
4531 With @option{-f}, output fields are separated by @var{output_delim_string}.
4532 The default with @option{-f} is to use the input delimiter.
4533 When using @option{-b} or @option{-c} to select ranges of byte or
4534 character offsets (as opposed to ranges of fields),
4535 output @var{output_delim_string} between non-overlapping
4536 ranges of selected bytes.
4539 @opindex --complement
4540 This option is a GNU extension.
4541 Select for printing the complement of the bytes, characters or fields
4542 selected with the @option{-b}, @option{-c} or @option{-f} options.
4543 In other words, do @emph{not} print the bytes, characters or fields
4544 specified via those options. This option is useful when you have
4545 many fields and want to print all but a few of them.
4552 @node paste invocation
4553 @section @command{paste}: Merge lines of files
4556 @cindex merging files
4558 @command{paste} writes to standard output lines consisting of sequentially
4559 corresponding lines of each given file, separated by a TAB character.
4560 Standard input is used for a file name of @samp{-} or if no input files
4582 paste [@var{option}]@dots{} [@var{file}]@dots{}
4585 The program accepts the following options. Also see @ref{Common options}.
4593 Paste the lines of one file at a time rather than one line from each
4594 file. Using the above example data:
4597 $ paste -s num2 let3
4602 @item -d @var{delim-list}
4603 @itemx --delimiters=@var{delim-list}
4605 @opindex --delimiters
4606 Consecutively use the characters in @var{delim-list} instead of
4607 TAB to separate merged lines. When @var{delim-list} is
4608 exhausted, start again at its beginning. Using the above example data:
4611 $ paste -d '%_' num2 let3 num2
4622 @node join invocation
4623 @section @command{join}: Join lines on a common field
4626 @cindex common field, joining on
4628 @command{join} writes to standard output a line for each pair of input
4629 lines that have identical join fields. Synopsis:
4632 join [@var{option}]@dots{} @var{file1} @var{file2}
4636 Either @var{file1} or @var{file2} (but not both) can be @samp{-},
4637 meaning standard input. @var{file1} and @var{file2} should be
4638 sorted on the join fields.
4640 Normally, the sort order is that of the
4641 collating sequence specified by the @env{LC_COLLATE} locale. Unless
4642 the @option{-t} option is given, the sort comparison ignores blanks at
4643 the start of the join field, as in @code{sort -b}. If the
4644 @option{--ignore-case} option is given, the sort comparison ignores
4645 the case of characters in the join field, as in @code{sort -f}.
4647 However, as a GNU extension, if the input has no unpairable lines the
4648 sort order can be any order that considers two fields to be equal if and
4649 only if the sort comparison described above considers them to be equal.
4667 The defaults are: the join field is the first field in each line;
4668 fields in the input are separated by one or more blanks, with leading
4669 blanks on the line ignored; fields in the output are separated by a
4670 space; each output line consists of the join field, the remaining
4671 fields from @var{file1}, then the remaining fields from @var{file2}.
4673 The program accepts the following options. Also see @ref{Common options}.
4677 @item -a @var{file-number}
4679 Print a line for each unpairable line in file @var{file-number} (either
4680 @samp{1} or @samp{2}), in addition to the normal output.
4682 @item -e @var{string}
4684 Replace those output fields that are missing in the input with
4688 @itemx --ignore-case
4690 @opindex --ignore-case
4691 Ignore differences in case when comparing keys.
4692 With this option, the lines of the input files must be ordered in the same way.
4693 Use @samp{sort -f} to produce this ordering.
4695 @item -1 @var{field}
4697 Join on field @var{field} (a positive integer) of file 1.
4699 @item -2 @var{field}
4701 Join on field @var{field} (a positive integer) of file 2.
4703 @item -j @var{field}
4704 Equivalent to @option{-1 @var{field} -2 @var{field}}.
4706 @item -o @var{field-list}
4707 Construct each output line according to the format in @var{field-list}.
4708 Each element in @var{field-list} is either the single character @samp{0} or
4709 has the form @var{m.n} where the file number, @var{m}, is @samp{1} or
4710 @samp{2} and @var{n} is a positive field number.
4712 A field specification of @samp{0} denotes the join field.
4713 In most cases, the functionality of the @samp{0} field spec
4714 may be reproduced using the explicit @var{m.n} that corresponds
4715 to the join field. However, when printing unpairable lines
4716 (using either of the @option{-a} or @option{-v} options), there is no way
4717 to specify the join field using @var{m.n} in @var{field-list}
4718 if there are unpairable lines in both files.
4719 To give @command{join} that functionality, @acronym{POSIX} invented the @samp{0}
4720 field specification notation.
4722 The elements in @var{field-list}
4723 are separated by commas or blanks.
4724 Blank separators typically need to be quoted for the shell. For
4725 example, the commands @samp{join -o 1.2,2.2} and @samp{join -o '1.2
4726 2.2'} are equivalent.
4728 All output lines---including those printed because of any -a or -v
4729 option---are subject to the specified @var{field-list}.
4732 Use character @var{char} as the input and output field separator.
4733 Treat as significant each occurrence of @var{char} in the input file.
4735 @item -v @var{file-number}
4736 Print a line for each unpairable line in file @var{file-number}
4737 (either @samp{1} or @samp{2}), instead of the normal output.
4744 @node Operating on characters
4745 @chapter Operating on characters
4747 @cindex operating on characters
4749 This commands operate on individual characters.
4752 * tr invocation:: Translate, squeeze, and/or delete characters.
4753 * expand invocation:: Convert tabs to spaces.
4754 * unexpand invocation:: Convert spaces to tabs.
4759 @section @command{tr}: Translate, squeeze, and/or delete characters
4766 tr [@var{option}]@dots{} @var{set1} [@var{set2}]
4769 @command{tr} copies standard input to standard output, performing
4770 one of the following operations:
4774 translate, and optionally squeeze repeated characters in the result,
4776 squeeze repeated characters,
4780 delete characters, then squeeze repeated characters from the result.
4783 The @var{set1} and (if given) @var{set2} arguments define ordered
4784 sets of characters, referred to below as @var{set1} and @var{set2}. These
4785 sets are the characters of the input that @command{tr} operates on.
4786 The @option{--complement} (@option{-c}, @option{-C}) option replaces
4788 complement (all of the characters that are not in @var{set1}).
4790 Currently @command{tr} fully supports only single-byte characters.
4791 Eventually it will support multibyte characters; when it does, the
4792 @option{-C} option will cause it to complement the set of characters,
4793 whereas @option{-c} will cause it to complement the set of values.
4794 This distinction will matter only when some values are not characters,
4795 and this is possible only in locales using multibyte encodings when
4796 the input contains encoding errors.
4798 The program accepts the @option{--help} and @option{--version}
4799 options. @xref{Common options}. Options must precede operands.
4804 * Character sets:: Specifying sets of characters.
4805 * Translating:: Changing one set of characters to another.
4806 * Squeezing:: Squeezing repeats and deleting.
4810 @node Character sets
4811 @subsection Specifying sets of characters
4813 @cindex specifying sets of characters
4815 The format of the @var{set1} and @var{set2} arguments resembles
4816 the format of regular expressions; however, they are not regular
4817 expressions, only lists of characters. Most characters simply
4818 represent themselves in these strings, but the strings can contain
4819 the shorthands listed below, for convenience. Some of them can be
4820 used only in @var{set1} or @var{set2}, as noted below.
4824 @item Backslash escapes
4825 @cindex backslash escapes
4827 A backslash followed by a character not listed below causes an error
4846 The character with the value given by @var{ooo}, which is 1 to 3
4855 The notation @samp{@var{m}-@var{n}} expands to all of the characters
4856 from @var{m} through @var{n}, in ascending order. @var{m} should
4857 collate before @var{n}; if it doesn't, an error results. As an example,
4858 @samp{0-9} is the same as @samp{0123456789}.
4860 @sc{gnu} @command{tr} does not support the System V syntax that uses square
4861 brackets to enclose ranges. Translations specified in that format
4862 sometimes work as expected, since the brackets are often transliterated
4863 to themselves. However, they should be avoided because they sometimes
4864 behave unexpectedly. For example, @samp{tr -d '[0-9]'} deletes brackets
4867 Many historically common and even accepted uses of ranges are not
4868 portable. For example, on @acronym{EBCDIC} hosts using the @samp{A-Z}
4869 range will not do what most would expect because @samp{A} through @samp{Z}
4870 are not contiguous as they are in @acronym{ASCII}.
4871 If you can rely on a @acronym{POSIX} compliant version of @command{tr}, then
4872 the best way to work around this is to use character classes (see below).
4873 Otherwise, it is most portable (and most ugly) to enumerate the members
4876 @item Repeated characters
4877 @cindex repeated characters
4879 The notation @samp{[@var{c}*@var{n}]} in @var{set2} expands to @var{n}
4880 copies of character @var{c}. Thus, @samp{[y*6]} is the same as
4881 @samp{yyyyyy}. The notation @samp{[@var{c}*]} in @var{string2} expands
4882 to as many copies of @var{c} as are needed to make @var{set2} as long as
4883 @var{set1}. If @var{n} begins with @samp{0}, it is interpreted in
4884 octal, otherwise in decimal.
4886 @item Character classes
4887 @cindex character classes
4889 The notation @samp{[:@var{class}:]} expands to all of the characters in
4890 the (predefined) class @var{class}. The characters expand in no
4891 particular order, except for the @code{upper} and @code{lower} classes,
4892 which expand in ascending order. When the @option{--delete} (@option{-d})
4893 and @option{--squeeze-repeats} (@option{-s}) options are both given, any
4894 character class can be used in @var{set2}. Otherwise, only the
4895 character classes @code{lower} and @code{upper} are accepted in
4896 @var{set2}, and then only if the corresponding character class
4897 (@code{upper} and @code{lower}, respectively) is specified in the same
4898 relative position in @var{set1}. Doing this specifies case conversion.
4899 The class names are given below; an error results when an invalid class
4911 Horizontal whitespace.
4920 Printable characters, not including space.
4926 Printable characters, including space.
4929 Punctuation characters.
4932 Horizontal or vertical whitespace.
4941 @item Equivalence classes
4942 @cindex equivalence classes
4944 The syntax @samp{[=@var{c}=]} expands to all of the characters that are
4945 equivalent to @var{c}, in no particular order. Equivalence classes are
4946 a relatively recent invention intended to support non-English alphabets.
4947 But there seems to be no standard way to define them or determine their
4948 contents. Therefore, they are not fully implemented in @sc{gnu} @command{tr};
4949 each character's equivalence class consists only of that character,
4950 which is of no particular use.
4956 @subsection Translating
4958 @cindex translating characters
4960 @command{tr} performs translation when @var{set1} and @var{set2} are
4961 both given and the @option{--delete} (@option{-d}) option is not given.
4962 @command{tr} translates each character of its input that is in @var{set1}
4963 to the corresponding character in @var{set2}. Characters not in
4964 @var{set1} are passed through unchanged. When a character appears more
4965 than once in @var{set1} and the corresponding characters in @var{set2}
4966 are not all the same, only the final one is used. For example, these
4967 two commands are equivalent:
4974 A common use of @command{tr} is to convert lowercase characters to
4975 uppercase. This can be done in many ways. Here are three of them:
4978 tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
4980 tr '[:lower:]' '[:upper:]'
4984 But note that using ranges like @code{a-z} above is not portable.
4986 When @command{tr} is performing translation, @var{set1} and @var{set2}
4987 typically have the same length. If @var{set1} is shorter than
4988 @var{set2}, the extra characters at the end of @var{set2} are ignored.
4990 On the other hand, making @var{set1} longer than @var{set2} is not
4991 portable; @acronym{POSIX} says that the result is undefined. In this situation,
4992 BSD @command{tr} pads @var{set2} to the length of @var{set1} by repeating
4993 the last character of @var{set2} as many times as necessary. System V
4994 @command{tr} truncates @var{set1} to the length of @var{set2}.
4996 By default, @sc{gnu} @command{tr} handles this case like BSD @command{tr}.
4997 When the @option{--truncate-set1} (@option{-t}) option is given,
4998 @sc{gnu} @command{tr} handles this case like the System V @command{tr}
4999 instead. This option is ignored for operations other than translation.
5001 Acting like System V @command{tr} in this case breaks the relatively common
5005 tr -cs A-Za-z0-9 '\012'
5009 because it converts only zero bytes (the first element in the
5010 complement of @var{set1}), rather than all non-alphanumerics, to
5014 By the way, the above idiom is not portable because it uses ranges, and
5015 it assumes that the octal code for newline is 012.
5016 Assuming a @acronym{POSIX} compliant @command{tr}, here is a better way to write it:
5019 tr -cs '[:alnum:]' '[\n*]'
5024 @subsection Squeezing repeats and deleting
5026 @cindex squeezing repeat characters
5027 @cindex deleting characters
5029 When given just the @option{--delete} (@option{-d}) option, @command{tr}
5030 removes any input characters that are in @var{set1}.
5032 When given just the @option{--squeeze-repeats} (@option{-s}) option,
5033 @command{tr} replaces each input sequence of a repeated character that
5034 is in @var{set1} with a single occurrence of that character.
5036 When given both @option{--delete} and @option{--squeeze-repeats}, @command{tr}
5037 first performs any deletions using @var{set1}, then squeezes repeats
5038 from any remaining characters using @var{set2}.
5040 The @option{--squeeze-repeats} option may also be used when translating,
5041 in which case @command{tr} first performs translation, then squeezes
5042 repeats from any remaining characters using @var{set2}.
5044 Here are some examples to illustrate various combinations of options:
5049 Remove all zero bytes:
5056 Put all words on lines by themselves. This converts all
5057 non-alphanumeric characters to newlines, then squeezes each string
5058 of repeated newlines into a single newline:
5061 tr -cs '[:alnum:]' '[\n*]'
5065 Convert each sequence of repeated newlines to a single newline:
5072 Find doubled occurrences of words in a document.
5073 For example, people often write ``the the'' with the repeated words
5074 separated by a newline. The Bourne shell script below works first
5075 by converting each sequence of punctuation and blank characters to a
5076 single newline. That puts each ``word'' on a line by itself.
5077 Next it maps all uppercase characters to lower case, and finally it
5078 runs @command{uniq} with the @option{-d} option to print out only the words
5084 | tr -s '[:punct:][:blank:]' '[\n*]' \
5085 | tr '[:upper:]' '[:lower:]' \
5090 Deleting a small set of characters is usually straightforward. For example,
5091 to remove all @samp{a}s, @samp{x}s, and @samp{M}s you would do this:
5097 However, when @samp{-} is one of those characters, it can be tricky because
5098 @samp{-} has special meanings. Performing the same task as above but also
5099 removing all @samp{-} characters, we might try @code{tr -d -axM}, but
5100 that would fail because @command{tr} would try to interpret @option{-a} as
5101 a command-line option. Alternatively, we could try putting the hyphen
5102 inside the string, @code{tr -d a-xM}, but that wouldn't work either because
5103 it would make @command{tr} interpret @code{a-x} as the range of characters
5104 @samp{a}@dots{}@samp{x} rather than the three.
5105 One way to solve the problem is to put the hyphen at the end of the list
5112 Or you can use @samp{--} to terminate option processing:
5118 More generally, use the character class notation @code{[=c=]}
5119 with @samp{-} (or any other character) in place of the @samp{c}:
5125 Note how single quotes are used in the above example to protect the
5126 square brackets from interpretation by a shell.
5131 @node expand invocation
5132 @section @command{expand}: Convert tabs to spaces
5135 @cindex tabs to spaces, converting
5136 @cindex converting tabs to spaces
5138 @command{expand} writes the contents of each given @var{file}, or standard
5139 input if none are given or for a @var{file} of @samp{-}, to standard
5140 output, with tab characters converted to the appropriate number of
5144 expand [@var{option}]@dots{} [@var{file}]@dots{}
5147 By default, @command{expand} converts all tabs to spaces. It preserves
5148 backspace characters in the output; they decrement the column count for
5149 tab calculations. The default action is equivalent to @option{-t 8} (set
5150 tabs every 8 columns).
5152 The program accepts the following options. Also see @ref{Common options}.
5156 @item -t @var{tab1}[,@var{tab2}]@dots{}
5157 @itemx --tabs=@var{tab1}[,@var{tab2}]@dots{}
5160 @cindex tab stops, setting
5161 If only one tab stop is given, set the tabs @var{tab1} spaces apart
5162 (default is 8). Otherwise, set the tabs at columns @var{tab1},
5163 @var{tab2}, @dots{} (numbered from 0), and replace any tabs beyond the
5164 last tab stop given with single spaces. Tab stops can be separated by
5165 blanks as well as by commas.
5167 For compatibility @command{expand} also supports an obsolete
5168 option syntax @option{-@var{tab1}[,@var{tab2}]@dots{}}. New scripts
5169 should use @option{-t @var{tab1}[,@var{tab2}]@dots{}} instead.
5175 @cindex initial tabs, converting
5176 Only convert initial tabs (those that precede all non-space or non-tab
5177 characters) on each line to spaces.
5184 @node unexpand invocation
5185 @section @command{unexpand}: Convert spaces to tabs
5189 @command{unexpand} writes the contents of each given @var{file}, or
5190 standard input if none are given or for a @var{file} of @samp{-}, to
5191 standard output, converting blanks at the beginning of each line into
5192 as many tab characters as needed. In the default @acronym{POSIX}
5193 locale, a @dfn{blank} is a space or a tab; other locales may specify
5194 additional blank characters. Synopsis:
5197 unexpand [@var{option}]@dots{} [@var{file}]@dots{}
5200 By default, @command{unexpand} converts only initial blanks (those
5201 that precede all non-blank characters) on each line. It
5202 preserves backspace characters in the output; they decrement the column
5203 count for tab calculations. By default, tabs are set at every 8th
5206 The program accepts the following options. Also see @ref{Common options}.
5210 @item -t @var{tab1}[,@var{tab2}]@dots{}
5211 @itemx --tabs=@var{tab1}[,@var{tab2}]@dots{}
5214 If only one tab stop is given, set the tabs @var{tab1} columns apart
5215 instead of the default 8. Otherwise, set the tabs at columns
5216 @var{tab1}, @var{tab2}, @dots{} (numbered from 0), and leave blanks
5217 beyond the tab stops given unchanged. Tab stops can be separated by
5218 blanks as well as by commas. This option implies the @option{-a} option.
5220 For compatibility @command{unexpand} supports an obsolete option syntax
5221 @option{-@var{tab1}[,@var{tab2}]@dots{}}, where tab stops must be
5222 separated by commas. (Unlike @option{-t}, this obsolete option does
5223 not imply @option{-a}.) New scripts should use @option{--first-only -t
5224 @var{tab1}[,@var{tab2}]@dots{}} instead.
5230 Also convert all sequences of two or more blanks just before a tab stop.
5231 even if they occur after non-blank characters in a line.
5238 @node Directory listing
5239 @chapter Directory listing
5241 This chapter describes the @command{ls} command and its variants @command{dir}
5242 and @command{vdir}, which list information about files.
5245 * ls invocation:: List directory contents.
5246 * dir invocation:: Briefly ls.
5247 * vdir invocation:: Verbosely ls.
5248 * dircolors invocation:: Color setup for ls, etc.
5253 @section @command{ls}: List directory contents
5256 @cindex directory listing
5258 The @command{ls} program lists information about files (of any type,
5259 including directories). Options and file arguments can be intermixed
5260 arbitrarily, as usual.
5262 For non-option command-line arguments that are directories, by default
5263 @command{ls} lists the contents of directories, not recursively, and
5264 omitting files with names beginning with @samp{.}. For other non-option
5265 arguments, by default @command{ls} lists just the file name. If no
5266 non-option argument is specified, @command{ls} operates on the current
5267 directory, acting as if it had been invoked with a single argument of @samp{.}.
5270 By default, the output is sorted alphabetically, according to the locale
5271 settings in effect.@footnote{If you use a non-@acronym{POSIX}
5272 locale (e.g., by setting @env{LC_ALL} to @samp{en_US}), then @command{ls} may
5273 produce output that is sorted differently than you're accustomed to.
5274 In that case, set the @env{LC_ALL} environment variable to @samp{C}.}
5275 If standard output is
5276 a terminal, the output is in columns (sorted vertically) and control
5277 characters are output as question marks; otherwise, the output is listed
5278 one per line and control characters are output as-is.
5280 Because @command{ls} is such a fundamental program, it has accumulated many
5281 options over the years. They are described in the subsections below;
5282 within each section, options are listed alphabetically (ignoring case).
5283 The division of options into the subsections is not absolute, since some
5284 options affect more than one aspect of @command{ls}'s operation.
5286 @cindex exit status of @command{ls}
5291 1 minor problems (e.g., a subdirectory was not found)
5292 2 serious trouble (e.g., memory exhausted)
5295 Also see @ref{Common options}.
5298 * Which files are listed::
5299 * What information is listed::
5300 * Sorting the output::
5301 * More details about version sort::
5302 * General output formatting::
5303 * Formatting file timestamps::
5304 * Formatting the file names::
5308 @node Which files are listed
5309 @subsection Which files are listed
5311 These options determine which files @command{ls} lists information for.
5312 By default, @command{ls} lists files and the contents of any
5313 directories on the command line, except that in directories it ignores
5314 files whose names start with @samp{.}.
5322 In directories, do not ignore file names that start with @samp{.}.
5327 @opindex --almost-all
5328 In directories, do not ignore all file names that start with @samp{.};
5329 ignore only @file{.} and @file{..}. The @option{--all} (@option{-a})
5330 option overrides this option.
5333 @itemx --ignore-backups
5335 @opindex --ignore-backups
5336 @cindex backup files, ignoring
5337 In directories, ignore files that end with @samp{~}. This option is
5338 equivalent to @samp{--ignore='*~' --ignore='.*~'}.
5343 @opindex --directory
5344 List just the names of directories, as with other types of files, rather
5345 than listing their contents.
5346 @c The following sentence is the same as the one for -F.
5347 Do not follow symbolic links listed on the
5348 command line unless the @option{--dereference-command-line} (@option{-H}),
5349 @option{--dereference} (@option{-L}), or
5350 @option{--dereference-command-line-symlink-to-dir} options are specified.
5353 @itemx --dereference-command-line
5355 @opindex --dereference-command-line
5356 @cindex symbolic links, dereferencing
5357 If a command line argument specifies a symbolic link, show information
5358 for the file the link references rather than for the link itself.
5360 @itemx --dereference-command-line-symlink-to-dir
5361 @opindex --dereference-command-line-symlink-to-dir
5362 @cindex symbolic links, dereferencing
5363 Do not dereference symbolic links, with one exception:
5364 if a command line argument specifies a symbolic link that refers to
5365 a directory, show information for that directory rather than for the
5367 This is the default behavior when no other dereferencing-related
5368 option has been specified (@option{--classify} (@option{-F}),
5369 @option{--directory} (@option{-d}),
5371 @option{--dereference} (@option{-L}), or
5372 @option{--dereference-command-line} (@option{-H})).
5374 @item --hide=PATTERN
5375 @opindex --hide=@var{pattern}
5376 In directories, ignore files whose names match the shell pattern
5377 @var{pattern}, unless the @option{--all} (@option{-a}) or
5378 @option{--almost-all} (@option{-A}) is also given. This
5379 option acts like @option{--ignore=@var{pattern}} except that it has no
5380 effect if @option{--all} (@option{-a}) or @option{--almost-all}
5381 (@option{-A}) is also given.
5383 This option can be useful in shell aliases. For example, if
5384 @command{lx} is an alias for @samp{ls --hide='*~'} and @command{ly} is
5385 an alias for @samp{ls --ignore='*~'}, then the command @samp{lx -A}
5386 lists the file @file{README~} even though @samp{ly -A} would not.
5388 @item -I @var{pattern}
5389 @itemx --ignore=@var{pattern}
5391 @opindex --ignore=@var{pattern}
5392 In directories, ignore files whose names match the shell pattern
5393 (not regular expression) @var{pattern}. As
5394 in the shell, an initial @samp{.} in a file name does not match a
5395 wildcard at the start of @var{pattern}. Sometimes it is useful
5396 to give this option several times. For example,
5399 $ ls --ignore='.??*' --ignore='.[^.]' --ignore='#*'
5402 The first option ignores names of length 3 or more that start with @samp{.},
5403 the second ignores all two-character names that start with @samp{.}
5404 except @samp{..}, and the third ignores names that start with @samp{#}.
5407 @itemx --dereference
5409 @opindex --dereference
5410 @cindex symbolic links, dereferencing
5411 When showing file information for a symbolic link, show information
5412 for the file the link references rather than the link itself.
5413 However, even with this option, @command{ls} still prints the name
5414 of the link itself, not the name of the file that the link points to.
5419 @opindex --recursive
5420 @cindex recursive directory listing
5421 @cindex directory listing, recursive
5422 List the contents of all directories recursively.
5427 @node What information is listed
5428 @subsection What information is listed
5430 These options affect the information that @command{ls} displays. By
5431 default, only file names are shown.
5437 @cindex hurd, author, printing
5438 List each file's author when producing long format directory listings.
5439 In GNU/Hurd, file authors can differ from their owners, but in other
5440 operating systems the two are the same.
5446 @cindex dired Emacs mode support
5447 With the long listing (@option{-l}) format, print an additional line after
5451 //DIRED// @var{beg1} @var{end1} @var{beg2} @var{end2} @dots{}
5455 The @var{begN} and @var{endN} are unsigned integers that record the
5456 byte position of the beginning and end of each file name in the output.
5457 This makes it easy for Emacs to find the names, even when they contain
5458 unusual characters such as space or newline, without fancy searching.
5460 If directories are being listed recursively (@option{-R}), output a similar
5461 line with offsets for each subdirectory name:
5464 //SUBDIRED// @var{beg1} @var{end1} @dots{}
5467 Finally, output a line of the form:
5470 //DIRED-OPTIONS// --quoting-style=@var{word}
5474 where @var{word} is the quoting style (@pxref{Formatting the file names}).
5476 Here is an actual example:
5479 $ mkdir -p a/sub/deeper a/sub2
5481 $ touch a/sub/deeper/file
5482 $ ls -gloRF --dired a
5485 -rw-r--r-- 1 0 Jun 10 12:27 f1
5486 -rw-r--r-- 1 0 Jun 10 12:27 f2
5487 drwxr-xr-x 3 4096 Jun 10 12:27 sub/
5488 drwxr-xr-x 2 4096 Jun 10 12:27 sub2/
5492 drwxr-xr-x 2 4096 Jun 10 12:27 deeper/
5496 -rw-r--r-- 1 0 Jun 10 12:27 file
5500 //DIRED// 48 50 84 86 120 123 158 162 217 223 282 286
5501 //SUBDIRED// 2 3 167 172 228 240 290 296
5502 //DIRED-OPTIONS// --quoting-style=literal
5505 Note that the pairs of offsets on the @samp{//DIRED//} line above delimit
5506 these names: @file{f1}, @file{f2}, @file{sub}, @file{sub2}, @file{deeper},
5508 The offsets on the @samp{//SUBDIRED//} line delimit the following
5509 directory names: @file{a}, @file{a/sub}, @file{a/sub/deeper}, @file{a/sub2}.
5511 Here is an example of how to extract the fifth entry name, @samp{deeper},
5512 corresponding to the pair of offsets, 222 and 228:
5515 $ ls -gloRF --dired a > out
5516 $ dd bs=1 skip=222 count=6 < out 2>/dev/null; echo
5520 Note that although the listing above includes a trailing slash
5521 for the @samp{deeper} entry, the offsets select the name without
5522 the trailing slash. However, if you invoke @command{ls} with @option{--dired}
5523 along with an option like @option{--escape} (aka @option{-b}) and operate
5524 on a file whose name contains special characters, notice that the backslash
5529 $ ls -blog --dired 'a b'
5530 -rw-r--r-- 1 0 Jun 10 12:28 a\ b
5532 //DIRED-OPTIONS// --quoting-style=escape
5535 If you use a quoting style that adds quote marks
5536 (e.g., @option{--quoting-style=c}), then the offsets include the quote marks.
5537 So beware that the user may select the quoting style via the environment
5538 variable @env{QUOTING_STYLE}. Hence, applications using @option{--dired}
5539 should either specify an explicit @option{--quoting-style=literal} option
5540 (aka @option{-N} or @option{--literal}) on the command line, or else be
5541 prepared to parse the escaped names.
5544 @opindex --full-time
5545 Produce long format directory listings, and list times in full. It is
5546 equivalent to using @option{--format=long} with
5547 @option{--time-style=full-iso} (@pxref{Formatting file timestamps}).
5551 Produce long format directory listings, but don't display owner information.
5557 Inhibit display of group information in a long format directory listing.
5558 (This is the default in some non-@sc{gnu} versions of @command{ls}, so we
5559 provide this option for compatibility.)
5567 @cindex inode number, printing
5568 Print the inode number (also called the file serial number and index
5569 number) of each file to the left of the file name. (This number
5570 uniquely identifies each file within a particular file system.)
5573 @itemx --format=long
5574 @itemx --format=verbose
5577 @opindex long ls @r{format}
5578 @opindex verbose ls @r{format}
5579 In addition to the name of each file, print the file type, permissions,
5580 number of hard links, owner name, group name, size, and
5581 timestamp (@pxref{Formatting file timestamps}), normally
5582 the modification time.
5584 Normally the size is printed as a byte count without punctuation, but
5585 this can be overridden (@pxref{Block size}). For example, @option{-h}
5586 prints an abbreviated, human-readable count, and
5587 @samp{--block-size="'1"} prints a byte count with the thousands
5588 separator of the current locale.
5590 For each directory that is listed, preface the files with a line
5591 @samp{total @var{blocks}}, where @var{blocks} is the total disk allocation
5592 for all files in that directory. The block size currently defaults to 1024
5593 bytes, but this can be overridden (@pxref{Block size}).
5594 The @var{blocks} computed counts each hard link separately;
5595 this is arguably a deficiency.
5597 @cindex permissions, output by @command{ls}
5598 The permissions listed are similar to symbolic mode specifications
5599 (@pxref{Symbolic Modes}). But @command{ls} combines multiple bits into the
5600 third character of each set of permissions as follows:
5603 If the setuid or setgid bit and the corresponding executable bit
5607 If the setuid or setgid bit is set but the corresponding executable bit
5611 If the sticky bit and the other-executable bit are both set.
5614 If the sticky bit is set but the other-executable bit is not set.
5617 If the executable bit is set and none of the above apply.
5623 Following the permission bits is a single character that specifies
5624 whether an alternate access method applies to the file. When that
5625 character is a space, there is no alternate access method. When it
5626 is a printing character (e.g., @samp{+}), then there is such a method.
5629 @itemx --numeric-uid-gid
5631 @opindex --numeric-uid-gid
5632 @cindex numeric uid and gid
5633 @cindex numeric user and group IDs
5634 Produce long format directory listings, but
5635 display numeric user and group IDs instead of the owner and group names.
5639 Produce long format directory listings, but don't display group information.
5640 It is equivalent to using @option{--format=long} with @option{--no-group} .
5646 @cindex disk allocation
5647 @cindex size of files, reporting
5648 Print the disk allocation of each file to the left of the file name.
5649 This is the amount of disk space used by the file, which is usually a
5650 bit more than the file's size, but it can be less if the file has holes.
5652 Normally the disk allocation is printed in units of
5653 1024 bytes, but this can be overridden (@pxref{Block size}).
5655 @cindex NFS mounts from BSD to HP-UX
5656 For files that are NFS-mounted from an HP-UX system to a BSD system,
5657 this option reports sizes that are half the correct values. On HP-UX
5658 systems, it reports sizes that are twice the correct values for files
5659 that are NFS-mounted from BSD systems. This is due to a flaw in HP-UX;
5660 it also affects the HP-UX @command{ls} program.
5667 @node Sorting the output
5668 @subsection Sorting the output
5670 @cindex sorting @command{ls} output
5671 These options change the order in which @command{ls} sorts the information
5672 it outputs. By default, sorting is done by character code
5673 (e.g., @acronym{ASCII} order).
5679 @itemx --time=status
5682 @opindex ctime@r{, printing or sorting by}
5683 @opindex status time@r{, printing or sorting by}
5684 @opindex use time@r{, printing or sorting files by}
5685 If the long listing format (e.g., @option{-l}, @option{-o}) is being used,
5686 print the status change time (the @samp{ctime} in the inode) instead of
5687 the modification time.
5688 When explicitly sorting by time (@option{--sort=time} or @option{-t})
5689 or when not using a long listing format,
5690 sort according to the status change time.
5694 @cindex unsorted directory listing
5695 @cindex directory order, listing by
5696 Primarily, like @option{-U}---do not sort; list the files in whatever
5697 order they are stored in the directory. But also enable @option{-a} (list
5698 all files) and disable @option{-l}, @option{--color}, and @option{-s} (if they
5699 were specified before the @option{-f}).
5705 @cindex reverse sorting
5706 Reverse whatever the sorting method is---e.g., list files in reverse
5707 alphabetical order, youngest first, smallest first, or whatever.
5713 @opindex size of files@r{, sorting files by}
5714 Sort by file size, largest first.
5720 @opindex modification time@r{, sorting files by}
5721 Sort by modification time (the @samp{mtime} in the inode), newest first.
5725 @itemx --time=access
5729 @opindex use time@r{, printing or sorting files by}
5730 @opindex atime@r{, printing or sorting files by}
5731 @opindex access time@r{, printing or sorting files by}
5732 If the long listing format (e.g., @option{--format=long}) is being used,
5733 print the last access time (the @samp{atime} in the inode).
5734 When explicitly sorting by time (@option{--sort=time} or @option{-t})
5735 or when not using a long listing format, sort according to the access time.
5741 @opindex none@r{, sorting option for @command{ls}}
5742 Do not sort; list the files in whatever order they are
5743 stored in the directory. (Do not do any of the other unrelated things
5744 that @option{-f} does.) This is especially useful when listing very large
5745 directories, since not doing any sorting can be noticeably faster.
5748 @itemx --sort=version
5751 @opindex version@r{, sorting option for @command{ls}}
5752 Sort by version name and number, lowest first. It behaves like a default
5753 sort, except that each sequence of decimal digits is treated numerically
5754 as an index/version number. (@xref{More details about version sort}.)
5757 @itemx --sort=extension
5760 @opindex extension@r{, sorting files by}
5761 Sort directory contents alphabetically by file extension (characters
5762 after the last @samp{.}); files with no extension are sorted first.
5767 @node More details about version sort
5768 @subsection More details about version sort
5770 The version sort takes into account the fact that file names frequently include
5771 indices or version numbers. Standard sorting functions usually do not produce
5772 the ordering that people expect because comparisons are made on a
5773 character-by-character basis. The version
5774 sort addresses this problem, and is especially useful when browsing
5775 directories that contain many files with indices/version numbers in their
5780 foo.zml-1.gz foo.zml-1.gz
5781 foo.zml-100.gz foo.zml-2.gz
5782 foo.zml-12.gz foo.zml-6.gz
5783 foo.zml-13.gz foo.zml-12.gz
5784 foo.zml-2.gz foo.zml-13.gz
5785 foo.zml-25.gz foo.zml-25.gz
5786 foo.zml-6.gz foo.zml-100.gz
5789 Note also that numeric parts with leading zeroes are considered as
5794 abc-1.007.tgz abc-1.007.tgz
5795 abc-1.012b.tgz abc-1.01a.tgz
5796 abc-1.01a.tgz abc-1.012b.tgz
5799 This functionality is implemented using the @code{strverscmp} function.
5800 @xref{String/Array Comparison, , , libc, The GNU C Library Reference Manual}.
5801 One result of that implementation decision is that @code{ls -v} does not
5802 use the locale category, @env{LC_COLLATE}. As a result, non-numeric prefixes
5803 are sorted as if @env{LC_COLLATE} were set to @code{C}.
5805 @node General output formatting
5806 @subsection General output formatting
5808 These options affect the appearance of the overall output.
5813 @itemx --format=single-column
5816 @opindex single-column @r{output of files}
5817 List one file per line. This is the default for @command{ls} when standard
5818 output is not a terminal.
5821 @itemx --format=vertical
5824 @opindex vertical @r{sorted files in columns}
5825 List files in columns, sorted vertically. This is the default for
5826 @command{ls} if standard output is a terminal. It is always the default
5827 for the @command{dir} and @command{d} programs.
5828 @sc{gnu} @command{ls} uses variable width columns to display as many files as
5829 possible in the fewest lines.
5831 @item --color [=@var{when}]
5833 @cindex color, distinguishing file types with
5834 Specify whether to use color for distinguishing file types. @var{when}
5835 may be omitted, or one of:
5838 @vindex none @r{color option}
5839 - Do not use color at all. This is the default.
5841 @vindex auto @r{color option}
5842 @cindex terminal, using color iff
5843 - Only use color if standard output is a terminal.
5845 @vindex always @r{color option}
5848 Specifying @option{--color} and no @var{when} is equivalent to
5849 @option{--color=always}.
5850 Piping a colorized listing through a pager like @command{more} or
5851 @command{less} usually produces unreadable results. However, using
5852 @code{more -f} does seem to work.
5856 @itemx --indicator-style=classify
5859 @opindex --indicator-style
5860 @cindex file type and executables, marking
5861 @cindex executables and file type, marking
5862 Append a character to each file name indicating the file type. Also,
5863 for regular files that are executable, append @samp{*}. The file type
5864 indicators are @samp{/} for directories, @samp{@@} for symbolic links,
5865 @samp{|} for FIFOs, @samp{=} for sockets, @samp{>} for doors,
5866 and nothing for regular files.
5867 @c The following sentence is the same as the one for -d.
5868 Do not follow symbolic links listed on the
5869 command line unless the @option{--dereference-command-line} (@option{-H}),
5870 @option{--dereference} (@option{-L}), or
5871 @option{--dereference-command-line-symlink-to-dir} options are specified.
5874 @itemx --indicator-style=file-type
5875 @opindex --file-type
5876 @opindex --indicator-style
5877 @cindex file type, marking
5878 Append a character to each file name indicating the file type. This is
5879 like @option{-F}, except that executables are not marked.
5881 @item --indicator-style=@var{word}
5882 @opindex --indicator-style
5883 Append a character indicator with style @var{word} to entry names,
5887 Do not append any character indicator; this is the default.
5889 Append @samp{/} for directories. This is the same as the @option{-p}
5892 Append @samp{/} for directories, @samp{@@} for symbolic links, @samp{|}
5893 for FIFOs, @samp{=} for sockets, and nothing for regular files. This is
5894 the same as the @option{--file-type} option.
5896 Append @samp{*} for executable regular files, otherwise behave as for
5897 @samp{file-type}. This is the same as the @option{-F} or
5898 @option{--classify} option.
5903 Print file sizes in 1024-byte blocks, overriding the default block
5904 size (@pxref{Block size}).
5905 This option is equivalent to @option{--block-size=1K}.
5908 @itemx --format=commas
5911 @opindex commas@r{, outputting between files}
5912 List files horizontally, with as many as will fit on each line,
5913 separated by @samp{, } (a comma and a space).
5916 @itemx --indicator-style=slash
5918 @opindex --indicator-style
5919 @cindex file type, marking
5920 Append a @samp{/} to directory names.
5923 @itemx --format=across
5924 @itemx --format=horizontal
5927 @opindex across@r{, listing files}
5928 @opindex horizontal@r{, listing files}
5929 List the files in columns, sorted horizontally.
5932 @itemx --tabsize=@var{cols}
5935 Assume that each tab stop is @var{cols} columns wide. The default is 8.
5936 @command{ls} uses tabs where possible in the output, for efficiency. If
5937 @var{cols} is zero, do not use tabs at all.
5940 @itemx --width=@var{cols}
5944 Assume the screen is @var{cols} columns wide. The default is taken
5945 from the terminal settings if possible; otherwise the environment
5946 variable @env{COLUMNS} is used if it is set; otherwise the default
5952 @node Formatting file timestamps
5953 @subsection Formatting file timestamps
5955 By default, file timestamps are listed in abbreviated form. Most
5956 locales use a timestamp like @samp{2002-03-30 23:45}. However, the
5957 default @acronym{POSIX} locale uses a date like @samp{Mar 30@ @ 2002}
5958 for non-recent timestamps, and a date-without-year and time like
5959 @samp{Mar 30 23:45} for recent timestamps.
5961 A timestamp is considered to be @dfn{recent} if it is less than six
5962 months old, and is not dated in the future. If a timestamp dated
5963 today is not listed in recent form, the timestamp is in the future,
5964 which means you probably have clock skew problems which may break
5965 programs like @command{make} that rely on file timestamps.
5968 Time stamps are listed according to the time zone rules specified by
5969 the @env{TZ} environment variable, or by the system default rules if
5970 @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
5971 with @env{TZ}, libc, The GNU C Library}.
5973 The following option changes how file timestamps are printed.
5976 @item --time-style=@var{style}
5977 @opindex --time-style
5979 List timestamps in style @var{style}. The @var{style} should
5980 be one of the following:
5985 List timestamps using @var{format}, where @var{format} is interpreted
5986 like the format argument of @command{date} (@pxref{date invocation}).
5987 For example, @option{--time-style="+%Y-%m-%d %H:%M:%S"} causes
5988 @command{ls} to list timestamps like @samp{2002-03-30 23:45:56}. As
5989 with @command{date}, @var{format}'s interpretation is affected by the
5990 @env{LC_TIME} locale category.
5992 If @var{format} contains two format strings separated by a newline,
5993 the former is used for non-recent files and the latter for recent
5994 files; if you want output columns to line up, you may need to insert
5995 spaces in one of the two formats.
5998 List timestamps in full using @acronym{ISO} 8601 date, time, and time zone
5999 format with nanosecond precision, e.g., @samp{2002-03-30
6000 23:45:56.477817180 -0700}. This style is equivalent to
6001 @samp{+%Y-%m-%d %H:%M:%S.%N %z}.
6003 This is useful because the time output includes all the information that
6004 is available from the operating system. For example, this can help
6005 explain @command{make}'s behavior, since @acronym{GNU} @command{make}
6006 uses the full timestamp to determine whether a file is out of date.
6009 List @acronym{ISO} 8601 date and time in minutes, e.g.,
6010 @samp{2002-03-30 23:45}. These timestamps are shorter than
6011 @samp{full-iso} timestamps, and are usually good enough for everyday
6012 work. This style is equivalent to @samp{+%Y-%m-%d %H:%M}.
6015 List @acronym{ISO} 8601 dates for non-recent timestamps (e.g.,
6016 @samp{2002-03-30@ }), and @acronym{ISO} 8601 month, day, hour, and
6017 minute for recent timestamps (e.g., @samp{03-30 23:45}). These
6018 timestamps are uglier than @samp{long-iso} timestamps, but they carry
6019 nearly the same information in a smaller space and their brevity helps
6020 @command{ls} output fit within traditional 80-column output lines.
6021 The following two @command{ls} invocations are equivalent:
6026 ls -l --time-style="+%Y-%m-%d $newline%m-%d %H:%M"
6027 ls -l --time-style="iso"
6032 List timestamps in a locale-dependent form. For example, a Finnish
6033 locale might list non-recent timestamps like @samp{maalis 30@ @ 2002}
6034 and recent timestamps like @samp{maalis 30 23:45}. Locale-dependent
6035 timestamps typically consume more space than @samp{iso} timestamps and
6036 are harder for programs to parse because locale conventions vary so
6037 widely, but they are easier for many people to read.
6039 The @env{LC_TIME} locale category specifies the timestamp format. The
6040 default @acronym{POSIX} locale uses timestamps like @samp{Mar 30@
6041 @ 2002} and @samp{Mar 30 23:45}; in this locale, the following two
6042 @command{ls} invocations are equivalent:
6047 ls -l --time-style="+%b %e %Y$newline%b %e %H:%M"
6048 ls -l --time-style="locale"
6051 Other locales behave differently. For example, in a German locale,
6052 @option{--time-style="locale"} might be equivalent to
6053 @option{--time-style="+%e. %b %Y $newline%e. %b %H:%M"}
6054 and might generate timestamps like @samp{30. M@"ar 2002@ } and
6055 @samp{30. M@"ar 23:45}.
6057 @item posix-@var{style}
6059 List @acronym{POSIX}-locale timestamps if the @env{LC_TIME} locale
6060 category is @acronym{POSIX}, @var{style} timestamps otherwise. For
6061 example, the default style, which is @samp{posix-long-iso}, lists
6062 timestamps like @samp{Mar 30@ @ 2002} and @samp{Mar 30 23:45} when in
6063 the @acronym{POSIX} locale, and like @samp{2002-03-30 23:45} otherwise.
6068 You can specify the default value of the @option{--time-style} option
6069 with the environment variable @env{TIME_STYLE}; if @env{TIME_STYLE} is not set
6070 the default style is @samp{posix-long-iso}. @acronym{GNU} Emacs 21 and
6071 later can parse @acronym{ISO} dates, but older Emacs versions do not, so if
6072 you are using an older version of Emacs and specify a non-@acronym{POSIX}
6073 locale, you may need to set @samp{TIME_STYLE="locale"}.
6075 To avoid certain denial-of-service attacks, timestamps that would be
6076 longer than 1000 bytes may be treated as errors.
6079 @node Formatting the file names
6080 @subsection Formatting the file names
6082 These options change how file names themselves are printed.
6088 @itemx --quoting-style=escape
6091 @opindex --quoting-style
6092 @cindex backslash sequences for file names
6093 Quote nongraphic characters in file names using alphabetic and octal
6094 backslash sequences like those used in C.
6098 @itemx --quoting-style=literal
6101 @opindex --quoting-style
6102 Do not quote file names. However, with @command{ls} nongraphic
6103 characters are still printed as question marks if the output is a
6104 terminal and you do not specify the @option{--show-control-chars}
6108 @itemx --hide-control-chars
6110 @opindex --hide-control-chars
6111 Print question marks instead of nongraphic characters in file names.
6112 This is the default if the output is a terminal and the program is
6117 @itemx --quoting-style=c
6119 @opindex --quote-name
6120 @opindex --quoting-style
6121 Enclose file names in double quotes and quote nongraphic characters as
6124 @item --quoting-style=@var{word}
6125 @opindex --quoting-style
6126 @cindex quoting style
6127 Use style @var{word} to quote file names and other strings that may
6128 contain arbitrary characters. The @var{word} should
6129 be one of the following:
6132 Output strings as-is; this is the same as the @option{-N} or
6133 @option{--literal} option.
6135 Quote strings for the shell if they contain shell metacharacters or would
6136 cause ambiguous output.
6137 The quoting is suitable for @acronym{POSIX}-compatible shells like
6138 @command{bash}, but it does not always work for incompatible shells
6141 Quote strings for the shell, even if they would normally not require quoting.
6143 Quote strings as for C character string literals, including the
6144 surrounding double-quote characters; this is the same as the
6145 @option{-Q} or @option{--quote-name} option.
6147 Quote strings as for C character string literals, except omit the
6148 surrounding double-quote
6149 characters; this is the same as the @option{-b} or @option{--escape} option.
6151 Quote strings as for C character string literals, except use
6152 surrounding quotation marks appropriate for the
6155 @c Use @t instead of @samp to avoid duplicate quoting in some output styles.
6156 Quote strings as for C character string literals, except use
6157 surrounding quotation marks appropriate for the locale, and quote
6158 @t{`like this'} instead of @t{"like
6159 this"} in the default C locale. This looks nicer on many displays.
6162 You can specify the default value of the @option{--quoting-style} option
6163 with the environment variable @env{QUOTING_STYLE}. If that environment
6164 variable is not set, the default value is @samp{literal}, but this
6165 default may change to @samp{shell} in a future version of this package.
6167 @item --show-control-chars
6168 @opindex --show-control-chars
6169 Print nongraphic characters as-is in file names.
6170 This is the default unless the output is a terminal and the program is
6176 @node dir invocation
6177 @section @command{dir}: Briefly list directory contents
6180 @cindex directory listing, brief
6182 @command{dir} (also installed as @command{d}) is equivalent to @code{ls -C
6183 -b}; that is, by default files are listed in columns, sorted vertically,
6184 and special characters are represented by backslash escape sequences.
6186 @xref{ls invocation, @command{ls}}.
6189 @node vdir invocation
6190 @section @command{vdir}: Verbosely list directory contents
6193 @cindex directory listing, verbose
6195 @command{vdir} (also installed as @command{v}) is equivalent to @code{ls -l
6196 -b}; that is, by default files are listed in long format and special
6197 characters are represented by backslash escape sequences.
6199 @node dircolors invocation
6200 @section @command{dircolors}: Color setup for @command{ls}
6204 @cindex setup for color
6206 @command{dircolors} outputs a sequence of shell commands to set up the
6207 terminal for color output from @command{ls} (and @command{dir}, etc.).
6211 eval "`dircolors [@var{option}]@dots{} [@var{file}]`"
6214 If @var{file} is specified, @command{dircolors} reads it to determine which
6215 colors to use for which file types and extensions. Otherwise, a
6216 precompiled database is used. For details on the format of these files,
6217 run @samp{dircolors --print-database}.
6220 @vindex SHELL @r{environment variable, and color}
6221 The output is a shell command to set the @env{LS_COLORS} environment
6222 variable. You can specify the shell syntax to use on the command line,
6223 or @command{dircolors} will guess it from the value of the @env{SHELL}
6224 environment variable.
6226 The program accepts the following options. Also see @ref{Common options}.
6231 @itemx --bourne-shell
6234 @opindex --bourne-shell
6235 @cindex Bourne shell syntax for color setup
6236 @cindex @command{sh} syntax for color setup
6237 Output Bourne shell commands. This is the default if the @env{SHELL}
6238 environment variable is set and does not end with @samp{csh} or
6247 @cindex C shell syntax for color setup
6248 @cindex @command{csh} syntax for color setup
6249 Output C shell commands. This is the default if @code{SHELL} ends with
6250 @command{csh} or @command{tcsh}.
6253 @itemx --print-database
6255 @opindex --print-database
6256 @cindex color database, printing
6257 @cindex database for color setup, printing
6258 @cindex printing color database
6259 Print the (compiled-in) default color configuration database. This
6260 output is itself a valid configuration file, and is fairly descriptive
6261 of the possibilities.
6268 @node Basic operations
6269 @chapter Basic operations
6271 @cindex manipulating files
6273 This chapter describes the commands for basic file manipulation:
6274 copying, moving (renaming), and deleting (removing).
6277 * cp invocation:: Copy files.
6278 * dd invocation:: Convert and copy a file.
6279 * install invocation:: Copy files and set attributes.
6280 * mv invocation:: Move (rename) files.
6281 * rm invocation:: Remove files or directories.
6282 * shred invocation:: Remove files more securely.
6287 @section @command{cp}: Copy files and directories
6290 @cindex copying files and directories
6291 @cindex files, copying
6292 @cindex directories, copying
6294 @command{cp} copies files (or, optionally, directories). The copy is
6295 completely independent of the original. You can either copy one file to
6296 another, or copy arbitrarily many files to a destination directory.
6300 cp [@var{option}]@dots{} [-T] @var{source} @var{dest}
6301 cp [@var{option}]@dots{} @var{source}@dots{} @var{directory}
6302 cp [@var{option}]@dots{} -t @var{directory} @var{source}@dots{}
6307 If two file names are given, @command{cp} copies the first file to the
6311 If the @option{--target-directory} (@option{-t}) option is given, or
6312 failing that if the last file is a directory and the
6313 @option{--no-target-directory} (@option{-T}) option is not given,
6314 @command{cp} copies each @var{source} file to the specified directory,
6315 using the @var{source}s' names.
6318 Generally, files are written just as they are read. For exceptions,
6319 see the @option{--sparse} option below.
6321 By default, @command{cp} does not copy directories. However, the
6322 @option{-R}, @option{-a}, and @option{-r} options cause @command{cp} to
6323 copy recursively by descending into source directories and copying files
6324 to corresponding destination directories.
6326 By default, @command{cp} follows symbolic links only when not copying
6327 recursively. This default can be overridden with the
6328 @option{--archive} (@option{-a}), @option{-d}, @option{--dereference}
6329 (@option{-L}), @option{--no-dereference} (@option{-P}), and
6330 @option{-H} options. If more than one of these options is specified,
6331 the last one silently overrides the others.
6333 By default, @command{cp} copies the contents of special files only
6334 when not copying recursively. This default can be overridden with the
6335 @option{--copy-contents} option.
6337 @cindex self-backups
6338 @cindex backups, making only
6339 @command{cp} generally refuses to copy a file onto itself, with the
6340 following exception: if @option{--force --backup} is specified with
6341 @var{source} and @var{dest} identical, and referring to a regular file,
6342 @command{cp} will make a backup file, either regular or numbered, as
6343 specified in the usual ways (@pxref{Backup options}). This is useful when
6344 you simply want to make a backup of an existing file before changing it.
6346 The program accepts the following options. Also see @ref{Common options}.
6353 Preserve as much as possible of the structure and attributes of the
6354 original files in the copy (but do not attempt to preserve internal
6355 directory structure; i.e., @samp{ls -U} may list the entries in a copied
6356 directory in a different order).
6357 Equivalent to @option{-dpPR}.
6360 @itemx @w{@kbd{--backup}[=@var{method}]}
6363 @vindex VERSION_CONTROL
6364 @cindex backups, making
6365 @xref{Backup options}.
6366 Make a backup of each file that would otherwise be overwritten or removed.
6367 As a special case, @command{cp} makes a backup of @var{source} when the force
6368 and backup options are given and @var{source} and @var{dest} are the same
6369 name for an existing, regular file. One useful application of this
6370 combination of options is this tiny Bourne shell script:
6374 # Usage: backup FILE...
6375 # Create a @sc{gnu}-style backup of each listed FILE.
6377 cp --backup --force -- "$i" "$i"
6381 @item --copy-contents
6382 @cindex directories, copying recursively
6383 @cindex copying directories recursively
6384 @cindex recursively copying directories
6385 @cindex non-directories, copying as special files
6386 If copying recursively, copy the contents of any special files (e.g.,
6387 FIFOs and device files) as if they were regular files. This means
6388 trying to read the data in each source file and writing it to the
6389 destination. It is usually a mistake to use this option, as it
6390 normally has undesirable effects on special files like FIFOs and the
6391 ones typically found in the @file{/dev} directory. In most cases,
6392 @code{cp -R --copy-contents} will hang indefinitely trying to read
6393 from FIFOs and special files like @file{/dev/console}, and it will
6394 fill up your destination disk if you use it to copy @file{/dev/zero}.
6395 This option has no effect unless copying recursively, and it does not
6396 affect the copying of symbolic links.
6400 @cindex symbolic links, copying
6401 @cindex hard links, preserving
6402 Copy symbolic links as symbolic links rather than copying the files that
6403 they point to, and preserve hard links between source files in the copies.
6404 Equivalent to @option{--no-dereference --preserve=links}.
6410 When copying without this option and an existing destination file cannot
6411 be opened for writing, the copy fails. However, with @option{--force}),
6412 when a destination file cannot be opened, @command{cp} then unlinks it and
6413 tries to open it again. Contrast this behavior with that enabled by
6414 @option{--link} and @option{--symbolic-link}, whereby the destination file
6415 is never opened but rather is unlinked unconditionally. Also see the
6416 description of @option{--remove-destination}.
6420 If a command line argument specifies a symbolic link, then copy the
6421 file it points to rather than the symbolic link itself. However,
6422 copy (preserving its nature) any symbolic link that is encountered
6423 via recursive traversal.
6426 @itemx --interactive
6428 @opindex --interactive
6429 Prompt whether to overwrite existing regular destination files.
6435 Make hard links instead of copies of non-directories.
6438 @itemx --dereference
6440 @opindex --dereference
6441 Always follow symbolic links.
6444 @itemx --no-dereference
6446 @opindex --no-dereference
6447 @cindex symbolic links, copying
6448 Copy symbolic links as symbolic links rather than copying the files that
6452 @itemx @w{@kbd{--preserve}[=@var{attribute_list}]}
6455 @cindex file information, preserving
6456 Preserve the specified attributes of the original files.
6457 If specified, the @var{attribute_list} must be a comma-separated list
6458 of one or more of the following strings:
6462 Preserve the permission attributes.
6464 Preserve the owner and group. On most modern systems,
6465 only the super-user may change the owner of a file, and regular users
6466 may preserve the group ownership of a file only if they happen to be
6467 a member of the desired group.
6469 Preserve the times of last access and last modification.
6471 Preserve in the destination files
6472 any links between corresponding source files.
6473 @c Give examples illustrating how hard links are preserved.
6474 @c Also, show how soft links map to hard links with -L and -H.
6476 Preserve all file attributes.
6477 Equivalent to specifying all of the above.
6478 @c Mention ACLs here.
6481 Using @option{--preserve} with no @var{attribute_list} is equivalent
6482 to @option{--preserve=mode,ownership,timestamps}.
6484 In the absence of this option, each destination file is created with the
6485 permissions of the corresponding source file, minus the bits set in the
6486 umask and minus the set-user-ID and set-group-ID bits.
6487 @xref{File permissions}.
6489 @itemx @w{@kbd{--no-preserve}=@var{attribute_list}}
6490 @cindex file information, preserving
6491 Do not preserve the specified attributes. The @var{attribute_list}
6492 has the same form as for @option{--preserve}.
6496 @cindex parent directories and @command{cp}
6497 Form the name of each destination file by appending to the target
6498 directory a slash and the specified name of the source file. The last
6499 argument given to @command{cp} must be the name of an existing directory.
6500 For example, the command:
6503 cp --parents a/b/c existing_dir
6507 copies the file @file{a/b/c} to @file{existing_dir/a/b/c}, creating
6508 any missing intermediate directories.
6510 @itemx @w{@kbd{--reply}[=@var{how}]}
6512 @cindex interactivity
6513 @c FIXME: remove in 2008
6514 @strong{Deprecated: to be removed in 2008.}@*
6515 Using @option{--reply=yes} makes @command{cp} act as if @samp{yes} were
6516 given as a response to every prompt about a destination file. That effectively
6517 cancels any preceding @option{--interactive} or @option{-i} option.
6518 Specify @option{--reply=no} to make @command{cp} act as if @samp{no} were
6519 given as a response to every prompt about a destination file.
6520 Specify @option{--reply=query} to make @command{cp} prompt the user
6521 about each existing destination file.
6528 @opindex --recursive
6529 @cindex directories, copying recursively
6530 @cindex copying directories recursively
6531 @cindex recursively copying directories
6532 @cindex non-directories, copying as special files
6533 Copy directories recursively. Symbolic links are not followed by
6534 default; see the @option{--archive} (@option{-a}), @option{-d},
6535 @option{--dereference} (@option{-L}), @option{--no-dereference}
6536 (@option{-P}), and @option{-H} options. Special files are copied by
6537 creating a destination file of the same type as the source; see the
6538 @option{--copy-contents} option. It is not portable to use
6539 @option{-r} to copy symbolic links or special files. On some
6540 non-@sc{gnu} systems, @option{-r} implies the equivalent of
6541 @option{-L} and @option{--copy-contents} for historical reasons.
6542 Also, it is not portable to use @option{-R} to copy symbolic links
6543 unless you also specify @option{-P}, as @acronym{POSIX} allows
6544 implementations that dereference symbolic links by default.
6546 @item --remove-destination
6547 @opindex --remove-destination
6548 Remove each existing destination file before attempting to open it
6549 (contrast with @option{-f} above).
6551 @item --sparse=@var{when}
6552 @opindex --sparse=@var{when}
6553 @cindex sparse files, copying
6554 @cindex holes, copying files with
6555 @findex read @r{system call, and holes}
6556 A @dfn{sparse file} contains @dfn{holes}---a sequence of zero bytes that
6557 does not occupy any physical disk blocks; the @samp{read} system call
6558 reads these as zeroes. This can both save considerable disk space and
6559 increase speed, since many binary files contain lots of consecutive zero
6560 bytes. By default, @command{cp} detects holes in input source files via a crude
6561 heuristic and makes the corresponding output file sparse as well.
6562 Only regular files may be sparse.
6564 The @var{when} value can be one of the following:
6567 The default behavior: if the input file is sparse, attempt to make
6568 the output file sparse, too. However, if an output file exists but
6569 refers to a non-regular file, then do not attempt to make it sparse.
6572 For each sufficiently long sequence of zero bytes in the input file,
6573 attempt to create a corresponding hole in the output file, even if the
6574 input file does not appear to be sparse.
6575 This is useful when the input file resides on a file system
6576 that does not support sparse files
6577 (for example, @samp{efs} file systems in SGI IRIX 5.3 and earlier),
6578 but the output file is on a type of file system that does support them.
6579 Holes may be created only in regular files, so if the destination file
6580 is of some other type, @command{cp} does not even try to make it sparse.
6583 Never make the output file sparse.
6584 This is useful in creating a file for use with the @command{mkswap} command,
6585 since such a file must not have any holes.
6588 @optStripTrailingSlashes
6591 @itemx --symbolic-link
6593 @opindex --symbolic-link
6594 @cindex symbolic links, copying with
6595 Make symbolic links instead of copies of non-directories. All source
6596 file names must be absolute (starting with @samp{/}) unless the
6597 destination files are in the current directory. This option merely
6598 results in an error message on systems that do not support symbolic links.
6604 @optNoTargetDirectory
6610 @cindex newer files, copying only
6611 Do not copy a non-directory that has an existing destination with the
6612 same or newer modification time. If time stamps are being preserved,
6613 the comparison is to the source time stamp truncated to the
6614 resolutions of the destination file system and of the system calls
6615 used to update time stamps; this avoids duplicate work if several
6616 @samp{cp -pu} commands are executed with the same source and
6623 Print the name of each file before copying it.
6626 @itemx --one-file-system
6628 @opindex --one-file-system
6629 @cindex file systems, omitting copying to different
6630 Skip subdirectories that are on different file systems from the one that
6631 the copy started on.
6632 However, mount point directories @emph{are} copied.
6640 @section @command{dd}: Convert and copy a file
6643 @cindex converting while copying a file
6645 @command{dd} copies a file (from standard input to standard output, by
6646 default) with a changeable I/O block size, while optionally performing
6647 conversions on it. Synopses:
6650 dd [@var{operand}]@dots{}
6654 The only options are @option{--help} and @option{--version}.
6655 @xref{Common options}. @command{dd} accepts the following operands.
6661 Read from @var{file} instead of standard input.
6665 Write to @var{file} instead of standard output. Unless
6666 @samp{conv=notrunc} is given, @command{dd} truncates @var{file} to zero
6667 bytes (or the size specified with @samp{seek=}).
6669 @item ibs=@var{bytes}
6671 @cindex block size of input
6672 @cindex input block size
6673 Read @var{bytes} bytes at a time.
6675 @item obs=@var{bytes}
6677 @cindex block size of output
6678 @cindex output block size
6679 Write @var{bytes} bytes at a time.
6681 @item bs=@var{bytes}
6684 Both read and write @var{bytes} bytes at a time. This overrides
6685 @samp{ibs} and @samp{obs}.
6687 @item cbs=@var{bytes}
6689 @cindex block size of conversion
6690 @cindex conversion block size
6691 Convert @var{bytes} bytes at a time.
6693 @item skip=@var{blocks}
6695 Skip @var{blocks} @samp{ibs}-byte blocks in the input file before copying.
6697 @item seek=@var{blocks}
6699 Skip @var{blocks} @samp{obs}-byte blocks in the output file before copying.
6701 @item count=@var{blocks}
6703 Copy @var{blocks} @samp{ibs}-byte blocks from the input file, instead
6704 of everything until the end of the file.
6706 @item conv=@var{conversion}[,@var{conversion}]@dots{}
6708 Convert the file as specified by the @var{conversion} argument(s).
6709 (No spaces around any comma(s).)
6716 @opindex ascii@r{, converting to}
6717 Convert @acronym{EBCDIC} to @acronym{ASCII},
6718 using the conversion table specified by @acronym{POSIX}.
6719 This provides a 1:1 translation for all 256 bytes.
6722 @opindex ebcdic@r{, converting to}
6723 Convert @acronym{ASCII} to @acronym{EBCDIC}.
6724 This is the inverse of the @samp{ascii} conversion.
6727 @opindex alternate ebcdic@r{, converting to}
6728 Convert @acronym{ASCII} to alternate @acronym{EBCDIC},
6729 using the alternate conversion table specified by @acronym{POSIX}.
6730 This is not a 1:1 translation, but reflects common historical practice
6731 for @samp{~}, @samp{[}, and @samp{]}.
6733 The @samp{ascii}, @samp{ebcdic}, and @samp{ibm} conversions are
6737 @opindex block @r{(space-padding)}
6738 For each line in the input, output @samp{cbs} bytes, replacing the
6739 input newline with a space and padding with spaces as necessary.
6743 Replace trailing spaces in each @samp{cbs}-sized input block with a
6746 The @samp{block} and @samp{unblock} conversions are mutually exclusive.
6749 @opindex lcase@r{, converting to}
6750 Change uppercase letters to lowercase.
6753 @opindex ucase@r{, converting to}
6754 Change lowercase letters to uppercase.
6756 The @samp{lcase} and @samp{ucase} conversions are mutually exclusive.
6759 @opindex swab @r{(byte-swapping)}
6760 @cindex byte-swapping
6761 Swap every pair of input bytes. @sc{gnu} @command{dd}, unlike others, works
6762 when an odd number of bytes are read---the last byte is simply copied
6763 (since there is nothing to swap it with).
6767 @cindex read errors, ignoring
6768 Continue after read errors.
6772 @cindex creating output file, avoiding
6773 Do not create the output file; the output file must already exist.
6777 @cindex creating output file, requiring
6778 Fail if the output file already exists; @command{dd} must create the
6781 The @samp{excl} and @samp{nocreat} conversions are mutually exclusive.
6785 @cindex truncating output file, avoiding
6786 Do not truncate the output file.
6789 @opindex sync @r{(padding with nulls)}
6790 Pad every input block to size of @samp{ibs} with trailing zero bytes.
6791 When used with @samp{block} or @samp{unblock}, pad with spaces instead of
6796 @cindex synchronized data writes, before finishing
6797 Synchronize output data just before finishing. This forces a physical
6798 write of output data.
6802 @cindex synchronized data and metadata writes, before finishing
6803 Synchronize output data and metadata just before finishing. This
6804 forces a physical write of output data and metadata.
6808 @item iflag=@var{flag}[,@var{flag}]@dots{}
6810 Access the input file using the flags specified by the @var{flag}
6811 argument(s). (No spaces around any comma(s).)
6813 @item oflag=@var{flag}[,@var{flag}]@dots{}
6815 Access the output file using the flags specified by the @var{flag}
6816 argument(s). (No spaces around any comma(s).)
6824 @cindex appending to the output file
6825 Write in append mode, so that even if some other process is writing to
6826 this file, every @command{dd} write will append to the current
6827 contents of the file. This flag makes sense only for output.
6832 Use direct I/O for data, avoiding the buffer cache.
6836 @cindex synchronized data reads
6837 Use synchronized I/O for data. For the output file, this forces a
6838 physical write of output data on each write. For the input file,
6839 this flag can matter when reading from a remote file that has been
6840 written to synchronously by some other process. Metadata (e.g.,
6841 last-access and last-modified time) is not necessarily synchronized.
6845 @cindex synchronized data and metadata I/O
6846 Use synchronized I/O for both data and metadata.
6850 @cindex nonblocking I/O
6851 Use non-blocking I/O.
6855 @cindex symbolic links, following
6856 Do not follow symbolic links.
6860 @cindex controlling terminal
6861 Do not assign the file to be a controlling terminal for @command{dd}.
6862 This has no effect when the file is not a terminal.
6863 On many hosts (e.g., @acronym{GNU}/Linux hosts), this option has no effect
6869 Use binary I/O. This option has an effect only on nonstandard
6870 platforms that distinguish binary from text I/O.
6875 Use text I/O. Like @samp{binary}, this option has no effect on
6880 These flags are not supported on all systems, and @samp{dd} rejects
6881 attempts to use them when they are not supported. When reading from
6882 standard input or writing to standard output, the @samp{nofollow} and
6883 @samp{noctty} flags should not be specified, and the other flags
6884 (e.g., @samp{nonblock}) can affect how other processes behave with the
6885 affected file descriptors, even after @command{dd} exits.
6889 @cindex multipliers after numbers
6890 The numeric-valued strings above (@var{bytes} and @var{blocks}) can be
6891 followed by a multiplier: @samp{b}=512, @samp{c}=1,
6892 @samp{w}=2, @samp{x@var{m}}=@var{m}, or any of the
6893 standard block size suffixes like @samp{k}=1024 (@pxref{Block size}).
6895 Use different @command{dd} invocations to use different block sizes for
6896 skipping and I/O@. For example, the following shell commands copy data
6897 in 512 KiB blocks between a disk and a tape, but do not save or restore a
6898 4 KiB label at the start of the disk:
6901 disk=/dev/rdsk/c0t1d0s2
6904 # Copy all but the label from disk to tape.
6905 (dd bs=4k skip=1 count=0 && dd bs=512k) <$disk >$tape
6907 # Copy from tape back to disk, but leave the disk label alone.
6908 (dd bs=4k seek=1 count=0 && dd bs=512k) <$tape >$disk
6911 Sending an @samp{INFO} signal to a running @command{dd}
6912 process makes it print I/O statistics to standard error
6913 and then resume copying. In the example below,
6914 @command{dd} is run in the background to copy 10 million blocks.
6915 The @command{kill} command makes it output intermediate I/O statistics,
6916 and when @command{dd} completes, it outputs the final statistics.
6919 $ dd if=/dev/zero of=/dev/null count=10MB & pid=$!
6920 $ kill -s INFO $pid; wait $pid
6921 3385223+0 records in
6922 3385223+0 records out
6923 1733234176 bytes (1.7 GB) copied, 6.42173 seconds, 270 MB/s
6924 10000000+0 records in
6925 10000000+0 records out
6926 5120000000 bytes (5.1 GB) copied, 18.913 seconds, 271 MB/s
6929 @vindex POSIXLY_CORRECT
6930 On systems lacking the @samp{INFO} signal @command{dd} responds to the
6931 @samp{USR1} signal instead, unless the @env{POSIXLY_CORRECT}
6932 environment variable is set.
6937 @node install invocation
6938 @section @command{install}: Copy files and set attributes
6941 @cindex copying files and setting attributes
6943 @command{install} copies files while setting their permission modes and, if
6944 possible, their owner and group. Synopses:
6947 install [@var{option}]@dots{} [-T] @var{source} @var{dest}
6948 install [@var{option}]@dots{} @var{source}@dots{} @var{directory}
6949 install [@var{option}]@dots{} -t @var{directory} @var{source}@dots{}
6950 install [@var{option}]@dots{} -d @var{directory}@dots{}
6955 If two file names are given, @command{install} copies the first file to the
6959 If the @option{--target-directory} (@option{-t}) option is given, or
6960 failing that if the last file is a directory and the
6961 @option{--no-target-directory} (@option{-T}) option is not given,
6962 @command{install} copies each @var{source} file to the specified
6963 directory, using the @var{source}s' names.
6966 If the @option{--directory} (@option{-d}) option is given,
6967 @command{install} creates each @var{directory} and any missing parent
6971 @cindex Makefiles, installing programs in
6972 @command{install} is similar to @command{cp}, but allows you to control the
6973 attributes of destination files. It is typically used in Makefiles to
6974 copy programs into their destination directories. It refuses to copy
6975 files onto themselves.
6977 The program accepts the following options. Also see @ref{Common options}.
6985 Ignored; for compatibility with old Unix versions of @command{install}.
6990 @opindex --directory
6991 @cindex directories, creating with given attributes
6992 @cindex parent directories, creating missing
6993 @cindex leading directories, creating missing
6994 Create each given directory and any missing parent directories, setting
6995 the owner, group and mode as given on the command line or to the
6996 defaults. It also gives any parent directories it creates those
6997 attributes. (This is different from the SunOS 4.x @command{install}, which
6998 gives directories that it creates the default attributes.)
7000 @item -g @var{group}
7001 @itemx --group=@var{group}
7004 @cindex group ownership of installed files, setting
7005 Set the group ownership of installed files or directories to
7006 @var{group}. The default is the process's current group. @var{group}
7007 may be either a group name or a numeric group ID.
7010 @itemx --mode=@var{mode}
7013 @cindex permissions of installed files, setting
7014 Set the permissions for the installed file or directory to @var{mode},
7015 which can be either an octal number, or a symbolic mode as in
7016 @command{chmod}, with @samp{a=} (no access allowed to anyone) as the
7017 point of departure (@pxref{File permissions}).
7018 The default mode is @samp{u=rwx,go=rx}---read, write,
7019 and execute for the owner, and read and execute for group and other.
7021 @item -o @var{owner}
7022 @itemx --owner=@var{owner}
7025 @cindex ownership of installed files, setting
7026 @cindex appropriate privileges
7027 @vindex root @r{as default owner}
7028 If @command{install} has appropriate privileges (is run as root), set the
7029 ownership of installed files or directories to @var{owner}. The default
7030 is @code{root}. @var{owner} may be either a user name or a numeric user
7034 @itemx --preserve-timestamps
7036 @opindex --preserve-timestamps
7037 @cindex timestamps of installed files, preserving
7038 Set the time of last access and the time of last modification of each
7039 installed file to match those of each corresponding original file.
7040 When a file is installed without this option, its last access and
7041 last modification times are both set to the time of installation.
7042 This option is useful if you want to use the last modification times
7043 of installed files to keep track of when they were last built as opposed
7044 to when they were last installed.
7050 @cindex symbol table information, stripping
7051 @cindex stripping symbol table information
7052 Strip the symbol tables from installed binary executables.
7058 @optNoTargetDirectory
7064 Print the name of each file before copying it.
7072 @section @command{mv}: Move (rename) files
7076 @command{mv} moves or renames files (or directories). Synopses:
7079 mv [@var{option}]@dots{} [-T] @var{source} @var{dest}
7080 mv [@var{option}]@dots{} @var{source}@dots{} @var{directory}
7081 mv [@var{option}]@dots{} -t @var{directory} @var{source}@dots{}
7086 If two file names are given, @command{mv} moves the first file to the
7090 If the @option{--target-directory} (@option{-t}) option is given, or
7091 failing that if the last file is a directory and the
7092 @option{--no-target-directory} (@option{-T}) option is not given,
7093 @command{mv} moves each @var{source} file to the specified
7094 directory, using the @var{source}s' names.
7097 @command{mv} can move any type of file from one file system to another.
7098 Prior to version @code{4.0} of the fileutils,
7099 @command{mv} could move only regular files between file systems.
7100 For example, now @command{mv} can move an entire directory hierarchy
7101 including special device files from one partition to another. It first
7102 uses some of the same code that's used by @code{cp -a} to copy the
7103 requested directories and files, then (assuming the copy succeeded)
7104 it removes the originals. If the copy fails, then the part that was
7105 copied to the destination partition is removed. If you were to copy
7106 three directories from one partition to another and the copy of the first
7107 directory succeeded, but the second didn't, the first would be left on
7108 the destination partition and the second and third would be left on the
7111 @cindex prompting, and @command{mv}
7112 If a destination file exists but is normally unwritable, standard input
7113 is a terminal, and the @option{-f} or @option{--force} option is not given,
7114 @command{mv} prompts the user for whether to replace the file. (You might
7115 own the file, or have write permission on its directory.) If the
7116 response is not affirmative, the file is skipped.
7118 @emph{Warning}: If you try to move a symlink that points to a directory,
7119 and you specify the symlink with a trailing slash, then @command{mv}
7120 doesn't move the symlink but instead moves the directory referenced
7121 by the symlink. @xref{Trailing slashes}.
7123 The program accepts the following options. Also see @ref{Common options}.
7133 @cindex prompts, omitting
7134 Do not prompt the user before removing a destination file.
7137 @itemx --interactive
7139 @opindex --interactive
7140 @cindex prompts, forcing
7141 Prompt whether to overwrite each existing destination file, regardless
7143 If the response is not affirmative, the file is skipped.
7145 @itemx @w{@kbd{--reply}[=@var{how}]}
7147 @cindex interactivity
7148 @c FIXME: remove in 2008
7149 @strong{Deprecated: to be removed in 2008.}@*
7150 Specifying @option{--reply=yes} is equivalent to using @option{--force}.
7151 Specify @option{--reply=no} to make @command{mv} act as if @samp{no} were
7152 given as a response to every prompt about a destination file.
7153 Specify @option{--reply=query} to make @command{mv} prompt the user
7154 about each existing destination file.
7155 Note that @option{--reply=no} has an effect only when @command{mv} would prompt
7156 without @option{-i} or equivalent, i.e., when a destination file exists and is
7157 not writable, standard input is a terminal, and no @option{-f} (or equivalent)
7158 option is specified.
7164 @cindex newer files, moving only
7165 Do not move a non-directory that has an existing destination with the
7166 same or newer modification time.
7167 If the move is across file system boundaries, the comparison is to the
7168 source time stamp truncated to the resolutions of the destination file
7169 system and of the system calls used to update time stamps; this avoids
7170 duplicate work if several @samp{mv -u} commands are executed with the
7171 same source and destination.
7177 Print the name of each file before moving it.
7179 @optStripTrailingSlashes
7185 @optNoTargetDirectory
7193 @section @command{rm}: Remove files or directories
7196 @cindex removing files or directories
7198 @command{rm} removes each given @var{file}. By default, it does not remove
7199 directories. Synopsis:
7202 rm [@var{option}]@dots{} [@var{file}]@dots{}
7205 @cindex prompting, and @command{rm}
7206 If a file is unwritable, standard input is a terminal, and the @option{-f}
7207 or @option{--force} option is not given, or the @option{-i} or
7208 @option{--interactive} option @emph{is} given, @command{rm} prompts the user
7209 for whether to remove the file.
7210 If the response is not affirmative, the file is skipped.
7212 @emph{Warning}: If you use @command{rm} to remove a file, it is usually
7213 possible to recover the contents of that file. If you want more assurance
7214 that the contents are truly unrecoverable, consider using @command{shred}.
7216 The program accepts the following options. Also see @ref{Common options}.
7223 @opindex --directory
7224 @cindex directories, removing with @code{unlink}
7227 Use the @code{unlink} function unconditionally rather than attempting
7228 to check whether the file is a directory and using @code{rmdir} if it
7229 is a directory. This can be useful on corrupted file systems where
7230 @code{unlink} works even though other, file-checking functions fail.
7231 For directories, this works
7232 only if you have appropriate privileges and if your operating system supports
7233 @code{unlink} for directories. Because unlinking a directory causes any files
7234 in the deleted directory to become unreferenced, it is wise to @command{fsck}
7235 the file system afterwards.
7241 Ignore nonexistent files and never prompt the user.
7242 Ignore any previous @option{--interactive} (@option{-i}) option.
7245 @itemx --interactive
7247 @opindex --interactive
7248 Prompt whether to remove each file.
7249 If the response is not affirmative, the file is skipped.
7250 Ignore any previous @option{--force} (@option{-f}) option.
7252 @itemx --preserve-root
7253 @opindex --preserve-root
7254 @cindex root directory, disallow recursive destruction
7255 Fail upon any attempt to remove the file system root, @file{/},
7256 when used with the @option{--recursive} option.
7257 Without @option{--recursive}, this option has no effect.
7258 @xref{Treating / specially}.
7260 @itemx --no-preserve-root
7261 @opindex --no-preserve-root
7262 @cindex root directory, allow recursive destruction
7263 Cancel the effect of any preceding @option{--preserve-root} option.
7264 @xref{Treating / specially}.
7271 @opindex --recursive
7272 @cindex directories, removing (recursively)
7273 Remove the listed directories and their contents recursively.
7279 Print the name of each file before removing it.
7283 @cindex files beginning with @samp{-}, removing
7284 @cindex @samp{-}, removing files beginning with
7285 One common question is how to remove files whose names begin with a
7286 @samp{-}. @sc{gnu} @command{rm}, like every program that uses the @code{getopt}
7287 function to parse its arguments, lets you use the @samp{--} option to
7288 indicate that all following arguments are non-options. To remove a file
7289 called @file{-f} in the current directory, you could type either:
7302 @opindex - @r{and Unix @command{rm}}
7303 The Unix @command{rm} program's use of a single @samp{-} for this purpose
7304 predates the development of the getopt standard syntax.
7309 @node shred invocation
7310 @section @command{shred}: Remove files more securely
7313 @cindex data, erasing
7314 @cindex erasing data
7316 @command{shred} overwrites devices or files, to help prevent even
7317 very expensive hardware from recovering the data.
7319 Ordinarily when you remove a file (@pxref{rm invocation}), the data is
7320 not actually destroyed. Only the index listing where the file is
7321 stored is destroyed, and the storage is made available for reuse.
7322 There are undelete utilities that will attempt to reconstruct the index
7323 and can bring the file back if the parts were not reused.
7325 On a busy system with a nearly-full drive, space can get reused in a few
7326 seconds. But there is no way to know for sure. If you have sensitive
7327 data, you may want to be sure that recovery is not possible by actually
7328 overwriting the file with non-sensitive data.
7330 However, even after doing that, it is possible to take the disk back
7331 to a laboratory and use a lot of sensitive (and expensive) equipment
7332 to look for the faint ``echoes'' of the original data underneath the
7333 overwritten data. If the data has only been overwritten once, it's not
7336 The best way to remove something irretrievably is to destroy the media
7337 it's on with acid, melt it down, or the like. For cheap removable media
7338 like floppy disks, this is the preferred method. However, hard drives
7339 are expensive and hard to melt, so the @command{shred} utility tries
7340 to achieve a similar effect non-destructively.
7342 This uses many overwrite passes, with the data patterns chosen to
7343 maximize the damage they do to the old data. While this will work on
7344 floppies, the patterns are designed for best effect on hard drives.
7345 For more details, see the source code and Peter Gutmann's paper
7346 @uref{http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html,
7347 @cite{Secure Deletion of Data from Magnetic and Solid-State Memory}},
7348 from the proceedings of the Sixth @acronym{USENIX} Security Symposium (San Jose,
7349 California, July 22--25, 1996).
7351 @strong{Please note} that @command{shred} relies on a very important assumption:
7352 that the file system overwrites data in place. This is the traditional
7353 way to do things, but many modern file system designs do not satisfy this
7354 assumption. Exceptions include:
7359 Log-structured or journaled file systems, such as those supplied with
7360 AIX and Solaris, and JFS, ReiserFS, XFS, Ext3 (in @code{data=journal} mode),
7361 BFS, NTFS, etc.@: when they are configured to journal @emph{data}.
7364 File systems that write redundant data and carry on even if some writes
7365 fail, such as RAID-based file systems.
7368 File systems that make snapshots, such as Network Appliance's NFS server.
7371 File systems that cache in temporary locations, such as NFS version 3
7375 Compressed file systems.
7378 In the particular case of ext3 file systems, the above disclaimer applies (and
7379 @command{shred} is thus of limited effectiveness) only in @code{data=journal}
7380 mode, which journals file data in addition to just metadata. In both
7381 the @code{data=ordered} (default) and @code{data=writeback} modes,
7382 @command{shred} works as usual. Ext3 journaling modes can be changed
7383 by adding the @code{data=something} option to the mount options for a
7384 particular file system in the @file{/etc/fstab} file, as documented in
7385 the mount man page (man mount).
7387 If you are not sure how your file system operates, then you should assume
7388 that it does not overwrite data in place, which means that shred cannot
7389 reliably operate on regular files in your file system.
7391 Generally speaking, it is more reliable to shred a device than a file,
7392 since this bypasses the problem of file system design mentioned above.
7393 However, even shredding devices is not always completely reliable. For
7394 example, most disks map out bad sectors invisibly to the application; if
7395 the bad sectors contain sensitive data, @command{shred} won't be able to
7398 @command{shred} makes no attempt to detect or report this problem, just as
7399 it makes no attempt to do anything about backups. However, since it is
7400 more reliable to shred devices than files, @command{shred} by default does
7401 not truncate or remove the output file. This default is more suitable
7402 for devices, which typically cannot be truncated and should not be
7405 Finally, consider the risk of backups and mirrors.
7406 File system backups and remote mirrors may contain copies of the
7407 file that cannot be removed, and that will allow a shredded file
7408 to be recovered later. So if you keep any data you may later want
7409 to destroy using @command{shred}, be sure that it is not backed up or mirrored.
7412 shred [@var{option}]@dots{} @var{file}[@dots{}]
7415 The program accepts the following options. Also see @ref{Common options}.
7423 @cindex force deletion
7424 Override file permissions if necessary to allow overwriting.
7427 @itemx -n @var{NUMBER}
7428 @itemx --iterations=@var{NUMBER}
7429 @opindex -n @var{NUMBER}
7430 @opindex --iterations=@var{NUMBER}
7431 @cindex iterations, selecting the number of
7432 By default, @command{shred} uses 25 passes of overwrite. This is enough
7433 for all of the useful overwrite patterns to be used at least once.
7434 You can reduce this to save time, or increase it if you have a lot of
7437 @item -s @var{BYTES}
7438 @itemx --size=@var{BYTES}
7439 @opindex -s @var{BYTES}
7440 @opindex --size=@var{BYTES}
7441 @cindex size of file to shred
7442 Shred the first @var{BYTES} bytes of the file. The default is to shred
7443 the whole file. @var{BYTES} can be followed by a size specification like
7444 @samp{K}, @samp{M}, or @samp{G} to specify a multiple. @xref{Block size}.
7450 @cindex removing files after shredding
7451 After shredding a file, truncate it (if possible) and then remove it.
7452 If a file has multiple links, only the named links will be removed.
7458 Display status updates as sterilization proceeds.
7464 By default, @command{shred} rounds the size of a regular file up to the next
7465 multiple of the file system block size to fully erase the last block of the file.
7466 Use @option{--exact} to suppress that behavior.
7467 Thus, by default if you shred a 10-byte regular file on a system with 512-byte
7468 blocks, the resulting file will be 512 bytes long. With this option,
7469 shred does not increase the apparent size of the file.
7475 Normally, the last pass that @command{shred} writes is made up of
7476 random data. If this would be conspicuous on your hard drive (for
7477 example, because it looks like encrypted data), or you just think
7478 it's tidier, the @option{--zero} option adds an additional overwrite pass with
7479 all zero bits. This is in addition to the number of passes specified
7480 by the @option{--iterations} option.
7484 You might use the following command to erase all trace of the
7485 file system you'd created on the floppy disk in your first drive.
7486 That command takes about 20 minutes to erase a ``1.44MB'' (actually
7490 shred --verbose /dev/fd0
7493 Similarly, to erase all data on a selected partition of
7494 your hard disk, you could give a command like this:
7497 shred --verbose /dev/sda5
7500 A @var{file} of @samp{-} denotes standard output.
7501 The intended use of this is to shred a removed temporary file.
7505 i=`tempfile -m 0600`
7508 echo "Hello, world" >&3
7513 However, the command @samp{shred - >file} does not shred the contents
7514 of @var{file}, since the shell truncates @var{file} before invoking
7515 @command{shred}. Use the command @samp{shred file} or (if using a
7516 Bourne-compatible shell) the command @samp{shred - 1<>file} instead.
7521 @node Special file types
7522 @chapter Special file types
7524 @cindex special file types
7525 @cindex file types, special
7527 This chapter describes commands which create special types of files (and
7528 @command{rmdir}, which removes directories, one special file type).
7530 @cindex special file types
7532 Although Unix-like operating systems have markedly fewer special file
7533 types than others, not @emph{everything} can be treated only as the
7534 undifferentiated byte stream of @dfn{normal files}. For example, when a
7535 file is created or removed, the system must record this information,
7536 which it does in a @dfn{directory}---a special type of file. Although
7537 you can read directories as normal files, if you're curious, in order
7538 for the system to do its job it must impose a structure, a certain
7539 order, on the bytes of the file. Thus it is a ``special'' type of file.
7541 Besides directories, other special file types include named pipes
7542 (FIFOs), symbolic links, sockets, and so-called @dfn{special files}.
7545 * link invocation:: Make a hard link via the link syscall
7546 * ln invocation:: Make links between files.
7547 * mkdir invocation:: Make directories.
7548 * mkfifo invocation:: Make FIFOs (named pipes).
7549 * mknod invocation:: Make block or character special files.
7550 * readlink invocation:: Print the referent of a symbolic link.
7551 * rmdir invocation:: Remove empty directories.
7552 * unlink invocation:: Remove files via the unlink syscall
7556 @node link invocation
7557 @section @command{link}: Make a hard link via the link syscall
7560 @cindex links, creating
7561 @cindex hard links, creating
7562 @cindex creating links (hard only)
7564 @command{link} creates a single hard link at a time.
7565 It is a minimalist interface to the system-provided
7566 @code{link} function. @xref{Hard Links, , , libc,
7567 The GNU C Library Reference Manual}.
7568 It avoids the bells and whistles of the more commonly-used
7569 @command{ln} command (@pxref{ln invocation}).
7573 link @var{filename} @var{linkname}
7576 @var{filename} must specify an existing file, and @var{linkname}
7577 must specify a nonexistent entry in an existing directory.
7578 @command{link} simply calls @code{link (@var{filename}, @var{linkname})}
7581 On a @acronym{GNU} system, this command acts like @samp{ln --directory
7582 --no-target-directory @var{filename} @var{linkname}}. However, the
7583 @option{--directory} and @option{--no-target-directory} options are
7584 not specified by @acronym{POSIX}, and the @command{link} command is
7585 more portable in practice.
7591 @section @command{ln}: Make links between files
7594 @cindex links, creating
7595 @cindex hard links, creating
7596 @cindex symbolic (soft) links, creating
7597 @cindex creating links (hard or soft)
7599 @cindex file systems and hard links
7600 @command{ln} makes links between files. By default, it makes hard links;
7601 with the @option{-s} option, it makes symbolic (or @dfn{soft}) links.
7605 ln [@var{option}]@dots{} [-T] @var{target} @var{linkname}
7606 ln [@var{option}]@dots{} @var{target}
7607 ln [@var{option}]@dots{} @var{target}@dots{} @var{directory}
7608 ln [@var{option}]@dots{} -t @var{directory} @var{target}@dots{}
7614 If two file names are given, @command{ln} creates a link to the first
7615 file from the second.
7618 If one @var{target} is given, @command{ln} creates a link to that file
7619 in the current directory.
7622 If the @option{--target-directory} (@option{-t}) option is given, or
7623 failing that if the last file is a directory and the
7624 @option{--no-target-directory} (@option{-T}) option is not given,
7625 @command{ln} creates a link to each @var{target} file in the specified
7626 directory, using the @var{target}s' names.
7630 Normally @command{ln} does not remove existing files. Use the
7631 @option{--force} (@option{-f}) option to remove them unconditionally,
7632 the @option{--interactive} (@option{-i}) option to remove them
7633 conditionally, and the @option{--backup} (@option{-b}) option to
7636 @cindex hard link, defined
7637 @cindex inode, and hard links
7638 A @dfn{hard link} is another name for an existing file; the link and the
7639 original are indistinguishable. Technically speaking, they share the
7640 same inode, and the inode contains all the information about a
7641 file---indeed, it is not incorrect to say that the inode @emph{is} the
7642 file. On all existing implementations, you cannot make a hard link to
7643 a directory, and hard links cannot cross file system boundaries. (These
7644 restrictions are not mandated by @acronym{POSIX}, however.)
7646 @cindex dereferencing symbolic links
7647 @cindex symbolic link, defined
7648 @dfn{Symbolic links} (@dfn{symlinks} for short), on the other hand, are
7649 a special file type (which not all kernels support: System V release 3
7650 (and older) systems lack symlinks) in which the link file actually
7651 refers to a different file, by name. When most operations (opening,
7652 reading, writing, and so on) are passed the symbolic link file, the
7653 kernel automatically @dfn{dereferences} the link and operates on the
7654 target of the link. But some operations (e.g., removing) work on the
7655 link file itself, rather than on its target. @xref{Symbolic Links,,,
7656 libc, The GNU C Library Reference Manual}.
7658 The program accepts the following options. Also see @ref{Common options}.
7669 @opindex --directory
7670 @cindex hard links to directories
7671 Allow the super-user to attempt to make hard links to directories.
7672 However, note that this will probably fail due to
7673 system restrictions, even for the super-user.
7679 Remove existing destination files.
7682 @itemx --interactive
7684 @opindex --interactive
7685 @cindex prompting, and @command{ln}
7686 Prompt whether to remove existing destination files.
7689 @itemx --no-dereference
7691 @opindex --no-dereference
7692 Do not treat the last operand specially when it is a symbolic link to
7693 a directory. Instead, treat it as if it were a normal file.
7695 When the destination is an actual directory (not a symlink to one),
7696 there is no ambiguity. The link is created in that directory.
7697 But when the specified destination is a symlink to a directory,
7698 there are two ways to treat the user's request. @command{ln} can
7699 treat the destination just as it would a normal directory and create
7700 the link in it. On the other hand, the destination can be viewed as a
7701 non-directory---as the symlink itself. In that case, @command{ln}
7702 must delete or backup that symlink before creating the new link.
7703 The default is to treat a destination that is a symlink to a directory
7704 just like a directory.
7706 This option is weaker than the @option{--no-target-directory}
7707 (@option{-T}) option, so it has no effect if both options are given.
7713 Make symbolic links instead of hard links. This option merely produces
7714 an error message on systems that do not support symbolic links.
7720 @optNoTargetDirectory
7726 Print the name of each file before linking it.
7737 # Create link ../a pointing to a in that directory.
7738 # Not really useful because it points to itself.
7743 # Change to the target before creating symlinks to avoid being confused.
7749 # Hard coded file names don't move well.
7750 ln -s $(pwd)/a /some/dir/
7754 # Relative file names survive directory moves and also
7755 # work across networked file systems.
7756 ln -s afile anotherfile
7757 ln -s ../adir/afile yetanotherfile
7761 @node mkdir invocation
7762 @section @command{mkdir}: Make directories
7765 @cindex directories, creating
7766 @cindex creating directories
7768 @command{mkdir} creates directories with the specified names. Synopsis:
7771 mkdir [@var{option}]@dots{} @var{name}@dots{}
7774 If a @var{name} is an existing file but not a directory, @command{mkdir} prints
7775 a warning message on stderr and will exit with a status of 1 after
7776 processing any remaining @var{name}s. The same is done when a @var{name} is an
7777 existing directory and the -p option is not given. If a @var{name} is an
7778 existing directory and the -p option is given, @command{mkdir} will ignore it.
7779 That is, @command{mkdir} will not print a warning, raise an error, or change
7780 the mode of the directory (even if the -m option is given), and will
7781 move on to processing any remaining @var{name}s.
7783 The program accepts the following options. Also see @ref{Common options}.
7788 @itemx --mode=@var{mode}
7791 @cindex modes of created directories, setting
7792 Set the mode of created directories to @var{mode}, which is symbolic as
7793 in @command{chmod} and uses @samp{a=rwx} (read, write and execute allowed for
7794 everyone) for the point of the departure. @xref{File permissions}.
7800 @cindex parent directories, creating
7801 Make any missing parent directories for each argument. The mode for parent
7802 directories is set to the umask modified by @samp{u+wx}.
7803 Ignore arguments corresponding to existing directories.
7809 Print a message for each created directory. This is most useful with
7816 @node mkfifo invocation
7817 @section @command{mkfifo}: Make FIFOs (named pipes)
7820 @cindex FIFOs, creating
7821 @cindex named pipes, creating
7822 @cindex creating FIFOs (named pipes)
7824 @command{mkfifo} creates FIFOs (also called @dfn{named pipes}) with the
7825 specified names. Synopsis:
7828 mkfifo [@var{option}] @var{name}@dots{}
7831 A @dfn{FIFO} is a special file type that permits independent processes
7832 to communicate. One process opens the FIFO file for writing, and
7833 another for reading, after which data can flow as with the usual
7834 anonymous pipe in shells or elsewhere.
7836 The program accepts the following option. Also see @ref{Common options}.
7841 @itemx --mode=@var{mode}
7844 @cindex modes of created FIFOs, setting
7845 Set the mode of created FIFOs to @var{mode}, which is symbolic as in
7846 @command{chmod} and uses @samp{a=rw} (read and write allowed for everyone)
7847 for the point of departure. @xref{File permissions}.
7854 @node mknod invocation
7855 @section @command{mknod}: Make block or character special files
7858 @cindex block special files, creating
7859 @cindex character special files, creating
7861 @command{mknod} creates a FIFO, character special file, or block special
7862 file with the specified name. Synopsis:
7865 mknod [@var{option}]@dots{} @var{name} @var{type} [@var{major} @var{minor}]
7868 @cindex special files
7869 @cindex block special files
7870 @cindex character special files
7871 Unlike the phrase ``special file type'' above, the term @dfn{special
7872 file} has a technical meaning on Unix: something that can generate or
7873 receive data. Usually this corresponds to a physical piece of hardware,
7874 e.g., a printer or a disk. (These files are typically created at
7875 system-configuration time.) The @command{mknod} command is what creates
7876 files of this type. Such devices can be read either a character at a
7877 time or a ``block'' (many characters) at a time, hence we say there are
7878 @dfn{block special} files and @dfn{character special} files.
7880 The arguments after @var{name} specify the type of file to make:
7885 @opindex p @r{for FIFO file}
7889 @opindex b @r{for block special file}
7890 for a block special file
7893 @c Don't document the `u' option -- it's just a synonym for `c'.
7894 @c Do *any* versions of mknod still use it?
7896 @opindex c @r{for character special file}
7897 @c @opindex u @r{for character special file}
7898 for a character special file
7902 When making a block or character special file, the major and minor
7903 device numbers must be given after the file type.
7904 If a major or minor device number begins with @samp{0x} or @samp{0X},
7905 it is interpreted as hexadecimal; otherwise, if it begins with @samp{0},
7906 as octal; otherwise, as decimal.
7908 The program accepts the following option. Also see @ref{Common options}.
7913 @itemx --mode=@var{mode}
7916 Set the mode of created files to @var{mode}, which is symbolic as in
7917 @command{chmod} and uses @samp{a=rw} as the point of departure.
7918 @xref{File permissions}.
7925 @node readlink invocation
7926 @section @command{readlink}: Print the referent of a symbolic link
7929 @cindex displaying value of a symbolic link
7931 @command{readlink} may work in one of two supported modes:
7937 @command{readlink} outputs the value of the given symbolic link.
7938 If @command{readlink} is invoked with an argument other than the name
7939 of a symbolic link, it produces no output and exits with a nonzero exit code.
7941 @item Canonicalize mode
7943 @command{readlink} outputs the absolute name of the given file which contains
7944 no @file{.}, @file{..} components nor any repeated separators
7945 (@file{/}) or symbolic links.
7950 readlink [@var{option}] @var{file}
7953 By default, @command{readlink} operates in readlink mode.
7955 The program accepts the following options. Also see @ref{Common options}.
7960 @itemx --canonicalize
7962 @opindex --canonicalize
7963 Activate canonicalize mode.
7964 If any component of the file name except the last one is missing or unavailable,
7965 @command{readlink} produces no output and exits with a nonzero exit code.
7968 @itemx --canonicalize-existing
7970 @opindex --canonicalize-existing
7971 Activate canonicalize mode.
7972 If any component is missing or unavailable, @command{readlink} produces
7973 no output and exits with a nonzero exit code.
7976 @itemx --canonicalize-missing
7978 @opindex --canonicalize-missing
7979 Activate canonicalize mode.
7980 If any component is missing or unavailable, @command{readlink} treats it
7986 @opindex --no-newline
7987 Do not output the trailing newline.
7997 Suppress most error messages.
8003 Report error messages.
8007 The @command{readlink} utility first appeared in OpenBSD 2.1.
8012 @node rmdir invocation
8013 @section @command{rmdir}: Remove empty directories
8016 @cindex removing empty directories
8017 @cindex directories, removing empty
8019 @command{rmdir} removes empty directories. Synopsis:
8022 rmdir [@var{option}]@dots{} @var{directory}@dots{}
8025 If any @var{directory} argument does not refer to an existing empty
8026 directory, it is an error.
8028 The program accepts the following option. Also see @ref{Common options}.
8032 @item --ignore-fail-on-non-empty
8033 @opindex --ignore-fail-on-non-empty
8034 @cindex directory deletion, ignoring failures
8035 Ignore each failure to remove a directory that is solely because
8036 the directory is non-empty.
8042 @cindex parent directories, removing
8043 Remove @var{directory}, then try to remove each component of @var{directory}.
8044 So, for example, @samp{rmdir -p a/b/c} is similar to @samp{rmdir a/b/c a/b a}.
8045 As such, it fails if any of those directories turns out not to be empty.
8046 Use the @option{--ignore-fail-on-non-empty} option to make it so such
8047 a failure does not evoke a diagnostic and does not cause @command{rmdir} to
8048 exit unsuccessfully.
8054 @cindex directory deletion, reporting
8055 Give a diagnostic for each successful removal.
8056 @var{directory} is removed.
8060 @xref{rm invocation}, for how to remove non-empty directories (recursively).
8065 @node unlink invocation
8066 @section @command{unlink}: Remove files via the unlink syscall
8069 @cindex removing files or directories (via the unlink syscall)
8071 @command{unlink} deletes a single specified file name.
8072 It is a minimalist interface to the system-provided
8073 @code{unlink} function. @xref{Deleting Files, , , libc,
8074 The GNU C Library Reference Manual}. Synopsis:
8075 It avoids the bells and whistles of the more commonly-used
8076 @command{rm} command (@pxref{rm invocation}).
8079 unlink @var{filename}
8082 On some systems @code{unlink} can be used to delete the name of a
8083 directory. On others, it can be used that way only by a privileged user.
8084 In the GNU system @code{unlink} can never delete the name of a directory.
8086 The @command{unlink} command honors the @option{--help} and
8087 @option{--version} options. To remove a file whose name begins with
8088 @samp{-}, prefix the name with @samp{./}, e.g., @samp{unlink ./--help}.
8093 @node Changing file attributes
8094 @chapter Changing file attributes
8096 @cindex changing file attributes
8097 @cindex file attributes, changing
8098 @cindex attributes, file
8100 A file is not merely its contents, a name, and a file type
8101 (@pxref{Special file types}). A file also has an owner (a user ID), a
8102 group (a group ID), permissions (what the owner can do with the file,
8103 what people in the group can do, and what everyone else can do), various
8104 timestamps, and other information. Collectively, we call these a file's
8107 These commands change file attributes.
8110 * chgrp invocation:: Change file groups.
8111 * chmod invocation:: Change access permissions.
8112 * chown invocation:: Change file owners and groups.
8113 * touch invocation:: Change file timestamps.
8117 @node chown invocation
8118 @section @command{chown}: Change file owner and group
8121 @cindex file ownership, changing
8122 @cindex group ownership, changing
8123 @cindex changing file ownership
8124 @cindex changing group ownership
8126 @command{chown} changes the user and/or group ownership of each given @var{file}
8127 to @var{new-owner} or to the user and group of an existing reference file.
8131 chown [@var{option}]@dots{} @{@var{new-owner} | --reference=@var{ref_file}@} @var{file}@dots{}
8134 If used, @var{new-owner} specifies the new owner and/or group as follows
8135 (with no embedded white space):
8138 [@var{owner}] [ : [@var{group}] ]
8145 If only an @var{owner} (a user name or numeric user ID) is given, that
8146 user is made the owner of each given file, and the files' group is not
8149 @item owner@samp{:}group
8150 If the @var{owner} is followed by a colon and a @var{group} (a
8151 group name or numeric group ID), with no spaces between them, the group
8152 ownership of the files is changed as well (to @var{group}).
8155 If a colon but no group name follows @var{owner}, that user is
8156 made the owner of the files and the group of the files is changed to
8157 @var{owner}'s login group.
8160 If the colon and following @var{group} are given, but the owner
8161 is omitted, only the group of the files is changed; in this case,
8162 @command{chown} performs the same function as @command{chgrp}.
8165 If only a colon is given, or if @var{new-owner} is empty, neither the
8166 owner nor the group is changed.
8170 Some older scripts may still use @samp{.} in place of the @samp{:} separator.
8171 @acronym{POSIX} 1003.1-2001 (@pxref{Standards conformance}) does not
8172 require support for that, but for backward compatibility @acronym{GNU}
8173 @command{chown} supports @samp{.} so long as no ambiguity results.
8174 New scripts should avoid the use of @samp{.} because it is not
8175 portable, and because it has undesirable results if the entire
8176 @var{owner@samp{.}group} happens to identify a user whose name
8179 The @command{chown} command sometimes clears the set-user-ID or
8180 set-group-ID permission bits. This behavior depends on the policy and
8181 functionality of the underlying @code{chown} system call, which may
8182 make system-dependent file mode modifications outside the control of
8183 the @command{chown} command. For example, the @command{chown} command
8184 might not affect those bits when operated as the superuser, or if the
8185 bits signify some function other than executable permission (e.g.,
8187 When in doubt, check the underlying system behavior.
8189 The program accepts the following options. Also see @ref{Common options}.
8197 @cindex changed owners, verbosely describing
8198 Verbosely describe the action for each @var{file} whose ownership
8207 @cindex error messages, omitting
8208 Do not print error messages about files whose ownership cannot be
8211 @itemx @w{@kbd{--from}=@var{old-owner}}
8213 @cindex symbolic links, changing owner
8214 Change a @var{file}'s ownership only if it has current attributes specified
8215 by @var{old-owner}. @var{old-owner} has the same form as @var{new-owner}
8217 This option is useful primarily from a security standpoint in that
8218 it narrows considerably the window of potential abuse.
8219 For example, to reflect a user ID numbering change for one user's files
8220 without an option like this, @code{root} might run
8223 find / -owner OLDUSER -print0 | xargs -0 chown -h NEWUSER
8226 But that is dangerous because the interval between when the @command{find}
8227 tests the existing file's owner and when the @command{chown} is actually run
8229 One way to narrow the gap would be to invoke chown for each file
8233 find / -owner OLDUSER -exec chown -h NEWUSER @{@} \;
8236 But that is very slow if there are many affected files.
8237 With this option, it is safer (the gap is narrower still)
8238 though still not perfect:
8241 chown -h -R --from=OLDUSER NEWUSER /
8245 @opindex --dereference
8246 @cindex symbolic links, changing owner
8248 Do not act on symbolic links themselves but rather on what they point to.
8249 This is the default.
8252 @itemx --no-dereference
8254 @opindex --no-dereference
8255 @cindex symbolic links, changing owner
8257 Act on symbolic links themselves instead of what they point to.
8258 This mode relies on the @code{lchown} system call.
8259 On systems that do not provide the @code{lchown} system call,
8260 @command{chown} fails when a file specified on the command line
8262 By default, no diagnostic is issued for symbolic links encountered
8263 during a recursive traversal, but see @option{--verbose}.
8265 @itemx --preserve-root
8266 @opindex --preserve-root
8267 @cindex root directory, disallow recursive modification
8268 Fail upon any attempt to recursively change the file system root, @file{/}.
8269 Without @option{--recursive}, this option has no effect.
8270 @xref{Treating / specially}.
8272 @itemx --no-preserve-root
8273 @opindex --no-preserve-root
8274 @cindex root directory, allow recursive modification
8275 Cancel the effect of any preceding @option{--preserve-root} option.
8276 @xref{Treating / specially}.
8278 @item --reference=@var{ref_file}
8279 @opindex --reference
8280 Change the user and group of each @var{file} to be the same as those of
8281 @var{ref_file}. If @var{ref_file} is a symbolic link, do not use the
8282 user and group of the symbolic link, but rather those of the file it
8289 Output a diagnostic for every file processed.
8290 If a symbolic link is encountered during a recursive traversal
8291 on a system without the @code{lchown} system call, and @option{--no-dereference}
8292 is in effect, then issue a diagnostic saying neither the symbolic link nor
8293 its referent is being changed.
8298 @opindex --recursive
8299 @cindex recursively changing file ownership
8300 Recursively change ownership of directories and their contents.
8303 @xref{Traversing symlinks}.
8306 @xref{Traversing symlinks}.
8309 @xref{Traversing symlinks}.
8318 # Change the owner of /u to "root".
8321 # Likewise, but also change its group to "staff".
8324 # Change the owner of /u and subfiles to "root".
8329 @node chgrp invocation
8330 @section @command{chgrp}: Change group ownership
8333 @cindex group ownership, changing
8334 @cindex changing group ownership
8336 @command{chgrp} changes the group ownership of each given @var{file}
8337 to @var{group} (which can be either a group name or a numeric group ID)
8338 or to the group of an existing reference file. Synopsis:
8341 chgrp [@var{option}]@dots{} @{@var{group} | --reference=@var{ref_file}@} @var{file}@dots{}
8344 The program accepts the following options. Also see @ref{Common options}.
8352 @cindex changed files, verbosely describing
8353 Verbosely describe the action for each @var{file} whose group actually
8362 @cindex error messages, omitting
8363 Do not print error messages about files whose group cannot be
8367 @opindex --dereference
8368 @cindex symbolic links, changing owner
8370 Do not act on symbolic links themselves but rather on what they point to.
8371 This is the default.
8374 @itemx --no-dereference
8376 @opindex --no-dereference
8377 @cindex symbolic links, changing group
8379 Act on symbolic links themselves instead of what they point to.
8380 This mode relies on the @code{lchown} system call.
8381 On systems that do not provide the @code{lchown} system call,
8382 @command{chgrp} fails when a file specified on the command line
8384 By default, no diagnostic is issued for symbolic links encountered
8385 during a recursive traversal, but see @option{--verbose}.
8387 @itemx --preserve-root
8388 @opindex --preserve-root
8389 @cindex root directory, disallow recursive modification
8390 Fail upon any attempt to recursively change the file system root, @file{/}.
8391 Without @option{--recursive}, this option has no effect.
8392 @xref{Treating / specially}.
8394 @itemx --no-preserve-root
8395 @opindex --no-preserve-root
8396 @cindex root directory, allow recursive modification
8397 Cancel the effect of any preceding @option{--preserve-root} option.
8398 @xref{Treating / specially}.
8400 @item --reference=@var{ref_file}
8401 @opindex --reference
8402 Change the group of each @var{file} to be the same as that of
8403 @var{ref_file}. If @var{ref_file} is a symbolic link, do not use the
8404 group of the symbolic link, but rather that of the file it refers to.
8410 Output a diagnostic for every file processed.
8411 If a symbolic link is encountered during a recursive traversal
8412 on a system without the @code{lchown} system call, and @option{--no-dereference}
8413 is in effect, then issue a diagnostic saying neither the symbolic link nor
8414 its referent is being changed.
8419 @opindex --recursive
8420 @cindex recursively changing group ownership
8421 Recursively change the group ownership of directories and their contents.
8424 @xref{Traversing symlinks}.
8427 @xref{Traversing symlinks}.
8430 @xref{Traversing symlinks}.
8439 # Change the group of /u to "staff".
8442 # Change the group of /u and subfiles to "staff".
8447 @node chmod invocation
8448 @section @command{chmod}: Change access permissions
8451 @cindex changing access permissions
8452 @cindex access permissions, changing
8453 @cindex permissions, changing access
8455 @command{chmod} changes the access permissions of the named files. Synopsis:
8458 chmod [@var{option}]@dots{} @{@var{mode} | --reference=@var{ref_file}@} @var{file}@dots{}
8461 @cindex symbolic links, permissions of
8462 @command{chmod} never changes the permissions of symbolic links, since
8463 the @command{chmod} system call cannot change their permissions.
8464 This is not a problem since the permissions of symbolic links are
8465 never used. However, for each symbolic link listed on the command
8466 line, @command{chmod} changes the permissions of the pointed-to file.
8467 In contrast, @command{chmod} ignores symbolic links encountered during
8468 recursive directory traversals.
8470 If used, @var{mode} specifies the new permissions.
8471 For details, see the section on @ref{File permissions}.
8472 If you really want @var{mode} to have a leading @samp{-}, you should
8473 use @option{--} first, e.g., @samp{chmod -- -w file}. Typically,
8474 though, @samp{chmod a-w file} is preferable, and @command{chmod -w
8475 file} (without the @option{--}) complains if it behaves differently
8476 from what @samp{chmod a-w file} would do.
8478 The program accepts the following options. Also see @ref{Common options}.
8486 Verbosely describe the action for each @var{file} whose permissions
8495 @cindex error messages, omitting
8496 Do not print error messages about files whose permissions cannot be
8499 @itemx --preserve-root
8500 @opindex --preserve-root
8501 @cindex root directory, disallow recursive modification
8502 Fail upon any attempt to recursively change the file system root, @file{/}.
8503 Without @option{--recursive}, this option has no effect.
8504 @xref{Treating / specially}.
8506 @itemx --no-preserve-root
8507 @opindex --no-preserve-root
8508 @cindex root directory, allow recursive modification
8509 Cancel the effect of any preceding @option{--preserve-root} option.
8510 @xref{Treating / specially}.
8516 Verbosely describe the action or non-action taken for every @var{file}.
8518 @item --reference=@var{ref_file}
8519 @opindex --reference
8520 Change the mode of each @var{file} to be the same as that of @var{ref_file}.
8521 @xref{File permissions}.
8522 If @var{ref_file} is a symbolic link, do not use the mode
8523 of the symbolic link, but rather that of the file it refers to.
8528 @opindex --recursive
8529 @cindex recursively changing access permissions
8530 Recursively change permissions of directories and their contents.
8537 @node touch invocation
8538 @section @command{touch}: Change file timestamps
8541 @cindex changing file timestamps
8542 @cindex file timestamps, changing
8543 @cindex timestamps, changing file
8545 @command{touch} changes the access and/or modification times of the
8546 specified files. Synopsis:
8549 touch [@var{option}]@dots{} @var{file}@dots{}
8552 @cindex empty files, creating
8553 Any @var{file} that does not exist is created empty.
8555 @cindex permissions, for changing file timestamps
8556 If changing both the access and modification times to the current
8557 time, @command{touch} can change the timestamps for files that the user
8558 running it does not own but has write permission for. Otherwise, the
8559 user must own the files.
8561 Although @command{touch} provides options for changing two of the times---the
8562 times of last access and modification---of a file, there is actually
8563 a third one as well: the inode change time. This is often referred to
8564 as a file's @code{ctime}.
8565 The inode change time represents the time when the file's meta-information
8566 last changed. One common example of this is when the permissions of a
8567 file change. Changing the permissions doesn't access the file, so
8568 the atime doesn't change, nor does it modify the file, so the mtime
8569 doesn't change. Yet, something about the file itself has changed,
8570 and this must be noted somewhere. This is the job of the ctime field.
8571 This is necessary, so that, for example, a backup program can make a
8572 fresh copy of the file, including the new permissions value.
8573 Another operation that modifies a file's ctime without affecting
8574 the others is renaming. In any case, it is not possible, in normal
8575 operations, for a user to change the ctime field to a user-specified value.
8578 Time stamps assume the time zone rules specified by the @env{TZ}
8579 environment variable, or by the system default rules if @env{TZ} is
8580 not set. @xref{TZ Variable,, Specifying the Time Zone with @env{TZ},
8581 libc, The GNU C Library}. You can avoid avoid ambiguities during
8582 daylight saving transitions by using @sc{utc} time stamps.
8584 The program accepts the following options. Also see @ref{Common options}.
8590 @itemx --time=access
8594 @opindex atime@r{, changing}
8595 @opindex access @r{time, changing}
8596 @opindex use @r{time, changing}
8597 Change the access time only.
8602 @opindex --no-create
8603 Do not create files that do not exist.
8606 @itemx --date=@var{time}
8610 Use @var{time} instead of the current time. It can contain month names,
8611 time zones, @samp{am} and @samp{pm}, @samp{yesterday}, etc. For
8612 example, @option{--date="2004-02-27 14:19:13.489392193 +0530"}
8613 specifies the instant of time that is 489,392,193 nanoseconds after
8614 February 27, 2004 at 2:19:13 PM in a time zone that is 5 hours and 30
8615 minutes east of @acronym{UTC}. @xref{Date input formats}.
8616 File systems that do not support high-resolution time stamps
8617 silently ignore any excess precision here.
8621 @cindex BSD @command{touch} compatibility
8622 Ignored; for compatibility with BSD versions of @command{touch}.
8626 @itemx --time=modify
8629 @opindex mtime@r{, changing}
8630 @opindex modify @r{time, changing}
8631 Change the modification time only.
8634 @itemx --reference=@var{file}
8636 @opindex --reference
8637 Use the times of the reference @var{file} instead of the current time.
8638 If this option is combined with the @option{--date=@var{time}}
8639 (@option{-d @var{time}}) option, the reference @var{file}'s time is
8640 the origin for any relative @var{time}s given, but is otherwise ignored.
8641 For example, @samp{-r foo -d '-5 seconds'} specifies a time stamp
8642 equal to five seconds before the corresponding time stamp for @file{foo}.
8644 @item -t [[@var{CC}]@var{YY}]@var{MMDDhhmm}[.@var{ss}]
8645 Use the argument (optional four-digit or two-digit years, months,
8646 days, hours, minutes, optional seconds) instead of the current time.
8647 If the year is specified with only two digits, then @var{CC}
8648 is 20 for years in the range 0 @dots{} 68, and 19 for years in
8649 69 @dots{} 99. If no digits of the year are specified,
8650 the argument is interpreted as a date in the current year.
8654 @vindex _POSIX2_VERSION
8655 On older systems, @command{touch} supports an obsolete syntax, as follows.
8656 If no timestamp is given with any of the @option{-d}, @option{-r}, or
8657 @option{-t} options, and if there are two or more @var{file}s and the
8658 first @var{file} is of the form @samp{@var{MMDDhhmm}[@var{YY}]} and this
8659 would be a valid argument to the @option{-t} option (if the @var{YY}, if
8660 any, were moved to the front), that argument is interpreted as the time
8661 for the other files instead of as a file name.
8662 This obsolete behavior can be enabled or disabled with the
8663 @env{_POSIX2_VERSION} environment variable (@pxref{Standards
8664 conformance}), but portable scripts should avoid commands whose
8665 behavior depends on this variable.
8666 For example, use @samp{touch ./12312359 main.c} or @samp{touch -t
8667 12312359 main.c} rather than the ambiguous @samp{touch 12312359 main.c}.
8677 No disk can hold an infinite amount of data. These commands report on
8678 how much disk storage is in use or available. (This has nothing much to
8679 do with how much @emph{main memory}, i.e., RAM, a program is using when
8680 it runs; for that, you want @command{ps} or @command{pstat} or @command{swap}
8681 or some such command.)
8684 * df invocation:: Report file system disk space usage.
8685 * du invocation:: Estimate file space usage.
8686 * stat invocation:: Report file or file system status.
8687 * sync invocation:: Synchronize memory and disk.
8692 @section @command{df}: Report file system disk space usage
8695 @cindex file system disk usage
8696 @cindex disk usage by file system
8698 @command{df} reports the amount of disk space used and available on
8699 file systems. Synopsis:
8702 df [@var{option}]@dots{} [@var{file}]@dots{}
8705 With no arguments, @command{df} reports the space used and available on all
8706 currently mounted file systems (of all types). Otherwise, @command{df}
8707 reports on the file system containing each argument @var{file}.
8709 Normally the disk space is printed in units of
8710 1024 bytes, but this can be overridden (@pxref{Block size}).
8711 Non-integer quantities are rounded up to the next higher unit.
8713 @cindex disk device file
8714 @cindex device file, disk
8715 If an argument @var{file} is a disk device file containing a mounted
8716 file system, @command{df} shows the space available on that file system
8717 rather than on the file system containing the device node (i.e., the root
8718 file system). @sc{gnu} @command{df} does not attempt to determine the disk usage
8719 on unmounted file systems, because on most kinds of systems doing so
8720 requires extremely nonportable intimate knowledge of file system
8723 The program accepts the following options. Also see @ref{Common options}.
8731 @cindex automounter file systems
8732 @cindex ignore file systems
8733 Include in the listing file systems that have a size of 0 blocks, which
8734 are omitted by default. Such file systems are typically special-purpose
8735 pseudo-file-systems, such as automounter entries. Also, file systems of
8736 type ``ignore'' or ``auto'', supported by some operating systems, are
8737 only included if this option is specified.
8740 @itemx --block-size=@var{size}
8742 @opindex --block-size
8743 @cindex file system sizes
8744 Scale sizes by @var{size} before printing them (@pxref{Block size}).
8745 For example, @option{-BG} prints sizes in units of 1,073,741,824 bytes.
8751 Equivalent to @option{--si}.
8758 List inode usage information instead of block usage. An inode (short
8759 for index node) contains information about a file such as its owner,
8760 permissions, timestamps, and location on the disk.
8764 @cindex kibibytes for file system sizes
8765 Print sizes in 1024-byte blocks, overriding the default block size
8766 (@pxref{Block size}).
8767 This option is equivalent to @option{--block-size=1K}.
8773 @cindex file system types, limiting output to certain
8774 Limit the listing to local file systems. By default, remote file systems
8779 @cindex file system space, retrieving old data more quickly
8780 Do not invoke the @code{sync} system call before getting any usage data.
8781 This may make @command{df} run significantly faster on systems with many
8782 disks, but on some systems (notably SunOS) the results may be slightly
8783 out of date. This is the default.
8786 @itemx --portability
8788 @opindex --portability
8789 @cindex one-line output format
8790 @cindex @acronym{POSIX} output format
8791 @cindex portable output format
8792 @cindex output format, portable
8793 Use the @acronym{POSIX} output format. This is like the default format except
8798 The information about each file system is always printed on exactly
8799 one line; a mount device is never put on a line by itself. This means
8800 that if the mount device name is more than 20 characters long (e.g., for
8801 some network mounts), the columns are misaligned.
8804 The labels in the header output line are changed to conform to @acronym{POSIX}.
8811 @cindex file system space, retrieving current data more slowly
8812 Invoke the @code{sync} system call before getting any usage data. On
8813 some systems (notably SunOS), doing this yields more up to date results,
8814 but in general this option makes @command{df} much slower, especially when
8815 there are many or very busy file systems.
8817 @item -t @var{fstype}
8818 @itemx --type=@var{fstype}
8821 @cindex file system types, limiting output to certain
8822 Limit the listing to file systems of type @var{fstype}. Multiple
8823 file system types can be specified by giving multiple @option{-t} options.
8824 By default, nothing is omitted.
8829 @opindex --print-type
8830 @cindex file system types, printing
8831 Print each file system's type. The types printed here are the same ones
8832 you can include or exclude with @option{-t} and @option{-x}. The particular
8833 types printed are whatever is supported by the system. Here are some of
8834 the common names (this list is certainly not exhaustive):
8839 @cindex @acronym{NFS} file system type
8840 An @acronym{NFS} file system, i.e., one mounted over a network from another
8841 machine. This is the one type name which seems to be used uniformly by
8844 @item 4.2@r{, }ufs@r{, }efs@dots{}
8845 @cindex Linux file system types
8846 @cindex local file system types
8847 @opindex 4.2 @r{file system type}
8848 @opindex ufs @r{file system type}
8849 @opindex efs @r{file system type}
8850 A file system on a locally-mounted hard disk. (The system might even
8851 support more than one type here; Linux does.)
8853 @item hsfs@r{, }cdfs
8854 @cindex CD-ROM file system type
8855 @cindex High Sierra file system
8856 @opindex hsfs @r{file system type}
8857 @opindex cdfs @r{file system type}
8858 A file system on a CD-ROM drive. HP-UX uses @samp{cdfs}, most other
8859 systems use @samp{hsfs} (@samp{hs} for ``High Sierra'').
8862 @cindex PC file system
8863 @cindex DOS file system
8864 @cindex MS-DOS file system
8865 @cindex diskette file system
8867 An MS-DOS file system, usually on a diskette.
8871 @item -x @var{fstype}
8872 @itemx --exclude-type=@var{fstype}
8874 @opindex --exclude-type
8875 Limit the listing to file systems not of type @var{fstype}.
8876 Multiple file system types can be eliminated by giving multiple
8877 @option{-x} options. By default, no file system types are omitted.
8880 Ignored; for compatibility with System V versions of @command{df}.
8888 @section @command{du}: Estimate file space usage
8891 @cindex file space usage
8892 @cindex disk usage for files
8894 @command{du} reports the amount of disk space used by the specified files
8895 and for each subdirectory (of directory arguments). Synopsis:
8898 du [@var{option}]@dots{} [@var{file}]@dots{}
8901 With no arguments, @command{du} reports the disk space for the current
8902 directory. Normally the disk space is printed in units of
8903 1024 bytes, but this can be overridden (@pxref{Block size}).
8904 Non-integer quantities are rounded up to the next higher unit.
8906 The program accepts the following options. Also see @ref{Common options}.
8914 Show counts for all files, not just directories.
8916 @itemx --apparent-size
8917 @opindex --apparent-size
8918 Print apparent sizes, rather than disk usage. The apparent size of a
8919 file is the number of bytes reported by @code{wc -c} on regular files,
8920 or more generally, @code{ls -l --block-size=1} or @code{stat --format=%s}.
8921 For example, a file containing the word @samp{zoo} with no newline would,
8922 of course, have an apparent size of 3. Such a small file may require
8923 anywhere from 0 to 16 KiB or more of disk space, depending on
8924 the type and configuration of the file system on which the file resides.
8925 However, a sparse file created with this command:
8928 dd bs=1 seek=2GiB if=/dev/null of=big
8932 has an apparent size of 2 GiB, yet on most modern
8933 systems, it actually uses almost no disk space.
8939 Equivalent to @code{--apparent-size --block-size=1}.
8942 @itemx --block-size=@var{size}
8944 @opindex --block-size
8946 Scale sizes by @var{size} before printing them (@pxref{Block size}).
8947 For example, @option{-BG} prints sizes in units of 1,073,741,824 bytes.
8953 @cindex grand total of disk space
8954 Print a grand total of all arguments after all arguments have
8955 been processed. This can be used to find out the total disk usage of
8956 a given set of files or directories.
8959 @itemx --dereference-args
8961 @opindex --dereference-args
8962 Dereference symbolic links that are command line arguments.
8963 Does not affect other symbolic links. This is helpful for finding
8964 out the disk usage of directories, such as @file{/usr/tmp}, which
8965 are often symbolic links.
8967 @itemx --files0-from=@var{FILE}
8968 @opindex --files0-from=@var{FILE}
8969 @cindex including files from @command{du}
8970 Rather than processing files named on the command line, process those
8971 named in file @var{FILE}; each name is terminated by a null byte.
8972 This is useful with the @option{--total} (@option{-c}) option when
8973 the list of file names is so long that it may exceed a command line
8975 In such cases, running @command{du} via @command{xargs} is undesirable
8976 because it splits the list into pieces and makes @command{du} print a
8977 total for each sublist rather than for the entire list.
8978 One way to produce a list of null-byte-terminated file names is with @sc{gnu}
8979 @command{find}, using its @option{-print0} predicate.
8980 Do not specify any @var{FILE} on the command line when using this option.
8986 Currently, @option{-H} is the same as @option{--si},
8987 except that @option{-H} evokes a warning.
8988 This option will be changed to be equivalent to
8989 @option{--dereference-args} (@option{-D}).
8993 @cindex kibibytes for file sizes
8994 Print sizes in 1024-byte blocks, overriding the default block size
8995 (@pxref{Block size}).
8996 This option is equivalent to @option{--block-size=1K}.
8999 @itemx --count-links
9001 @opindex --count-links
9002 @cindex hard links, counting in @command{du}
9003 Count the size of all files, even if they have appeared already (as a
9007 @itemx --dereference
9009 @opindex --dereference
9010 @cindex symbolic links, dereferencing in @command{du}
9011 Dereference symbolic links (show the disk space used by the file
9012 or directory that the link points to instead of the space used by
9016 @itemx --no-dereference
9018 @opindex --no-dereference
9019 @cindex symbolic links, dereferencing in @command{du}
9020 For each symbolic links encountered by @command{du},
9021 consider the disk space used by the symbolic link.
9023 @item --max-depth=@var{DEPTH}
9024 @opindex --max-depth=@var{DEPTH}
9025 @cindex limiting output of @command{du}
9026 Show the total for each directory (and file if --all) that is at
9027 most MAX_DEPTH levels down from the root of the hierarchy. The root
9028 is at level 0, so @code{du --max-depth=0} is equivalent to @code{du -s}.
9034 @cindex output null-byte-terminated lines
9035 Output a null byte at the end of each line, rather than a newline.
9036 This option enables other programs to parse the output of @command{du}
9037 even when that output would contain file names with embedded newlines.
9042 Append an SI-style abbreviation to each size, such as @samp{MB} for
9043 megabytes. Powers of 1000 are used, not 1024; @samp{MB} stands for
9044 1,000,000 bytes. Use the @option{-h} or @option{--human-readable} option if
9045 you prefer powers of 1024.
9050 @opindex --summarize
9051 Display only a total for each argument.
9054 @itemx --separate-dirs
9056 @opindex --separate-dirs
9057 Report the size of each directory separately, not including the sizes
9062 @cindex last modified dates, displaying in @command{du}
9063 Show time of the most recent modification of any file in the directory,
9064 or any of its subdirectories.
9067 @itemx --time=status
9070 @opindex ctime@r{, show the most recent}
9071 @opindex status time@r{, show the most recent}
9072 @opindex use time@r{, show the most recent}
9073 Show the most recent status change time (the @samp{ctime} in the inode) of
9074 any file in the directory, instead of the modification time.
9077 @itemx --time=access
9079 @opindex atime@r{, show the most recent}
9080 @opindex access time@r{, show the most recent}
9081 Show the most recent access time (the @samp{atime} in the inode) of
9082 any file in the directory, instead of the modification time.
9084 @item --time-style=@var{style}
9085 @opindex --time-style
9087 List timestamps in style @var{style}. This option has an effect only if
9088 the @option{--time} option is also specified. The @var{style} should
9089 be one of the following:
9094 List timestamps using @var{format}, where @var{format} is interpreted
9095 like the format argument of @command{date} (@pxref{date invocation}).
9096 For example, @option{--time-style="+%Y-%m-%d %H:%M:%S"} causes
9097 @command{du} to list timestamps like @samp{2002-03-30 23:45:56}. As
9098 with @command{date}, @var{format}'s interpretation is affected by the
9099 @env{LC_TIME} locale category.
9102 List timestamps in full using @acronym{ISO} 8601 date, time, and time zone
9103 format with nanosecond precision, e.g., @samp{2002-03-30
9104 23:45:56.477817180 -0700}. This style is equivalent to
9105 @samp{+%Y-%m-%d %H:%M:%S.%N %z}.
9108 List @acronym{ISO} 8601 date and time in minutes, e.g.,
9109 @samp{2002-03-30 23:45}. These timestamps are shorter than
9110 @samp{full-iso} timestamps, and are usually good enough for everyday
9111 work. This style is equivalent to @samp{+%Y-%m-%d %H:%M}.
9114 List @acronym{ISO} 8601 dates for timestamps, e.g., @samp{2002-03-30}.
9115 This style is equivalent to @samp{+%Y-%m-%d}.
9119 You can specify the default value of the @option{--time-style} option
9120 with the environment variable @env{TIME_STYLE}; if @env{TIME_STYLE} is not set
9121 the default style is @samp{long-iso}. For compatibility with @command{ls},
9122 if @env{TIME_STYLE} begins with @samp{+} and contains a newline,
9123 the newline and any later characters are ignored; if @env{TIME_STYLE}
9124 begins with @samp{posix-} the @samp{posix-} is ignored; and if
9125 @env{TIME_STYLE} is @samp{locale} it is ignored.
9128 @itemx --one-file-system
9130 @opindex --one-file-system
9131 @cindex one file system, restricting @command{du} to
9132 Skip directories that are on different file systems from the one that
9133 the argument being processed is on.
9135 @item --exclude=@var{PATTERN}
9136 @opindex --exclude=@var{PATTERN}
9137 @cindex excluding files from @command{du}
9138 When recursing, skip subdirectories or files matching @var{PATTERN}.
9139 For example, @code{du --exclude='*.o'} excludes files whose names
9143 @itemx --exclude-from=@var{FILE}
9144 @opindex -X @var{FILE}
9145 @opindex --exclude-from=@var{FILE}
9146 @cindex excluding files from @command{du}
9147 Like @option{--exclude}, except take the patterns to exclude from @var{FILE},
9148 one per line. If @var{FILE} is @samp{-}, take the patterns from standard
9153 @cindex NFS mounts from BSD to HP-UX
9154 On BSD systems, @command{du} reports sizes that are half the correct
9155 values for files that are NFS-mounted from HP-UX systems. On HP-UX
9156 systems, it reports sizes that are twice the correct values for
9157 files that are NFS-mounted from BSD systems. This is due to a flaw
9158 in HP-UX; it also affects the HP-UX @command{du} program.
9163 @node stat invocation
9164 @section @command{stat}: Report file or file system status
9168 @cindex file system status
9170 @command{stat} displays information about the specified file(s). Synopsis:
9173 stat [@var{option}]@dots{} [@var{file}]@dots{}
9176 With no option, @command{stat} reports all information about the given files.
9177 But it also can be used to report the information of the file systems the
9178 given files are located on. If the files are links, @command{stat} can
9179 also give information about the files the links point to.
9185 @itemx --file-system
9187 @opindex --file-system
9188 @cindex file systems
9189 Report information about the file systems where the given files are located
9190 instead of information about the files themselves.
9193 @itemx --dereference
9195 @opindex --dereference
9196 @cindex symbolic links, dereferencing in @command{stat}
9197 Change how @command{stat} treats symbolic links.
9198 With this option, @command{stat} acts on the file referenced
9199 by each symbolic link argument.
9200 Without it, @command{stat} acts on any symbolic link argument directly.
9206 @cindex terse output
9207 Print the information in terse form, suitable for parsing by other programs.
9210 @itemx --format=@var{format}
9212 @opindex --format=@var{format}
9213 @cindex output format
9214 Use @var{format} rather than the default format.
9216 The valid format sequences for files are:
9219 @item %a - Access rights in octal
9220 @item %A - Access rights in human readable form
9221 @item %b - Number of blocks allocated (see @samp{%B})
9222 @item %B - The size in bytes of each block reported by @samp{%b}
9223 @item %d - Device number in decimal
9224 @item %D - Device number in hex
9225 @item %f - Raw mode in hex
9226 @item %F - File type
9227 @item %g - Group ID of owner
9228 @item %G - Group name of owner
9229 @item %h - Number of hard links
9230 @item %i - Inode number
9231 @item %n - File name
9232 @item %N - Quoted file name with dereference if symbolic link
9233 @item %o - I/O block size
9234 @item %s - Total size, in bytes
9235 @item %t - Major device type in hex
9236 @item %T - Minor device type in hex
9237 @item %u - User ID of owner
9238 @item %U - User name of owner
9239 @item %x - Time of last access
9240 @item %X - Time of last access as seconds since Epoch
9241 @item %y - Time of last modification
9242 @item %Y - Time of last modification as seconds since Epoch
9243 @item %z - Time of last change
9244 @item %Z - Time of last change as seconds since Epoch
9247 The valid format sequences for file systems are:
9250 @item %a - Free blocks available to non-superuser
9251 @item %b - Total data blocks in file system
9252 @item %c - Total file nodes in file system
9253 @item %d - Free file nodes in file system
9254 @item %f - Free blocks in file system
9255 @item %i - File System ID in hex
9256 @item %l - Maximum length of file names
9257 @item %n - File name
9258 @item %s - Block size (for faster transfers)
9259 @item %S - Fundamental block size (for block counts)
9260 @item %t - Type in hex
9261 @item %T - Type in human readable form
9265 Time stamps are listed according to the time zone rules specified by
9266 the @env{TZ} environment variable, or by the system default rules if
9267 @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
9268 with @env{TZ}, libc, The GNU C Library}.
9274 @node sync invocation
9275 @section @command{sync}: Synchronize data on disk with memory
9278 @cindex synchronize disk and memory
9280 @cindex superblock, writing
9281 @cindex inodes, written buffered
9282 @command{sync} writes any data buffered in memory out to disk. This can
9283 include (but is not limited to) modified superblocks, modified inodes,
9284 and delayed reads and writes. This must be implemented by the kernel;
9285 The @command{sync} program does nothing but exercise the @code{sync} system
9288 @cindex crashes and corruption
9289 The kernel keeps data in memory to avoid doing (relatively slow) disk
9290 reads and writes. This improves performance, but if the computer
9291 crashes, data may be lost or the file system corrupted as a
9292 result. The @command{sync} command ensures everything in memory
9295 Any arguments are ignored, except for a lone @option{--help} or
9296 @option{--version} (@pxref{Common options}).
9302 @chapter Printing text
9304 @cindex printing text, commands for
9305 @cindex commands for printing text
9307 This section describes commands that display text strings.
9310 * echo invocation:: Print a line of text.
9311 * printf invocation:: Format and print data.
9312 * yes invocation:: Print a string until interrupted.
9316 @node echo invocation
9317 @section @command{echo}: Print a line of text
9320 @cindex displaying text
9321 @cindex printing text
9322 @cindex text, displaying
9323 @cindex arbitrary text, displaying
9325 @command{echo} writes each given @var{string} to standard output, with a
9326 space between each and a newline after the last one. Synopsis:
9329 echo [@var{option}]@dots{} [@var{string}]@dots{}
9332 The program accepts the following options. Also see @ref{Common options}.
9333 Options must precede operands, and the normally-special argument
9334 @samp{--} has no special meaning and is treated like any other
9340 Do not output the trailing newline.
9344 @cindex backslash escapes
9345 Enable interpretation of the following backslash-escaped characters in
9354 suppress trailing newline
9368 the eight-bit value that is the octal number @var{nnn}
9369 (zero to three octal digits)
9371 the eight-bit value that is the octal number @var{nnn}
9372 (one to three octal digits)
9374 the eight-bit value that is the hexadecimal number @var{hh}
9375 (one or two hexadecimal digits)
9380 @cindex backslash escapes
9381 Disable interpretation of backslash escapes in each @var{string}.
9382 This is the default. If @option{-e} and @option{-E} are both
9383 specified, the last one given takes effect.
9387 @vindex POSIXLY_CORRECT
9388 If the @env{POSIXLY_CORRECT} environment variable is set, then when
9389 @command{echo}'s first argument is not @option{-n} it outputs
9390 option-like arguments instead of treating them as options. For
9391 example, @code{echo -ne hello} outputs @samp{-ne hello} instead of
9394 @acronym{POSIX} does not require support for any options, and says
9395 that the behavior of @command{echo} is implementation-defined if any
9396 @var{string} contains a backslash or if the first argument is
9397 @option{-n}. Portable programs can use the @command{printf} command
9398 if they need to omit trailing newlines or output control characters or
9399 backslashes. @xref{printf invocation}.
9404 @node printf invocation
9405 @section @command{printf}: Format and print data
9408 @command{printf} does formatted printing of text. Synopsis:
9411 printf @var{format} [@var{argument}]@dots{}
9414 @command{printf} prints the @var{format} string, interpreting @samp{%}
9415 directives and @samp{\} escapes to format numeric and string arguments
9416 in a way that is mostly similar to the C @samp{printf} function. The
9417 differences are as follows:
9422 The @var{format} argument is reused as necessary to convert all the
9423 given @var{argument}s. For example, the command @samp{printf %s a b}
9427 Missing @var{argument}s are treated as null strings or as zeros,
9428 depending on whether the context expects a string or a number. For
9429 example, the command @samp{printf %sx%d} prints @samp{x0}.
9433 An additional escape, @samp{\c}, causes @command{printf} to produce no
9434 further output. For example, the command @samp{printf 'A%sC\cD%sF' B
9435 E} prints @samp{ABC}.
9438 The hexadecimal escape sequence @samp{\x@var{hh}} has at most two
9439 digits, as opposed to C where it can have an unlimited number of
9440 digits. For example, the command @samp{printf '\x07e'} prints two
9441 bytes, whereas the C statement @samp{printf ("\x07e")} prints just
9446 @command{printf} has an additional directive, @samp{%b}, which prints its
9447 argument string with @samp{\} escapes interpreted in the same way as in
9448 the @var{format} string, except that octal escapes are of the form
9449 @samp{\0@var{ooo}} where @var{ooo} is 0 to 3 octal digits.
9450 If a precision is also given, it limits the number of bytes printed
9451 from the converted string.
9454 Numeric arguments must be single C constants, possibly with leading
9455 @samp{+} or @samp{-}. For example, @samp{printf %.4d -3} outputs
9459 @vindex POSIXLY_CORRECT
9460 If the leading character of a numeric argument is @samp{"} or @samp{'}
9461 then its value is the numeric value of the immediately following
9462 character. Any remaining characters are silently ignored if the
9463 @env{POSIXLY_CORRECT} environment variable is set; otherwise, a
9464 warning is printed. For example, @samp{printf "%d" "'a"} outputs
9465 @samp{97} on hosts that use the @acronym{ASCII} character set, since
9466 @samp{a} has the numeric value 97 in @acronym{ASCII}.
9471 A floating-point argument must use a period before any fractional
9472 digits, but is printed according to the @env{LC_NUMERIC} category of the
9473 current locale. For example, in a locale whose radix character is a
9474 comma, the command @samp{printf %g 3.14} outputs @samp{3,14} whereas
9475 the command @samp{printf %g 3,14} is an error.
9479 @command{printf} interprets @samp{\@var{ooo}} in @var{format} as an octal number
9480 (if @var{ooo} is 1 to 3 octal digits) specifying a character to print,
9481 and @samp{\x@var{hh}} as a hexadecimal number (if @var{hh} is 1 to 2 hex
9482 digits) specifying a character to print.
9487 @cindex ISO/IEC 10646
9489 @command{printf} interprets two character syntaxes introduced in ISO C 99:
9490 @samp{\u} for 16-bit Unicode (ISO/IEC 10646) characters, specified as
9491 four hexadecimal digits @var{hhhh}, and @samp{\U} for 32-bit Unicode
9492 characters, specified as eight hexadecimal digits @var{hhhhhhhh}.
9493 @command{printf} outputs the Unicode characters
9494 according to the @env{LC_CTYPE} locale.
9496 The processing of @samp{\u} and @samp{\U} requires a full-featured
9497 @code{iconv} facility. It is activated on systems with glibc 2.2 (or newer),
9498 or when @code{libiconv} is installed prior to this package. Otherwise
9499 @samp{\u} and @samp{\U} will print as-is.
9501 The only options are a lone @option{--help} or
9502 @option{--version}. @xref{Common options}.
9503 Options must precede operands.
9505 The Unicode character syntaxes are useful for writing strings in a locale
9506 independent way. For example, a string containing the Euro currency symbol
9509 $ /usr/local/bin/printf '\u20AC 14.95'
9513 will be output correctly in all locales supporting the Euro symbol
9514 (ISO-8859-15, UTF-8, and others). Similarly, a Chinese string
9517 $ /usr/local/bin/printf '\u4e2d\u6587'
9521 will be output correctly in all Chinese locales (GB2312, BIG5, UTF-8, etc).
9523 Note that in these examples, the full name of @command{printf} has been
9524 given, to distinguish it from the GNU @code{bash} built-in function
9527 For larger strings, you don't need to look up the hexadecimal code
9528 values of each character one by one. @acronym{ASCII} characters mixed with \u
9529 escape sequences is also known as the JAVA source file encoding. You can
9530 use GNU recode 3.5c (or newer) to convert strings to this encoding. Here
9531 is how to convert a piece of text into a shell script which will output
9532 this text in a locale-independent way:
9535 $ LC_CTYPE=zh_CN.big5 /usr/local/bin/printf \
9536 '\u4e2d\u6587\n' > sample.txt
9537 $ recode BIG5..JAVA < sample.txt \
9538 | sed -e "s|^|/usr/local/bin/printf '|" -e "s|$|\\\\n'|" \
9545 @node yes invocation
9546 @section @command{yes}: Print a string until interrupted
9549 @cindex repeated output of a string
9551 @command{yes} prints the command line arguments, separated by spaces and
9552 followed by a newline, forever until it is killed. If no arguments are
9553 given, it prints @samp{y} followed by a newline forever until killed.
9555 Upon a write error, @command{yes} exits with status @samp{1}.
9557 The only options are a lone @option{--help} or @option{--version}.
9558 To output an argument that begins with
9559 @samp{-}, precede it with @option{--}, e.g., @samp{yes -- --help}.
9560 @xref{Common options}.
9567 @cindex commands for exit status
9568 @cindex exit status commands
9570 This section describes commands that are primarily useful for their exit
9571 status, rather than their output. Thus, they are often used as the
9572 condition of shell @code{if} statements, or as the last command in a
9576 * false invocation:: Do nothing, unsuccessfully.
9577 * true invocation:: Do nothing, successfully.
9578 * test invocation:: Check file types and compare values.
9579 * expr invocation:: Evaluate expressions.
9583 @node false invocation
9584 @section @command{false}: Do nothing, unsuccessfully
9587 @cindex do nothing, unsuccessfully
9588 @cindex failure exit status
9589 @cindex exit status of @command{false}
9591 @command{false} does nothing except return an exit status of 1, meaning
9592 @dfn{failure}. It can be used as a place holder in shell scripts
9593 where an unsuccessful command is needed.
9595 @command{false} honors the @option{--help} and @option{--version} options.
9597 This version of @command{false} is implemented as a C program, and is thus
9598 more secure and faster than a shell script implementation, and may safely
9599 be used as a dummy shell for the purpose of disabling accounts.
9601 Note that @command{false} (unlike all other programs documented herein)
9602 exits unsuccessfully, even when invoked with
9603 @option{--help} or @option{--version}.
9606 @node true invocation
9607 @section @command{true}: Do nothing, successfully
9610 @cindex do nothing, successfully
9612 @cindex successful exit
9613 @cindex exit status of @command{true}
9615 @command{true} does nothing except return an exit status of 0, meaning
9616 @dfn{success}. It can be used as a place holder in shell scripts
9617 where a successful command is needed, although the shell built-in
9618 command @code{:} (colon) may do the same thing faster.
9619 In most modern shells, @command{true} is a built-in command, so when
9620 you use @samp{true} in a script, you're probably using the built-in
9621 command, not the one documented here.
9623 @command{true} honors the @option{--help} and @option{--version} options.
9625 Note, however, that it is possible to cause @command{true}
9626 to exit with nonzero status: when invoked in non-@acronym{POSIX} mode,
9627 with the @option{--help} or @option{--version} option, and with standard
9628 output already closed or redirected to a file that evokes an I/O error.
9629 For example, using a Bourne-compatible shell:
9632 $ ./true --version >&-
9633 ./true: write error: Bad file number
9634 $ ./true --version > /dev/full
9635 ./true: write error: No space left on device
9638 This version of @command{true} is implemented as a C program, and is thus
9639 more secure and faster than a shell script implementation, and may safely
9640 be used as a dummy shell for the purpose of disabling accounts.
9642 @node test invocation
9643 @section @command{test}: Check file types and compare values
9646 @cindex check file types
9647 @cindex compare values
9648 @cindex expression evaluation
9650 @command{test} returns a status of 0 (true) or 1 (false) depending on the
9651 evaluation of the conditional expression @var{expr}. Each part of the
9652 expression must be a separate argument.
9654 @command{test} has file status checks, string operators, and numeric
9655 comparison operators.
9657 @command{test} has an alternate form that uses opening and closing
9658 square brackets instead a leading @samp{test}. For example, instead
9659 of @samp{test -d /}, you can write @samp{[ -d / ]}. The square
9660 brackets must be separate arguments; for example, @samp{[-d /]} does
9661 not have the desired effect. Since @samp{test @var{expr}} and @samp{[
9662 @var{expr} ]} have the same meaning, only the former form is discussed
9668 test @var{expression}
9670 [ @var{expression} ]
9675 @cindex conflicts with shell built-ins
9676 @cindex built-in shell commands, conflicts with
9677 Because most shells have a built-in @command{test} command, using an
9678 unadorned @command{test} in a script or interactively may get you
9679 different functionality than that described here.
9681 If @var{expression} is omitted, @command{test} returns false.
9682 If @var{expression} is a single argument,
9683 @command{test} returns false if the argument is null and true otherwise. The argument
9684 can be any string, including strings like @samp{-d}, @samp{-1},
9685 @samp{--}, @samp{--help}, and @samp{--version} that most other
9686 programs would treat as options. To get help and version information,
9687 invoke the commands @samp{[ --help} and @samp{[ --version}, without
9688 the usual closing brackets. @xref{Common options}.
9690 @cindex exit status of @command{test}
9694 0 if the expression is true,
9695 1 if the expression is false,
9696 2 if an error occurred.
9700 * File type tests:: -[bcdfhLpSt]
9701 * Access permission tests:: -[gkruwxOG]
9702 * File characteristic tests:: -e -s -nt -ot -ef
9703 * String tests:: -z -n = !=
9704 * Numeric tests:: -eq -ne -lt -le -gt -ge
9705 * Connectives for test:: ! -a -o
9709 @node File type tests
9710 @subsection File type tests
9712 @cindex file type tests
9714 These options test for particular types of files. (Everything's a file,
9715 but not all files are the same!)
9721 @cindex block special check
9722 True if @var{file} exists and is a block special device.
9726 @cindex character special check
9727 True if @var{file} exists and is a character special device.
9731 @cindex directory check
9732 True if @var{file} exists and is a directory.
9736 @cindex regular file check
9737 True if @var{file} exists and is a regular file.
9740 @itemx -L @var{file}
9743 @cindex symbolic link check
9744 True if @var{file} exists and is a symbolic link.
9745 Unlike all other file-related tests, this test does not dereference
9746 @var{file} if it is a symbolic link.
9750 @cindex named pipe check
9751 True if @var{file} exists and is a named pipe.
9755 @cindex socket check
9756 True if @var{file} exists and is a socket.
9760 @cindex terminal check
9761 True if @var{fd} is a file descriptor that is associated with a
9767 @node Access permission tests
9768 @subsection Access permission tests
9770 @cindex access permission tests
9771 @cindex permission tests
9773 These options test for particular access permissions.
9779 @cindex set-group-ID check
9780 True if @var{file} exists and has its set-group-ID bit set.
9784 @cindex sticky bit check
9785 True if @var{file} exists and has its @dfn{sticky} bit set.
9789 @cindex readable file check
9790 True if @var{file} exists and read permission is granted.
9794 @cindex set-user-ID check
9795 True if @var{file} exists and has its set-user-ID bit set.
9799 @cindex writable file check
9800 True if @var{file} exists and write permission is granted.
9804 @cindex executable file check
9805 True if @var{file} exists and execute permission is granted
9806 (or search permission, if it is a directory).
9810 @cindex owned by effective user ID check
9811 True if @var{file} exists and is owned by the current effective user ID.
9815 @cindex owned by effective group ID check
9816 True if @var{file} exists and is owned by the current effective group ID.
9820 @node File characteristic tests
9821 @subsection File characteristic tests
9823 @cindex file characteristic tests
9825 These options test other file characteristics.
9831 @cindex existence-of-file check
9832 True if @var{file} exists.
9836 @cindex nonempty file check
9837 True if @var{file} exists and has a size greater than zero.
9839 @item @var{file1} -nt @var{file2}
9841 @cindex newer-than file check
9842 True if @var{file1} is newer (according to modification date) than
9843 @var{file2}, or if @var{file1} exists and @var{file2} does not.
9845 @item @var{file1} -ot @var{file2}
9847 @cindex older-than file check
9848 True if @var{file1} is older (according to modification date) than
9849 @var{file2}, or if @var{file2} exists and @var{file1} does not.
9851 @item @var{file1} -ef @var{file2}
9853 @cindex same file check
9854 @cindex hard link check
9855 True if @var{file1} and @var{file2} have the same device and inode
9856 numbers, i.e., if they are hard links to each other.
9862 @subsection String tests
9864 @cindex string tests
9866 These options test string characteristics. You may need to quote
9867 @var{string} arguments for the shell. For example:
9873 The quotes here prevent the wrong arguments from being passed to
9874 @command{test} if @samp{$V} is empty or contains special characters.
9878 @item -z @var{string}
9880 @cindex zero-length string check
9881 True if the length of @var{string} is zero.
9883 @item -n @var{string}
9886 @cindex nonzero-length string check
9887 True if the length of @var{string} is nonzero.
9889 @item @var{string1} = @var{string2}
9891 @cindex equal string check
9892 True if the strings are equal.
9894 @item @var{string1} != @var{string2}
9896 @cindex not-equal string check
9897 True if the strings are not equal.
9903 @subsection Numeric tests
9905 @cindex numeric tests
9906 @cindex arithmetic tests
9908 Numeric relationals. The arguments must be entirely numeric (possibly
9909 negative), or the special expression @w{@code{-l @var{string}}}, which
9910 evaluates to the length of @var{string}.
9914 @item @var{arg1} -eq @var{arg2}
9915 @itemx @var{arg1} -ne @var{arg2}
9916 @itemx @var{arg1} -lt @var{arg2}
9917 @itemx @var{arg1} -le @var{arg2}
9918 @itemx @var{arg1} -gt @var{arg2}
9919 @itemx @var{arg1} -ge @var{arg2}
9926 These arithmetic binary operators return true if @var{arg1} is equal,
9927 not-equal, less-than, less-than-or-equal, greater-than, or
9928 greater-than-or-equal than @var{arg2}, respectively.
9935 test -1 -gt -2 && echo yes
9937 test -l abc -gt 1 && echo yes
9940 @error{} test: integer expression expected before -eq
9944 @node Connectives for test
9945 @subsection Connectives for @command{test}
9947 @cindex logical connectives
9948 @cindex connectives, logical
9950 The usual logical connectives.
9956 True if @var{expr} is false.
9958 @item @var{expr1} -a @var{expr2}
9960 @cindex logical and operator
9961 @cindex and operator
9962 True if both @var{expr1} and @var{expr2} are true.
9964 @item @var{expr1} -o @var{expr2}
9966 @cindex logical or operator
9968 True if either @var{expr1} or @var{expr2} is true.
9973 @node expr invocation
9974 @section @command{expr}: Evaluate expressions
9977 @cindex expression evaluation
9978 @cindex evaluation of expressions
9980 @command{expr} evaluates an expression and writes the result on standard
9981 output. Each token of the expression must be a separate argument.
9983 Operands are either integers or strings. Integers consist of one or
9984 more decimal digits, with an optional leading @samp{-}.
9985 @command{expr} converts
9986 anything appearing in an operand position to an integer or a string
9987 depending on the operation being applied to it.
9989 Strings are not quoted for @command{expr} itself, though you may need to
9990 quote them to protect characters with special meaning to the shell,
9991 e.g., spaces. However, regardless of whether it is quoted, a string
9992 operand should not be a parenthesis or any of @command{expr}'s
9993 operators like @code{+}, so you cannot safely pass an arbitrary string
9994 @code{$str} to expr merely by quoting it to the shell. One way to
9995 work around this is to use the @sc{gnu} extension @code{+},
9996 (e.g., @code{+ "$str" = foo}); a more portable way is to use
9997 @code{@w{" $str"}} and to adjust the rest of the expression to take
9998 the leading space into account (e.g., @code{@w{" $str" = " foo"}}).
10000 You should not pass a negative integer or a string with leading
10001 @samp{-} as @command{expr}'s first argument, as it might be
10002 misinterpreted as an option; this can be avoided by parenthesization.
10003 Also, portable scripts should not use a string operand that happens to
10004 take the form of an integer; this can be worked around by inserting
10005 leading spaces as mentioned above.
10007 @cindex parentheses for grouping
10008 Operators may be given as infix symbols or prefix keywords. Parentheses
10009 may be used for grouping in the usual manner. You must quote
10010 parentheses and many operators to avoid the shell evaluating them,
10013 The only options are @option{--help} and @option{--version}. @xref{Common
10014 options}. Options must precede operands.
10016 @cindex exit status of @command{expr}
10020 0 if the expression is neither null nor 0,
10021 1 if the expression is null or 0,
10022 2 if the expression is syntactically invalid,
10023 3 if an error occurred.
10027 * String expressions:: + : match substr index length
10028 * Numeric expressions:: + - * / %
10029 * Relations for expr:: | & < <= = == != >= >
10030 * Examples of expr:: Examples.
10034 @node String expressions
10035 @subsection String expressions
10037 @cindex string expressions
10038 @cindex expressions, string
10040 @command{expr} supports pattern matching and other string operators. These
10041 have lower precedence than both the numeric and relational operators (in
10042 the next sections).
10046 @item @var{string} : @var{regex}
10047 @cindex pattern matching
10048 @cindex regular expression matching
10049 @cindex matching patterns
10050 Perform pattern matching. The arguments are converted to strings and the
10051 second is considered to be a (basic, a la GNU @code{grep}) regular
10052 expression, with a @code{^} implicitly prepended. The first argument is
10053 then matched against this regular expression.
10055 If the match succeeds and @var{regex} uses @samp{\(} and @samp{\)}, the
10056 @code{:} expression returns the part of @var{string} that matched the
10057 subexpression; otherwise, it returns the number of characters matched.
10059 If the match fails, the @code{:} operator returns the null string if
10060 @samp{\(} and @samp{\)} are used in @var{regex}, otherwise 0.
10062 @kindex \( @r{regexp operator}
10063 Only the first @samp{\( @dots{} \)} pair is relevant to the return
10064 value; additional pairs are meaningful only for grouping the regular
10065 expression operators.
10067 @kindex \+ @r{regexp operator}
10068 @kindex \? @r{regexp operator}
10069 @kindex \| @r{regexp operator}
10070 In the regular expression, @code{\+}, @code{\?}, and @code{\|} are
10071 operators which respectively match one or more, zero or one, or separate
10072 alternatives. SunOS and other @command{expr}'s treat these as regular
10073 characters. (@acronym{POSIX} allows either behavior.)
10074 @xref{Top, , Regular Expression Library, regex, Regex}, for details of
10075 regular expression syntax. Some examples are in @ref{Examples of expr}.
10077 @item match @var{string} @var{regex}
10079 An alternative way to do pattern matching. This is the same as
10080 @w{@samp{@var{string} : @var{regex}}}.
10082 @item substr @var{string} @var{position} @var{length}
10084 Returns the substring of @var{string} beginning at @var{position}
10085 with length at most @var{length}. If either @var{position} or
10086 @var{length} is negative, zero, or non-numeric, returns the null string.
10088 @item index @var{string} @var{charset}
10090 Returns the first position in @var{string} where the first character in
10091 @var{charset} was found. If no character in @var{charset} is found in
10092 @var{string}, return 0.
10094 @item length @var{string}
10096 Returns the length of @var{string}.
10098 @item + @var{token}
10100 Interpret @var{token} as a string, even if it is a keyword like @var{match}
10101 or an operator like @code{/}.
10102 This makes it possible to test @code{expr length + "$x"} or
10103 @code{expr + "$x" : '.*/\(.\)'} and have it do the right thing even if
10104 the value of @var{$x} happens to be (for example) @code{/} or @code{index}.
10105 This operator is a GNU extension. Portable shell scripts should use
10106 @code{@w{" $token"} : @w{' \(.*\)'}} instead of @code{+ "$token"}.
10110 To make @command{expr} interpret keywords as strings, you must use the
10111 @code{quote} operator.
10114 @node Numeric expressions
10115 @subsection Numeric expressions
10117 @cindex numeric expressions
10118 @cindex expressions, numeric
10120 @command{expr} supports the usual numeric operators, in order of increasing
10121 precedence. The string operators (previous section) have lower precedence,
10122 the connectives (next section) have higher.
10130 @cindex subtraction
10131 Addition and subtraction. Both arguments are converted to integers;
10132 an error occurs if this cannot be done.
10138 @cindex multiplication
10141 Multiplication, division, remainder. Both arguments are converted to
10142 integers; an error occurs if this cannot be done.
10147 @node Relations for expr
10148 @subsection Relations for @command{expr}
10150 @cindex connectives, logical
10151 @cindex logical connectives
10152 @cindex relations, numeric or string
10154 @command{expr} supports the usual logical connectives and relations. These
10155 are higher precedence than either the string or numeric operators
10156 (previous sections). Here is the list, lowest-precedence operator first.
10162 @cindex logical or operator
10163 @cindex or operator
10164 Returns its first argument if that is neither null nor zero, otherwise
10165 its second argument if it is neither null nor zero, otherwise 0. It
10166 does not evaluate its second argument if its first argument is neither
10171 @cindex logical and operator
10172 @cindex and operator
10173 Return its first argument if neither argument is null or zero, otherwise
10174 0. It does not evaluate its second argument if its first argument is
10177 @item < <= = == != >= >
10184 @cindex comparison operators
10186 Compare the arguments and return 1 if the relation is true, 0 otherwise.
10187 @code{==} is a synonym for @code{=}. @command{expr} first tries to convert
10188 both arguments to integers and do a numeric comparison; if either
10189 conversion fails, it does a lexicographic comparison using the character
10190 collating sequence specified by the @env{LC_COLLATE} locale.
10195 @node Examples of expr
10196 @subsection Examples of using @command{expr}
10198 @cindex examples of @command{expr}
10199 Here are a few examples, including quoting for shell metacharacters.
10201 To add 1 to the shell variable @code{foo}, in Bourne-compatible shells:
10204 foo=`expr $foo + 1`
10207 To print the non-directory part of the file name stored in
10208 @code{$fname}, which need not contain a @code{/}:
10211 expr $fname : '.*/\(.*\)' '|' $fname
10214 An example showing that @code{\+} is an operator:
10222 expr abc : 'a\(.\)c'
10224 expr index abcdef cz
10227 @error{} expr: syntax error
10228 expr index quote index a
10234 @chapter Redirection
10236 @cindex redirection
10237 @cindex commands for redirection
10239 Unix shells commonly provide several forms of @dfn{redirection}---ways
10240 to change the input source or output destination of a command. But one
10241 useful redirection is performed by a separate command, not by the shell;
10242 it's described here.
10245 * tee invocation:: Redirect output to multiple files.
10249 @node tee invocation
10250 @section @command{tee}: Redirect output to multiple files
10253 @cindex pipe fitting
10254 @cindex destinations, multiple output
10255 @cindex read from stdin and write to stdout and files
10257 The @command{tee} command copies standard input to standard output and also
10258 to any files given as arguments. This is useful when you want not only
10259 to send some data down a pipe, but also to save a copy. Synopsis:
10262 tee [@var{option}]@dots{} [@var{file}]@dots{}
10265 If a file being written to does not already exist, it is created. If a
10266 file being written to already exists, the data it previously contained
10267 is overwritten unless the @option{-a} option is used.
10269 A @var{file} of @samp{-} causes @command{tee} to send another copy of
10270 input to standard output, but this is typically not that useful as the
10271 copies are interleaved.
10273 The program accepts the following options. Also see @ref{Common options}.
10280 Append standard input to the given files rather than overwriting
10284 @itemx --ignore-interrupts
10286 @opindex --ignore-interrupts
10287 Ignore interrupt signals.
10294 @node File name manipulation
10295 @chapter File name manipulation
10297 @cindex file name manipulation
10298 @cindex manipulation of file names
10299 @cindex commands for file name manipulation
10301 This section describes commands that manipulate file names.
10304 * basename invocation:: Strip directory and suffix from a file name.
10305 * dirname invocation:: Strip non-directory suffix from a file name.
10306 * pathchk invocation:: Check file name portability.
10310 @node basename invocation
10311 @section @command{basename}: Strip directory and suffix from a file name
10314 @cindex strip directory and suffix from file names
10315 @cindex directory, stripping from file names
10316 @cindex suffix, stripping from file names
10317 @cindex file names, stripping directory and suffix
10318 @cindex leading directory components, stripping
10320 @command{basename} removes any leading directory components from
10321 @var{name}. Synopsis:
10324 basename @var{name} [@var{suffix}]
10327 If @var{suffix} is specified and is identical to the end of @var{name},
10328 it is removed from @var{name} as well. @command{basename} prints the
10329 result on standard output.
10331 The only options are @option{--help} and @option{--version}. @xref{Common
10332 options}. Options must precede operands.
10340 basename /usr/bin/sort
10343 basename include/stdio.h .h
10347 @node dirname invocation
10348 @section @command{dirname}: Strip non-directory suffix from a file name
10351 @cindex directory components, printing
10352 @cindex stripping non-directory suffix
10353 @cindex non-directory suffix, stripping
10355 @command{dirname} prints all but the final slash-delimited component of
10356 a string (presumably a file name). Synopsis:
10362 If @var{name} is a single component, @command{dirname} prints @samp{.}
10363 (meaning the current directory).
10365 The only options are @option{--help} and @option{--version}. @xref{Common
10373 # Output "/usr/bin".
10374 dirname /usr/bin/sort
10381 @node pathchk invocation
10382 @section @command{pathchk}: Check file name portability
10385 @cindex file names, checking validity and portability
10386 @cindex valid file names, checking for
10387 @cindex portable file names, checking for
10389 @command{pathchk} checks portability of file names. Synopsis:
10392 pathchk [@var{option}]@dots{} @var{name}@dots{}
10395 For each @var{name}, @command{pathchk} prints a message if any of
10396 these conditions is true:
10400 One of the existing directories in @var{name} does not have search
10401 (execute) permission,
10403 The length of @var{name} is larger than the maximum supported by the
10406 The length of one component of @var{name} is longer than
10407 its file system's maximum.
10410 A nonexistent @var{name} is not an error, so long a file with that
10411 name could be created under the above conditions.
10413 The program accepts the following options. Also see @ref{Common options}.
10414 Options must precede operands.
10420 Instead of performing checks based on the underlying file system,
10421 print a message if any of these conditions is true:
10425 A file name is empty.
10428 The length of a file name or one of its components exceeds the
10429 @acronym{POSIX} minimum limits for portability.
10432 A file name contains a character outside the portable file name
10433 character set, namely, the ASCII letters and digits, @samp{-},
10434 @samp{.}, @samp{/}, and @samp{_}.
10439 Print a message if a file name is empty, or if it contains a component
10440 that begins with @samp{-}.
10442 @item --portability
10443 @opindex --portability
10444 Print a message if a file name is not portable to all @acronym{POSIX}
10445 hosts. This option is equivalent to @samp{-p -P}.
10449 @cindex exit status of @command{pathchk}
10453 0 if all specified file names passed all checks,
10458 @node Working context
10459 @chapter Working context
10461 @cindex working context
10462 @cindex commands for printing the working context
10464 This section describes commands that display or alter the context in
10465 which you are working: the current directory, the terminal settings, and
10466 so forth. See also the user-related commands in the next section.
10469 * pwd invocation:: Print working directory.
10470 * stty invocation:: Print or change terminal characteristics.
10471 * printenv invocation:: Print environment variables.
10472 * tty invocation:: Print file name of terminal on standard input.
10476 @node pwd invocation
10477 @section @command{pwd}: Print working directory
10480 @cindex print name of current directory
10481 @cindex current working directory, printing
10482 @cindex working directory, printing
10484 @cindex symbolic links and @command{pwd}
10485 @command{pwd} prints the fully resolved name of the current directory.
10486 That is, all components of the printed name will be actual directory
10487 names---none will be symbolic links.
10489 @cindex conflicts with shell built-ins
10490 @cindex built-in shell commands, conflicts with
10491 Because most shells have a built-in @command{pwd} command, using an
10492 unadorned @command{pwd} in a script or interactively may get you
10493 different functionality than that described here.
10495 The only options are a lone @option{--help} or
10496 @option{--version}. @xref{Common options}.
10501 @node stty invocation
10502 @section @command{stty}: Print or change terminal characteristics
10505 @cindex change or print terminal settings
10506 @cindex terminal settings
10507 @cindex line settings of terminal
10509 @command{stty} prints or changes terminal characteristics, such as baud rate.
10513 stty [@var{option}] [@var{setting}]@dots{}
10514 stty [@var{option}]
10517 If given no line settings, @command{stty} prints the baud rate, line
10518 discipline number (on systems that support it), and line settings
10519 that have been changed from the values set by @samp{stty sane}.
10520 By default, mode reading and setting are performed on the tty line
10521 connected to standard input, although this can be modified by the
10522 @option{--file} option.
10524 @command{stty} accepts many non-option arguments that change aspects of
10525 the terminal line operation, as described below.
10527 The program accepts the following options. Also see @ref{Common options}.
10534 Print all current settings in human-readable form. This option may not
10535 be used in combination with any line settings.
10537 @item -F @var{device}
10538 @itemx --file=@var{device}
10541 Set the line opened by the file name specified in @var{device} instead of
10542 the tty line connected to standard input. This option is necessary
10543 because opening a @acronym{POSIX} tty requires use of the @code{O_NONDELAY} flag to
10544 prevent a @acronym{POSIX} tty from blocking until the carrier detect line is high if
10545 the @code{clocal} flag is not set. Hence, it is not always possible
10546 to allow the shell to open the device in the traditional manner.
10552 @cindex machine-readable @command{stty} output
10553 Print all current settings in a form that can be used as an argument to
10554 another @command{stty} command to restore the current settings. This option
10555 may not be used in combination with any line settings.
10559 Many settings can be turned off by preceding them with a @samp{-}.
10560 Such arguments are marked below with ``May be negated'' in their
10561 description. The descriptions themselves refer to the positive
10562 case, that is, when @emph{not} negated (unless stated otherwise,
10565 Some settings are not available on all @acronym{POSIX} systems, since they use
10566 extensions. Such arguments are marked below with ``Non-@acronym{POSIX}'' in their
10567 description. On non-@acronym{POSIX} systems, those or other settings also may not
10568 be available, but it's not feasible to document all the variations: just
10574 * Control:: Control settings
10575 * Input:: Input settings
10576 * Output:: Output settings
10577 * Local:: Local settings
10578 * Combination:: Combination settings
10579 * Characters:: Special characters
10580 * Special:: Special settings
10585 @subsection Control settings
10587 @cindex control settings
10593 @cindex two-way parity
10594 Generate parity bit in output and expect parity bit in input.
10600 @cindex even parity
10601 Set odd parity (even if negated). May be negated.
10608 @cindex character size
10609 @cindex eight-bit characters
10610 Set character size to 5, 6, 7, or 8 bits.
10615 Send a hangup signal when the last process closes the tty. May be
10621 Use two stop bits per character (one if negated). May be negated.
10625 Allow input to be received. May be negated.
10629 @cindex modem control
10630 Disable modem control signals. May be negated.
10634 @cindex hardware flow control
10635 @cindex flow control, hardware
10636 @cindex RTS/CTS flow control
10637 Enable RTS/CTS flow control. Non-@acronym{POSIX}. May be negated.
10642 @subsection Input settings
10644 @cindex input settings
10649 @cindex breaks, ignoring
10650 Ignore break characters. May be negated.
10654 @cindex breaks, cause interrupts
10655 Make breaks cause an interrupt signal. May be negated.
10659 @cindex parity, ignoring
10660 Ignore characters with parity errors. May be negated.
10664 @cindex parity errors, marking
10665 Mark parity errors (with a 255-0-character sequence). May be negated.
10669 Enable input parity checking. May be negated.
10673 @cindex eight-bit input
10674 Clear high (8th) bit of input characters. May be negated.
10678 @cindex newline, translating to return
10679 Translate newline to carriage return. May be negated.
10683 @cindex return, ignoring
10684 Ignore carriage return. May be negated.
10688 @cindex return, translating to newline
10689 Translate carriage return to newline. May be negated.
10693 @cindex input encoding, UTF-8
10694 Assume input characters are UTF-8 encoded. May be negated.
10698 @kindex C-s/C-q flow control
10699 @cindex XON/XOFF flow control
10700 Enable XON/XOFF flow control (that is, @kbd{CTRL-S}/@kbd{CTRL-Q}). May
10707 @cindex software flow control
10708 @cindex flow control, software
10709 Enable sending of @code{stop} character when the system input buffer
10710 is almost full, and @code{start} character when it becomes almost
10711 empty again. May be negated.
10715 @cindex uppercase, translating to lowercase
10716 Translate uppercase characters to lowercase. Non-@acronym{POSIX}. May be
10721 Allow any character to restart output (only the start character
10722 if negated). Non-@acronym{POSIX}. May be negated.
10726 @cindex beeping at input buffer full
10727 Enable beeping and not flushing input buffer if a character arrives
10728 when the input buffer is full. Non-@acronym{POSIX}. May be negated.
10733 @subsection Output settings
10735 @cindex output settings
10736 These arguments specify output-related operations.
10741 Postprocess output. May be negated.
10745 @cindex lowercase, translating to output
10746 Translate lowercase characters to uppercase. Non-@acronym{POSIX}. May be
10751 @cindex return, translating to newline
10752 Translate carriage return to newline. Non-@acronym{POSIX}. May be negated.
10756 @cindex newline, translating to crlf
10757 Translate newline to carriage return-newline. Non-@acronym{POSIX}. May be
10762 Do not print carriage returns in the first column. Non-@acronym{POSIX}.
10767 Newline performs a carriage return. Non-@acronym{POSIX}. May be negated.
10771 @cindex pad instead of timing for delaying
10772 Use fill (padding) characters instead of timing for delays. Non-@acronym{POSIX}.
10777 @cindex pad character
10778 Use delete characters for fill instead of null characters. Non-@acronym{POSIX}.
10784 Newline delay style. Non-@acronym{POSIX}.
10791 Carriage return delay style. Non-@acronym{POSIX}.
10797 @opindex tab@var{n}
10798 Horizontal tab delay style. Non-@acronym{POSIX}.
10803 Backspace delay style. Non-@acronym{POSIX}.
10808 Vertical tab delay style. Non-@acronym{POSIX}.
10813 Form feed delay style. Non-@acronym{POSIX}.
10818 @subsection Local settings
10820 @cindex local settings
10825 Enable @code{interrupt}, @code{quit}, and @code{suspend} special
10826 characters. May be negated.
10830 Enable @code{erase}, @code{kill}, @code{werase}, and @code{rprnt}
10831 special characters. May be negated.
10835 Enable non-@acronym{POSIX} special characters. May be negated.
10839 Echo input characters. May be negated.
10845 Echo @code{erase} characters as backspace-space-backspace. May be
10850 @cindex newline echoing after @code{kill}
10851 Echo a newline after a @code{kill} character. May be negated.
10855 @cindex newline, echoing
10856 Echo newline even if not echoing other characters. May be negated.
10860 @cindex flushing, disabling
10861 Disable flushing after @code{interrupt} and @code{quit} special
10862 characters. May be negated.
10866 @cindex case translation
10867 Enable input and output of uppercase characters by preceding their
10868 lowercase equivalents with @samp{\}, when @code{icanon} is set.
10869 Non-@acronym{POSIX}. May be negated.
10873 @cindex background jobs, stopping at terminal write
10874 Stop background jobs that try to write to the terminal. Non-@acronym{POSIX}.
10881 Echo erased characters backward, between @samp{\} and @samp{/}.
10882 Non-@acronym{POSIX}. May be negated.
10888 @cindex control characters, using @samp{^@var{c}}
10889 @cindex hat notation for control characters
10890 Echo control characters in hat notation (@samp{^@var{c}}) instead
10891 of literally. Non-@acronym{POSIX}. May be negated.
10897 Echo the @code{kill} special character by erasing each character on
10898 the line as indicated by the @code{echoprt} and @code{echoe} settings,
10899 instead of by the @code{echoctl} and @code{echok} settings. Non-@acronym{POSIX}.
10905 @subsection Combination settings
10907 @cindex combination settings
10908 Combination settings:
10915 Same as @code{parenb -parodd cs7}. May be negated. If negated, same
10916 as @code{-parenb cs8}.
10920 Same as @code{parenb parodd cs7}. May be negated. If negated, same
10921 as @code{-parenb cs8}.
10925 Same as @code{-icrnl -onlcr}. May be negated. If negated, same as
10926 @code{icrnl -inlcr -igncr onlcr -ocrnl -onlret}.
10930 Reset the @code{erase} and @code{kill} special characters to their default
10937 @c This is too long to write inline.
10939 cread -ignbrk brkint -inlcr -igncr icrnl -ixoff
10940 -iuclc -ixany imaxbel opost -olcuc -ocrnl onlcr
10941 -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0
10942 ff0 isig icanon iexten echo echoe echok -echonl
10943 -noflsh -xcase -tostop -echoprt echoctl echoke
10947 and also sets all special characters to their default values.
10951 Same as @code{brkint ignpar istrip icrnl ixon opost isig icanon}, plus
10952 sets the @code{eof} and @code{eol} characters to their default values
10953 if they are the same as the @code{min} and @code{time} characters.
10954 May be negated. If negated, same as @code{raw}.
10961 -ignbrk -brkint -ignpar -parmrk -inpck -istrip
10962 -inlcr -igncr -icrnl -ixon -ixoff -iuclc -ixany
10963 -imaxbel -opost -isig -icanon -xcase min 1 time 0
10967 May be negated. If negated, same as @code{cooked}.
10971 Same as @option{-icanon}. May be negated. If negated, same as
10976 @cindex eight-bit characters
10977 Same as @code{-parenb -istrip cs8}. May be negated. If negated,
10978 same as @code{parenb istrip cs7}.
10982 Same as @option{-parenb -istrip -opost cs8}. May be negated.
10983 If negated, same as @code{parenb istrip opost cs7}.
10987 Same as @option{-ixany}. Non-@acronym{POSIX}. May be negated.
10991 Same as @code{tab0}. Non-@acronym{POSIX}. May be negated. If negated, same
10998 Same as @code{xcase iuclc olcuc}. Non-@acronym{POSIX}. May be negated.
11002 Same as @code{echoe echoctl echoke}.
11006 Same as @code{echoe echoctl echoke -ixany intr ^C erase ^? kill C-u}.
11011 @subsection Special characters
11013 @cindex special characters
11014 @cindex characters, special
11016 The special characters' default values vary from system to system.
11017 They are set with the syntax @samp{name value}, where the names are
11018 listed below and the value can be given either literally, in hat
11019 notation (@samp{^@var{c}}), or as an integer which may start with
11020 @samp{0x} to indicate hexadecimal, @samp{0} to indicate octal, or
11021 any other digit to indicate decimal.
11023 @cindex disabling special characters
11024 @kindex u@r{, and disabling special characters}
11025 For GNU stty, giving a value of @code{^-} or @code{undef} disables that
11026 special character. (This is incompatible with Ultrix @command{stty},
11027 which uses a value of @samp{u} to disable a special character. GNU
11028 @command{stty} treats a value @samp{u} like any other, namely to set that
11029 special character to @key{U}.)
11035 Send an interrupt signal.
11039 Send a quit signal.
11043 Erase the last character typed.
11047 Erase the current line.
11051 Send an end of file (terminate the input).
11059 Alternate character to end the line. Non-@acronym{POSIX}.
11063 Switch to a different shell layer. Non-@acronym{POSIX}.
11067 Restart the output after stopping it.
11075 Send a terminal stop signal.
11079 Send a terminal stop signal after flushing the input. Non-@acronym{POSIX}.
11083 Redraw the current line. Non-@acronym{POSIX}.
11087 Erase the last word typed. Non-@acronym{POSIX}.
11091 Enter the next character typed literally, even if it is a special
11092 character. Non-@acronym{POSIX}.
11097 @subsection Special settings
11099 @cindex special settings
11104 Set the minimum number of characters that will satisfy a read until
11105 the time value has expired, when @option{-icanon} is set.
11109 Set the number of tenths of a second before reads time out if the minimum
11110 number of characters have not been read, when @option{-icanon} is set.
11112 @item ispeed @var{n}
11114 Set the input speed to @var{n}.
11116 @item ospeed @var{n}
11118 Set the output speed to @var{n}.
11122 Tell the tty kernel driver that the terminal has @var{n} rows. Non-@acronym{POSIX}.
11125 @itemx columns @var{n}
11128 Tell the kernel that the terminal has @var{n} columns. Non-@acronym{POSIX}.
11134 Print the number of rows and columns that the kernel thinks the
11135 terminal has. (Systems that don't support rows and columns in the kernel
11136 typically use the environment variables @env{LINES} and @env{COLUMNS}
11137 instead; however, GNU @command{stty} does not know anything about them.)
11138 Non-@acronym{POSIX}.
11142 Use line discipline @var{n}. Non-@acronym{POSIX}.
11146 Print the terminal speed.
11149 @cindex baud rate, setting
11150 @c FIXME: Is this still true that the baud rate can't be set
11151 @c higher than 38400?
11152 Set the input and output speeds to @var{n}. @var{n} can be one
11153 of: 0 50 75 110 134 134.5 150 200 300 600 1200 1800 2400 4800 9600
11154 19200 38400 @code{exta} @code{extb}. @code{exta} is the same as
11155 19200; @code{extb} is the same as 38400. 0 hangs up the line if
11156 @option{-clocal} is set.
11160 @node printenv invocation
11161 @section @command{printenv}: Print all or some environment variables
11164 @cindex printing all or some environment variables
11165 @cindex environment variables, printing
11167 @command{printenv} prints environment variable values. Synopsis:
11170 printenv [@var{option}] [@var{variable}]@dots{}
11173 If no @var{variable}s are specified, @command{printenv} prints the value of
11174 every environment variable. Otherwise, it prints the value of each
11175 @var{variable} that is set, and nothing for those that are not set.
11177 The only options are a lone @option{--help} or @option{--version}.
11178 @xref{Common options}.
11180 @cindex exit status of @command{printenv}
11184 0 if all variables specified were found
11185 1 if at least one specified variable was not found
11186 2 if a write error occurred
11190 @node tty invocation
11191 @section @command{tty}: Print file name of terminal on standard input
11194 @cindex print terminal file name
11195 @cindex terminal file name, printing
11197 @command{tty} prints the file name of the terminal connected to its standard
11198 input. It prints @samp{not a tty} if standard input is not a terminal.
11202 tty [@var{option}]@dots{}
11205 The program accepts the following option. Also see @ref{Common options}.
11215 Print nothing; only return an exit status.
11219 @cindex exit status of @command{tty}
11223 0 if standard input is a terminal
11224 1 if standard input is not a terminal
11225 2 if given incorrect arguments
11226 3 if a write error occurs
11230 @node User information
11231 @chapter User information
11233 @cindex user information, commands for
11234 @cindex commands for printing user information
11236 This section describes commands that print user-related information:
11237 logins, groups, and so forth.
11240 * id invocation:: Print user identity.
11241 * logname invocation:: Print current login name.
11242 * whoami invocation:: Print effective user ID.
11243 * groups invocation:: Print group names a user is in.
11244 * users invocation:: Print login names of users currently logged in.
11245 * who invocation:: Print who is currently logged in.
11249 @node id invocation
11250 @section @command{id}: Print user identity
11253 @cindex real user and group IDs, printing
11254 @cindex effective user and group IDs, printing
11255 @cindex printing real and effective user and group IDs
11257 @command{id} prints information about the given user, or the process
11258 running it if no user is specified. Synopsis:
11261 id [@var{option}]@dots{} [@var{username}]
11264 By default, it prints the real user ID, real group ID, effective user ID
11265 if different from the real user ID, effective group ID if different from
11266 the real group ID, and supplemental group IDs.
11268 Each of these numeric values is preceded by an identifying string and
11269 followed by the corresponding user or group name in parentheses.
11271 The options cause @command{id} to print only part of the above information.
11272 Also see @ref{Common options}.
11279 Print only the group ID.
11285 Print only the group ID and the supplementary groups.
11291 Print the user or group name instead of the ID number. Requires
11292 @option{-u}, @option{-g}, or @option{-G}.
11298 Print the real, instead of effective, user or group ID. Requires
11299 @option{-u}, @option{-g}, or @option{-G}.
11305 Print only the user ID.
11312 @node logname invocation
11313 @section @command{logname}: Print current login name
11316 @cindex printing user's login name
11317 @cindex login name, printing
11318 @cindex user name, printing
11321 @command{logname} prints the calling user's name, as found in a
11322 system-maintained file (often @file{/var/run/utmp} or
11323 @file{/etc/utmp}), and exits with a status of 0. If there is no entry
11324 for the calling process, @command{logname} prints
11325 an error message and exits with a status of 1.
11327 The only options are @option{--help} and @option{--version}. @xref{Common
11333 @node whoami invocation
11334 @section @command{whoami}: Print effective user ID
11337 @cindex effective user ID, printing
11338 @cindex printing the effective user ID
11340 @command{whoami} prints the user name associated with the current
11341 effective user ID. It is equivalent to the command @samp{id -un}.
11343 The only options are @option{--help} and @option{--version}. @xref{Common
11349 @node groups invocation
11350 @section @command{groups}: Print group names a user is in
11353 @cindex printing groups a user is in
11354 @cindex supplementary groups, printing
11356 @command{groups} prints the names of the primary and any supplementary
11357 groups for each given @var{username}, or the current process if no names
11358 are given. If names are given, the name of each user is printed before
11359 the list of that user's groups. Synopsis:
11362 groups [@var{username}]@dots{}
11365 The group lists are equivalent to the output of the command @samp{id -Gn}.
11367 The only options are @option{--help} and @option{--version}. @xref{Common
11373 @node users invocation
11374 @section @command{users}: Print login names of users currently logged in
11377 @cindex printing current usernames
11378 @cindex usernames, printing current
11380 @cindex login sessions, printing users with
11381 @command{users} prints on a single line a blank-separated list of user
11382 names of users currently logged in to the current host. Each user name
11383 corresponds to a login session, so if a user has more than one login
11384 session, that user's name will appear the same number of times in the
11393 With no @var{file} argument, @command{users} extracts its information from
11394 a system-maintained file (often @file{/var/run/utmp} or
11395 @file{/etc/utmp}). If a file argument is given, @command{users} uses
11396 that file instead. A common choice is @file{/var/log/wtmp}.
11398 The only options are @option{--help} and @option{--version}. @xref{Common
11404 @node who invocation
11405 @section @command{who}: Print who is currently logged in
11408 @cindex printing current user information
11409 @cindex information, about current users
11411 @command{who} prints information about users who are currently logged on.
11415 @command{who} [@var{option}] [@var{file}] [am i]
11418 @cindex terminal lines, currently used
11420 @cindex remote hostname
11421 If given no non-option arguments, @command{who} prints the following
11422 information for each user currently logged on: login name, terminal
11423 line, login time, and remote hostname or X display.
11427 If given one non-option argument, @command{who} uses that instead of
11428 a default system-maintained file (often @file{/var/run/utmp} or
11429 +@file{/etc/utmp}) as the name of the file containing the record of
11430 users logged on. @file{/var/log/wtmp} is commonly given as an argument
11431 to @command{who} to look at who has previously logged on.
11435 If given two non-option arguments, @command{who} prints only the entry
11436 for the user running it (determined from its standard input), preceded
11437 by the hostname. Traditionally, the two arguments given are @samp{am
11438 i}, as in @samp{who am i}.
11441 Time stamps are listed according to the time zone rules specified by
11442 the @env{TZ} environment variable, or by the system default rules if
11443 @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
11444 with @env{TZ}, libc, The GNU C Library}.
11446 The program accepts the following options. Also see @ref{Common options}.
11454 Same as @samp{-b -d --login -p -r -t -T -u}.
11460 Print the date and time of last system boot.
11466 Print information corresponding to dead processes.
11472 Print column headings.
11478 Include idle time in HOURS:MINUTES, @samp{.} (to indicate
11479 current process), or @samp{old}.
11483 Same as @samp{who am i}.
11489 Print only the login names and the number of users logged on.
11490 Overrides all other options.
11494 Ignored; for compatibility with other versions of @command{who}.
11503 After the login time, print the number of hours and minutes that the
11504 user has been idle. @samp{.} means the user was active in last minute.
11505 @samp{old} means the user was idle for more than 24 hours.
11511 List only the entries that correspond to processes via which the
11512 system is waiting for a user to login. The user name is always @samp{LOGIN}.
11516 Attempt to canonicalize hostnames found in utmp through a DNS lookup. This
11517 is not the default because it can cause significant delays on systems with
11518 automatic dial-up internet access.
11524 Print a line of column headings.
11535 @opindex --writable
11536 @cindex message status
11537 @pindex write@r{, allowed}
11538 After each login name print a character indicating the user's message status:
11541 @samp{+} allowing @code{write} messages
11542 @samp{-} disallowing @code{write} messages
11543 @samp{?} cannot find terminal device
11551 @node System context
11552 @chapter System context
11554 @cindex system context
11555 @cindex context, system
11556 @cindex commands for system context
11558 This section describes commands that print or change system-wide
11562 * date invocation:: Print or set system date and time.
11563 * uname invocation:: Print system information.
11564 * hostname invocation:: Print or set system name.
11565 * hostid invocation:: Print numeric host identifier.
11569 @node date invocation
11570 @section @command{date}: Print or set system date and time
11573 @cindex time, printing or setting
11574 @cindex printing the current time
11579 date [@var{option}]@dots{} [+@var{format}]
11580 date [-u|--utc|--universal] @c this avoids a newline in the output
11581 [ MMDDhhmm[[CC]YY][.ss] ]
11585 Invoking @command{date} with no @var{format} argument is equivalent to invoking
11586 it with a default format that depends on the @env{LC_TIME} locale category.
11587 In the default C locale, this format is @samp{'+%a %b %e %H:%M:%S %Z %Y'},
11588 so the output looks like @samp{Thu Mar @ 3 13:47:51 PST 2005}.
11591 Normally, @command{date} uses the time zone rules indicated by the
11592 @env{TZ} environment variable, or the system default rules if @env{TZ}
11593 is not set. @xref{TZ Variable,, Specifying the Time Zone with
11594 @env{TZ}, libc, The GNU C Library}.
11596 @findex strftime @r{and @command{date}}
11597 @cindex time formats
11598 @cindex formatting times
11599 If given an argument that starts with a @samp{+}, @command{date} prints the
11600 current time and date (or the time and date specified by the
11601 @option{--date} option, see below) in the format defined by that argument,
11602 which is similar to that of the @code{strftime} function. Except for
11603 conversion specifiers, which start with @samp{%}, characters in the
11604 format string are printed unchanged. The conversion specifiers are
11610 * Time conversion specifiers:: %[HIklMNpPrRsSTXzZ]
11611 * Date conversion specifiers:: %[aAbBcCdDeFgGhjmuUVwWxyY]
11612 * Literal conversion specifiers:: %[%nt]
11613 * Padding and other flags:: Pad with zeroes, spaces, etc.
11614 * Setting the time:: Changing the system clock.
11615 * Options for date:: Instead of the current time.
11616 * Examples of date:: Examples.
11619 @node Time conversion specifiers
11620 @subsection Time conversion specifiers
11622 @cindex time conversion specifiers
11623 @cindex conversion specifiers, time
11625 @command{date} conversion specifiers related to times.
11629 hour (@samp{00}@dots{}@samp{23})
11631 hour (@samp{01}@dots{}@samp{12})
11633 hour (@samp{ 0}@dots{}@samp{23}).
11634 This is a @acronym{GNU} extension.
11636 hour (@samp{ 1}@dots{}@samp{12}).
11637 This is a @acronym{GNU} extension.
11639 minute (@samp{00}@dots{}@samp{59})
11641 nanoseconds (@samp{000000000}@dots{}@samp{999999999}).
11642 This is a @acronym{GNU} extension.
11644 locale's equivalent of either @samp{AM} or @samp{PM};
11645 blank in many locales.
11646 Noon is treated as @samp{PM} and midnight as @samp{AM}.
11648 like @samp{%p}, except lower case.
11649 This is a @acronym{GNU} extension.
11651 locale's 12-hour clock time (e.g., @samp{11:11:04 PM})
11653 24-hour hour and minute. Same as @samp{%H:%M}.
11654 This is a @acronym{GNU} extension.
11656 @cindex epoch, seconds since
11657 @cindex seconds since the epoch
11658 @cindex beginning of time
11659 seconds since the epoch, i.e., since 1970-01-01 00:00:00 UTC.
11660 Leap seconds are not counted unless leap second support is available.
11661 @xref{%s-examples}, for examples.
11662 This is a @acronym{GNU} extension.
11664 second (@samp{00}@dots{}@samp{60}).
11665 This may be @samp{60} if leap seconds are supported.
11667 24-hour hour, minute, and second. Same as @samp{%H:%M:%S}.
11669 locale's time representation (e.g., @samp{23:13:48})
11671 @w{RFC 2822/ISO 8601} style numeric time zone (e.g., @samp{-0600}
11672 or @samp{+0100}), or nothing if no
11673 time zone is determinable. This value reflects the numeric time zone
11674 appropriate for the current time, using the time zone rules specified
11675 by the @env{TZ} environment variable.
11676 The time (and optionally, the time zone rules) can be overridden
11677 by the @option{--date} option.
11678 This is a @acronym{GNU} extension.
11680 alphabetic time zone abbreviation (e.g., @samp{EDT}), or nothing if no
11681 time zone is determinable. See @samp{%z} for how it is determined.
11685 @node Date conversion specifiers
11686 @subsection Date conversion specifiers
11688 @cindex date conversion specifiers
11689 @cindex conversion specifiers, date
11691 @command{date} conversion specifiers related to dates.
11695 locale's abbreviated weekday name (e.g., @samp{Sun})
11697 locale's full weekday name, variable length (e.g., @samp{Sunday})
11699 locale's abbreviated month name (e.g., @samp{Jan})
11701 locale's full month name, variable length (e.g., @samp{January})
11703 locale's date and time (e.g., @samp{Thu Mar @ 3 23:05:25 2005})
11705 century. This is like @samp{%Y}, except the last two digits are omitted.
11706 For example, it is @samp{20} if @samp{%Y} is @samp{2000},
11707 and is @samp{-0} if @samp{%Y} is @samp{-001}.
11708 It is normally at least two characters, but it may be more.
11710 day of month (e.g., @samp{01})
11712 date; same as @samp{%m/%d/%y}
11714 day of month, space padded; same as @samp{%_d}
11716 full date in @w{ISO 8601} format; same as @samp{%Y-%m-%d}.
11717 This is a good choice for a date format, as it is standard and
11718 is easy to sort in the usual case where years are in the range
11720 This is a @acronym{GNU} extension.
11722 The year corresponding to the ISO week number, but without the century
11723 (range @samp{00} through @samp{99}). This has the same format and value
11724 as @samp{%y}, except that if the ISO week number (see @samp{%V}) belongs
11725 to the previous or next year, that year is used instead.
11726 This is a @acronym{GNU} extension.
11728 The year corresponding to the ISO week number. This has the same format
11729 and value as @samp{%Y}, except that if the ISO week number (see
11730 @samp{%V}) belongs to the previous or next year, that year is used
11732 This is a @acronym{GNU} extension.
11736 day of year (@samp{001}@dots{}@samp{366})
11738 month (@samp{01}@dots{}@samp{12})
11740 day of week (@samp{1}@dots{}@samp{7}) with @samp{1} corresponding to Monday
11742 week number of year with Sunday as first day of week
11743 (@samp{00}@dots{}@samp{53}).
11744 Days in a new year preceding the first Sunday are in week zero.
11746 week number of year with Monday as first day of the week as a decimal
11747 (@samp{01}@dots{}@samp{53}).
11748 If the week containing January 1 has four or more days in
11749 the new year, then it is considered week 1; otherwise, it is week 53 of
11750 the previous year, and the next week is week 1. (See the @acronym{ISO} 8601
11753 day of week (@samp{0}@dots{}@samp{6}) with 0 corresponding to Sunday
11755 week number of year with Monday as first day of week
11756 (@samp{00}@dots{}@samp{53}).
11757 Days in a new year preceding the first Monday are in week zero.
11759 locale's date representation (e.g., @samp{12/31/99})
11761 last two digits of year (@samp{00}@dots{}@samp{99})
11763 year. This is normally at least four characters, but it may be more.
11764 Year @samp{0000} precedes year @samp{0001}, and year @samp{-001}
11765 precedes year @samp{0000}.
11769 @node Literal conversion specifiers
11770 @subsection Literal conversion specifiers
11772 @cindex literal conversion specifiers
11773 @cindex conversion specifiers, literal
11775 @command{date} conversion specifiers that produce literal strings.
11787 @node Padding and other flags
11788 @subsection Padding and other flags
11790 @cindex numeric field padding
11791 @cindex padding of numeric fields
11792 @cindex fields, padding numeric
11794 Unless otherwise specified, @command{date} normally pads numeric fields
11795 with zeroes, so that, for
11796 example, numeric months are always output as two digits.
11797 Seconds since the epoch are not padded, though,
11798 since there is no natural width for them.
11800 As a @acronym{GNU} extension, @command{date} recognizes any of the
11801 following optional flags after the @samp{%}:
11805 (hyphen) Do not pad the field; useful if the output is intended for
11808 (underscore) Pad with spaces; useful if you need a fixed
11809 number of characters in the output, but zeroes are too distracting.
11811 (zero) Pad with zeros even if the conversion specifier
11812 would normally pad with spaces.
11814 Use upper case characters if possible.
11816 Use opposite case characters if possible.
11817 A field that is normally upper case becomes lower case, and vice versa.
11821 Here are some examples of padding:
11824 date +%d/%m -d "Feb 1"
11826 date +%-d/%-m -d "Feb 1"
11828 date +%_d/%_m -d "Feb 1"
11832 As a @acronym{GNU} extension, you can specify the field width
11833 (after any flag, if present) as a decimal number. If the natural size of the
11834 output is of the field has less than the specified number of characters,
11835 the result is written right adjusted and padded to the given
11836 size. For example, @samp{%9B} prints the right adjusted month name in
11837 a field of width 9.
11839 An optional modifier can follow the optional flag and width
11840 specification. The modifiers are:
11844 Use the locale's alternate representation for date and time. This
11845 modifier applies to the @samp{%c}, @samp{%C}, @samp{%x}, @samp{%X},
11846 @samp{%y} and @samp{%Y} conversion specifiers. In a Japanese locale, for
11847 example, @samp{%Ex} might yield a date format based on the Japanese
11851 Use the locale's alternate numeric symbols for numbers. This modifier
11852 applies only to numeric conversion specifiers.
11855 If the format supports the modifier but no alternate representation
11856 is available, it is ignored.
11859 @node Setting the time
11860 @subsection Setting the time
11862 @cindex setting the time
11863 @cindex time setting
11864 @cindex appropriate privileges
11866 If given an argument that does not start with @samp{+}, @command{date} sets
11867 the system clock to the time and date specified by that argument (as
11868 described below). You must have appropriate privileges to set the
11869 system clock. The @option{--date} and @option{--set} options may not be
11870 used with such an argument. The @option{--universal} option may be used
11871 with such an argument to indicate that the specified time and date are
11872 relative to Coordinated Universal Time rather than to the local time
11875 The argument must consist entirely of digits, which have the following
11888 first two digits of year (optional)
11890 last two digits of year (optional)
11895 The @option{--set} option also sets the system clock; see the next section.
11898 @node Options for date
11899 @subsection Options for @command{date}
11901 @cindex @command{date} options
11902 @cindex options for @command{date}
11904 The program accepts the following options. Also see @ref{Common options}.
11908 @item -d @var{datestr}
11909 @itemx --date=@var{datestr}
11912 @cindex parsing date strings
11913 @cindex date strings, parsing
11914 @cindex arbitrary date strings, parsing
11917 @opindex next @var{day}
11918 @opindex last @var{day}
11919 Display the time and date specified in @var{datestr} instead of the
11920 current time and date. @var{datestr} can be in almost any common
11921 format. It can contain month names, time zones, @samp{am} and @samp{pm},
11922 @samp{yesterday}, etc. For example, @option{--date="2004-02-27
11923 14:19:13.489392193 +0530"} specifies the instant of time that is
11924 489,392,193 nanoseconds after February 27, 2004 at 2:19:13 PM in a
11925 time zone that is 5 hours and 30 minutes east of @acronym{UTC}.
11926 @xref{Date input formats}.
11928 @item -f @var{datefile}
11929 @itemx --file=@var{datefile}
11932 Parse each line in @var{datefile} as with @option{-d} and display the
11933 resulting time and date. If @var{datefile} is @samp{-}, use standard
11934 input. This is useful when you have many dates to process, because the
11935 system overhead of starting up the @command{date} executable many times can
11938 @item -I[@var{timespec}]
11939 @itemx --iso-8601[=@var{timespec}]
11940 @opindex -I[@var{timespec}]
11941 @opindex --iso-8601[=@var{timespec}]
11942 Display the date using the @acronym{ISO} 8601 format, @samp{%Y-%m-%d}.
11944 The argument @var{timespec} specifies the number of additional
11945 terms of the time to include. It can be one of the following:
11948 Print just the date. This is the default if @var{timespec} is omitted.
11951 Append the hour of the day to the date.
11954 Append the hours and minutes.
11957 Append the hours, minutes, and seconds.
11960 Append the hours, minutes, seconds, and nanoseconds.
11963 If showing any time terms, then include the time zone using the format
11971 @opindex --rfc-2822
11972 Display the time and date using the format @samp{%a, %d %b %Y %H:%M:%S
11973 %z}, evaluated in the C locale so abbreviations are always in English.
11977 Fri,@ @ 1 Aug 2003 23:05:56 -0700
11980 This format conforms to
11981 @uref{ftp://ftp.rfc-editor.org/in-notes/rfc2822.txt, RFC 2822} and
11982 @uref{ftp://ftp.rfc-editor.org/in-notes/rfc822.txt, RFC 822}, the
11983 current and previous standards for Internet email.
11985 @item -r @var{file}
11986 @itemx --reference=@var{file}
11988 @opindex --reference
11989 Display the time and date reference according to the last modification
11990 time of @var{file}, instead of the current time and date.
11992 @item -s @var{datestr}
11993 @itemx --set=@var{datestr}
11996 Set the time and date to @var{datestr}. See @option{-d} above.
12003 @opindex --universal
12004 @cindex Coordinated Universal Time
12006 @cindex Greenwich Mean Time
12009 Use Coordinated Universal Time (@acronym{UTC}) by operating as if the
12010 @env{TZ} environment variable were set to the string @samp{UTC0}.
12012 Universal Time is often called ``Greenwich Mean Time'' (@sc{gmt}) for
12013 historical reasons.
12017 @node Examples of date
12018 @subsection Examples of @command{date}
12020 @cindex examples of @command{date}
12022 Here are a few examples. Also see the documentation for the @option{-d}
12023 option in the previous section.
12028 To print the date of the day before yesterday:
12031 date --date='2 days ago'
12035 To print the date of the day three months and one day hence:
12038 date --date='3 months 1 day'
12042 To print the day of year of Christmas in the current year:
12045 date --date='25 Dec' +%j
12049 To print the current full month name and the day of the month:
12055 But this may not be what you want because for the first nine days of
12056 the month, the @samp{%d} expands to a zero-padded two-digit field,
12057 for example @samp{date -d 1may '+%B %d'} will print @samp{May 01}.
12060 To print a date without the leading zero for one-digit days
12061 of the month, you can use the (@acronym{GNU} extension)
12062 @samp{-} flag to suppress
12063 the padding altogether:
12066 date -d 1may '+%B %-d
12070 To print the current date and time in the format required by many
12071 non-@acronym{GNU} versions of @command{date} when setting the system clock:
12074 date +%m%d%H%M%Y.%S
12078 To set the system clock forward by two minutes:
12081 date --set='+2 minutes'
12085 To print the date in the format specified by RFC-2822,
12086 use @samp{date --rfc-2822}. I just did and saw this:
12089 Thu, 31 Jul 2003 13:13:05 -0700
12092 @anchor{%s-examples}
12094 To convert a date string to the number of seconds since the epoch
12095 (which is 1970-01-01 00:00:00 UTC), use the @option{--date} option with
12096 the @samp{%s} format. That can be useful in sorting and/or graphing
12097 and/or comparing data by date. The following command outputs the
12098 number of the seconds since the epoch for the time two minutes after the
12102 date --date='1970-01-01 00:02:00 +0000' +%s
12106 If you do not specify time zone information in the date string,
12107 @command{date} uses your computer's idea of the time zone when
12108 interpreting the string. For example, if your computer's time zone is
12109 that of Cambridge, Massachusetts, which was then 5 hours (i.e., 18,000
12110 seconds) behind UTC:
12113 # local time zone used
12114 date --date='1970-01-01 00:02:00' +%s
12119 If you're sorting or graphing dated data, your raw date values may be
12120 represented as seconds since the epoch. But few people can look at
12121 the date @samp{946684800} and casually note ``Oh, that's the first second
12122 of the year 2000 in Greenwich, England.''
12125 date --date='2000-01-01 UTC' +%s
12129 An alternative is to use the @option{--utc} (@option{-u}) option.
12130 Then you may omit @samp{UTC} from the date string. Although this
12131 produces the same result for @samp{%s} and many other format sequences,
12132 with a time zone offset different from zero, it would give a different
12133 result for zone-dependent formats like @samp{%z}.
12136 date -u --date=2000-01-01 +%s
12140 To convert such an unwieldy number of seconds back to
12141 a more readable form, use a command like this:
12144 # local time zone used
12145 date -d '1970-01-01 UTC 946684800 seconds' +"%Y-%m-%d %T %z"
12146 1999-12-31 19:00:00 -0500
12149 Often it is better to output UTC-relative date and time:
12152 date -u -d '1970-01-01 946684800 seconds' +"%Y-%m-%d %T %z"
12153 2000-01-01 00:00:00 +0000
12159 @node uname invocation
12160 @section @command{uname}: Print system information
12163 @cindex print system information
12164 @cindex system information, printing
12166 @command{uname} prints information about the machine and operating system
12167 it is run on. If no options are given, @command{uname} acts as if the
12168 @option{-s} option were given. Synopsis:
12171 uname [@var{option}]@dots{}
12174 If multiple options or @option{-a} are given, the selected information is
12175 printed in this order:
12178 @var{kernel-name} @var{nodename} @var{kernel-release} @var{kernel-version}
12179 @var{machine} @var{processor} @var{hardware-platform} @var{operating-system}
12182 The information may contain internal spaces, so such output cannot be
12183 parsed reliably. In the following example, @var{release} is
12184 @samp{2.2.18ss.e820-bda652a #4 SMP Tue Jun 5 11:24:08 PDT 2001}:
12188 @result{} Linux dum 2.2.18 #4 SMP Tue Jun 5 11:24:08 PDT 2001 i686 unknown unknown GNU/Linux
12192 The program accepts the following options. Also see @ref{Common options}.
12200 Print all of the below information.
12203 @itemx --hardware-platform
12205 @opindex --hardware-platform
12206 @cindex implementation, hardware
12207 @cindex hardware platform
12208 @cindex platform, hardware
12209 Print the hardware platform name
12210 (sometimes called the hardware implementation).
12216 @cindex machine type
12217 @cindex hardware class
12218 @cindex hardware type
12219 Print the machine hardware name (sometimes called the hardware class
12225 @opindex --nodename
12228 @cindex network node name
12229 Print the network node hostname.
12234 @opindex --processor
12235 @cindex host processor type
12236 Print the processor type (sometimes called the instruction set
12237 architecture or ISA).
12240 @itemx --operating-system
12242 @opindex --operating-system
12243 @cindex operating system name
12244 Print the name of the operating system.
12247 @itemx --kernel-release
12249 @opindex --kernel-release
12250 @cindex kernel release
12251 @cindex release of kernel
12252 Print the kernel release.
12255 @itemx --kernel-name
12257 @opindex --kernel-name
12258 @cindex kernel name
12259 @cindex name of kernel
12260 Print the kernel name.
12261 @acronym{POSIX} 1003.1-2001 (@pxref{Standards conformance}) calls this
12262 ``the implementation of the operating system'', because the
12263 @acronym{POSIX} specification itself has no notion of ``kernel''.
12264 The kernel name might be the same as the operating system name printed
12265 by the @option{-o} or @option{--operating-system} option, but it might
12266 differ. Some operating systems (e.g., FreeBSD, HP-UX) have the same
12267 name as their underlying kernels; others (e.g., GNU/Linux, Solaris)
12271 @itemx --kernel-version
12273 @opindex --kernel-version
12274 @cindex kernel version
12275 @cindex version of kernel
12276 Print the kernel version.
12283 @node hostname invocation
12284 @section @command{hostname}: Print or set system name
12287 @cindex setting the hostname
12288 @cindex printing the hostname
12289 @cindex system name, printing
12290 @cindex appropriate privileges
12292 With no arguments, @command{hostname} prints the name of the current host
12293 system. With one argument, it sets the current host name to the
12294 specified string. You must have appropriate privileges to set the host
12298 hostname [@var{name}]
12301 The only options are @option{--help} and @option{--version}. @xref{Common
12307 @node hostid invocation
12308 @section @command{hostid}: Print numeric host identifier.
12311 @cindex printing the host identifier
12313 @command{hostid} prints the numeric identifier of the current host
12314 in hexadecimal. This command accepts no arguments.
12315 The only options are @option{--help} and @option{--version}.
12316 @xref{Common options}.
12318 For example, here's what it prints on one system I use:
12325 On that system, the 32-bit quantity happens to be closely
12326 related to the system's Internet address, but that isn't always
12332 @node Modified command invocation
12333 @chapter Modified command invocation
12335 @cindex modified command invocation
12336 @cindex invocation of commands, modified
12337 @cindex commands for invoking other commands
12339 This section describes commands that run other commands in some context
12340 different than the current one: a modified environment, as a different
12344 * chroot invocation:: Modify the root directory.
12345 * env invocation:: Modify environment variables.
12346 * nice invocation:: Modify scheduling priority.
12347 * nohup invocation:: Immunize to hangups.
12348 * su invocation:: Modify user and group ID.
12352 @node chroot invocation
12353 @section @command{chroot}: Run a command with a different root directory
12356 @cindex running a program in a specified root directory
12357 @cindex root directory, running a program in a specified
12359 @command{chroot} runs a command with a specified root directory.
12360 On many systems, only the super-user can do this.
12364 chroot @var{newroot} [@var{command} [@var{args}]@dots{}]
12365 chroot @var{option}
12368 Ordinarily, file names are looked up starting at the root of the
12369 directory structure, i.e., @file{/}. @command{chroot} changes the root to
12370 the directory @var{newroot} (which must exist) and then runs
12371 @var{command} with optional @var{args}. If @var{command} is not
12372 specified, the default is the value of the @env{SHELL} environment
12373 variable or @command{/bin/sh} if not set, invoked with the @option{-i} option.
12374 @var{command} must not be a special built-in utility
12375 (@pxref{Special built-in utilities}).
12377 The only options are @option{--help} and @option{--version}. @xref{Common
12378 options}. Options must precede operands.
12380 Here are a few tips to help avoid common problems in using chroot.
12381 To start with a simple example, make @var{command} refer to a statically
12382 linked binary. If you were to use a dynamically linked executable, then
12383 you'd have to arrange to have the shared libraries in the right place under
12384 your new root directory.
12386 For example, if you create a statically linked @command{ls} executable,
12387 and put it in @file{/tmp/empty}, you can run this command as root:
12390 $ chroot /tmp/empty /ls -Rl /
12393 Then you'll see output like this:
12398 -rwxr-xr-x 1 0 0 1041745 Aug 16 11:17 ls
12401 If you want to use a dynamically linked executable, say @command{bash},
12402 then first run @samp{ldd bash} to see what shared objects it needs.
12403 Then, in addition to copying the actual binary, also copy the listed
12404 files to the required positions under your intended new root directory.
12405 Finally, if the executable requires any other files (e.g., data, state,
12406 device files), copy them into place, too.
12408 @cindex exit status of @command{chroot}
12412 1 if @command{chroot} itself fails
12413 126 if @var{command} is found but cannot be invoked
12414 127 if @var{command} cannot be found
12415 the exit status of @var{command} otherwise
12419 @node env invocation
12420 @section @command{env}: Run a command in a modified environment
12423 @cindex environment, running a program in a modified
12424 @cindex modified environment, running a program in a
12425 @cindex running a program in a modified environment
12427 @command{env} runs a command with a modified environment. Synopses:
12430 env [@var{option}]@dots{} [@var{name}=@var{value}]@dots{} @c
12431 [@var{command} [@var{args}]@dots{}]
12435 Operands of the form @samp{@var{variable}=@var{value}} set
12436 the environment variable @var{variable} to value @var{value}.
12437 @var{value} may be empty (@samp{@var{variable}=}). Setting a variable
12438 to an empty value is different from unsetting it.
12439 These operands are evaluated left-to-right, so if two operands
12440 mention the same variable the earlier is ignored.
12442 Environment variable names can be empty, and can contain any
12443 characters other than @samp{=} and the null character (@acronym{ASCII}
12444 @sc{nul}). However, it is wise to limit yourself to names that
12445 consist solely of underscores, digits, and @acronym{ASCII} letters,
12446 and that begin with a non-digit, as applications like the shell do not
12447 work well with other names.
12450 The first operand that does not contain the character @samp{=}
12451 specifies the program to invoke; it is
12452 searched for according to the @env{PATH} environment variable. Any
12453 remaining arguments are passed as arguments to that program.
12454 The program should not be a special built-in utility
12455 (@pxref{Special built-in utilities}).
12457 @cindex environment, printing
12459 If no command name is specified following the environment
12460 specifications, the resulting environment is printed. This is like
12461 specifying the @command{printenv} program.
12463 The program accepts the following options. Also see @ref{Common options}.
12464 Options must precede operands.
12468 @item -u @var{name}
12469 @itemx --unset=@var{name}
12472 Remove variable @var{name} from the environment, if it was in the
12477 @itemx --ignore-environment
12480 @opindex --ignore-environment
12481 Start with an empty environment, ignoring the inherited environment.
12485 @cindex exit status of @command{env}
12489 0 if no @var{command} is specified and the environment is output
12490 1 if @command{env} itself fails
12491 126 if @var{command} is found but cannot be invoked
12492 127 if @var{command} cannot be found
12493 the exit status of @var{command} otherwise
12497 @node nice invocation
12498 @section @command{nice}: Run a command with modified scheduling priority
12502 @cindex modifying scheduling priority
12503 @cindex scheduling priority, modifying
12504 @cindex priority, modifying
12505 @cindex appropriate privileges
12507 @command{nice} prints or modifies a process's @dfn{nice value},
12508 a parameter that affects the process's scheduling priority.
12512 nice [@var{option}]@dots{} [@var{command} [@var{arg}]@dots{}]
12515 If no arguments are given, @command{nice} prints the current nice
12516 value, which it inherited. Otherwise, @command{nice} runs the given
12517 @var{command} with its nice value adjusted. By default, its nice
12518 value is incremented by 10.
12520 Nice values range at least from @minus{}20 (resulting in the most
12521 favorable scheduling) through 19 (the least favorable). Some systems
12522 may have a wider range of nice values; conversely, other systems may
12523 enforce more restrictive limits. An attempt to set the nice value
12524 outside the supported range is treated as an attempt to use the
12525 minimum or maximum supported value.
12527 @var{command} must not be a special built-in utility (@pxref{Special
12528 built-in utilities}).
12530 @cindex conflicts with shell built-ins
12531 @cindex built-in shell commands, conflicts with
12532 Because many shells have a built-in @command{nice} command, using an
12533 unadorned @command{nice} in a script or interactively may get you
12534 different functionality than that described here.
12536 The program accepts the following option. Also see @ref{Common options}.
12537 Options must precede operands.
12540 @item -n @var{adjustment}
12541 @itemx --adjustment=@var{adjustment}
12543 @opindex --adjustment
12544 Add @var{adjustment} instead of 10 to the command's nice value. If
12545 @var{adjustment} is negative and you lack appropriate privileges,
12546 @command{nice} issues a warning but otherwise acts as if you specified
12549 For compatibility @command{nice} also supports an obsolete
12550 option syntax @option{-@var{adjustment}}. New scripts should use
12551 @option{-n @var{adjustment}} instead.
12555 @cindex exit status of @command{nice}
12559 0 if no @var{command} is specified and the current priority is output
12560 1 if @command{nice} itself fails
12561 126 if @var{command} is found but cannot be invoked
12562 127 if @var{command} cannot be found
12563 the exit status of @var{command} otherwise
12566 It is sometimes useful to run non-interactive programs with reduced priority.
12569 $ nice factor 4611686018427387903
12572 Since @command{nice} prints the current priority,
12573 you can invoke it through itself to demonstrate how it works.
12575 The default behavior is to increase the nice value by @samp{10}:
12586 The @var{adjustment} is relative to the current nice value. In the
12587 next example, the first @command{nice} invocation runs the second one
12588 with nice value 10, and it in turn runs the final one with a nice
12589 value that is 3 more:
12592 $ nice nice -n 3 nice
12596 Specifying a nice value larger than the supported range
12597 is the same as specifying the maximum supported value:
12600 $ nice -n 10000000000 nice
12604 Only a privileged user may run a process with higher priority:
12608 nice: cannot set priority: Permission denied
12610 $ sudo nice -n -1 nice
12615 @node nohup invocation
12616 @section @command{nohup}: Run a command immune to hangups
12619 @cindex hangups, immunity to
12620 @cindex immunity to hangups
12621 @cindex logging out and continuing to run
12624 @command{nohup} runs the given @var{command} with hangup signals ignored,
12625 so that the command can continue running in the background after you log
12629 nohup @var{command} [@var{arg}]@dots{}
12633 If standard output is a terminal, the command's standard output is appended
12634 to the file @file{nohup.out}; if that cannot be written to, it is appended
12635 to the file @file{$HOME/nohup.out}; and if that cannot be written to, the
12636 command is not run.
12637 Any @file{nohup.out} or @file{$HOME/nohup.out} file created by
12638 @command{nohup} is made readable and writable only to the user,
12639 regardless of the current umask settings.
12641 If standard error is a terminal, it is redirected to the same file
12642 descriptor as the (possibly-redirected) standard output.
12644 @vindex POSIXLY_CORRECT
12645 If standard input is a terminal, it is closed so that terminal
12646 sessions do not mistakenly consider the terminal to be used by the
12647 command. To avoid glitches in poorly-written programs standard input
12648 is then reopened with an innocuous file descriptor that cannot be read
12649 from. However, these steps are skipped if @env{POSIXLY_CORRECT} is
12650 set since @acronym{POSIX} requires standard input to be left alone.
12652 @command{nohup} does not automatically put the command it runs in the
12653 background; you must do that explicitly, by ending the command line
12654 with an @samp{&}. Also, @command{nohup} does not change the
12655 scheduling priority of @var{command}; use @command{nice} for that,
12656 e.g., @samp{nohup nice @var{command}}.
12658 @var{command} must not be a special built-in utility (@pxref{Special
12659 built-in utilities}).
12661 The only options are @option{--help} and @option{--version}. @xref{Common
12662 options}. Options must precede operands.
12664 @cindex exit status of @command{nohup}
12668 126 if @var{command} is found but cannot be invoked
12669 127 if @command{nohup} itself fails or if @var{command} cannot be found
12670 the exit status of @var{command} otherwise
12674 @node su invocation
12675 @section @command{su}: Run a command with substitute user and group ID
12678 @cindex substitute user and group IDs
12679 @cindex user ID, switching
12680 @cindex super-user, becoming
12681 @cindex root, becoming
12683 @command{su} allows one user to temporarily become another user. It runs a
12684 command (often an interactive shell) with the real and effective user
12685 ID, group ID, and supplemental groups of a given @var{user}. Synopsis:
12688 su [@var{option}]@dots{} [@var{user} [@var{arg}]@dots{}]
12691 @cindex passwd entry, and @command{su} shell
12693 @flindex /etc/passwd
12694 If no @var{user} is given, the default is @code{root}, the super-user.
12695 The shell to use is taken from @var{user}'s @code{passwd} entry, or
12696 @file{/bin/sh} if none is specified there. If @var{user} has a
12697 password, @command{su} prompts for the password unless run by a user with
12698 effective user ID of zero (the super-user).
12704 @cindex login shell
12705 By default, @command{su} does not change the current directory.
12706 It sets the environment variables @env{HOME} and @env{SHELL}
12707 from the password entry for @var{user}, and if @var{user} is not
12708 the super-user, sets @env{USER} and @env{LOGNAME} to @var{user}.
12709 By default, the shell is not a login shell.
12711 Any additional @var{arg}s are passed as additional arguments to the
12714 @cindex @option{-su}
12715 GNU @command{su} does not treat @file{/bin/sh} or any other shells specially
12716 (e.g., by setting @code{argv[0]} to @option{-su}, passing @option{-c} only
12717 to certain shells, etc.).
12720 @command{su} can optionally be compiled to use @code{syslog} to report
12721 failed, and optionally successful, @command{su} attempts. (If the system
12722 supports @code{syslog}.) However, GNU @command{su} does not check if the
12723 user is a member of the @code{wheel} group; see below.
12725 The program accepts the following options. Also see @ref{Common options}.
12728 @item -c @var{command}
12729 @itemx --command=@var{command}
12732 Pass @var{command}, a single command line to run, to the shell with
12733 a @option{-c} option instead of starting an interactive shell.
12740 @cindex file name pattern expansion, disabled
12741 @cindex globbing, disabled
12742 Pass the @option{-f} option to the shell. This probably only makes sense
12743 if the shell run is @command{csh} or @command{tcsh}, for which the @option{-f}
12744 option prevents reading the startup file (@file{.cshrc}). With
12745 Bourne-like shells, the @option{-f} option disables file name pattern
12746 expansion (globbing), which is not likely to be useful.
12754 @c other variables already indexed above
12757 @cindex login shell, creating
12758 Make the shell a login shell. This means the following. Unset all
12759 environment variables except @env{TERM}, @env{HOME}, and @env{SHELL}
12760 (which are set as described above), and @env{USER} and @env{LOGNAME}
12761 (which are set, even for the super-user, as described above), and set
12762 @env{PATH} to a compiled-in default value. Change to @var{user}'s home
12763 directory. Prepend @samp{-} to the shell's name, intended to make it
12764 read its login startup file(s).
12768 @itemx --preserve-environment
12771 @opindex --preserve-environment
12772 @cindex environment, preserving
12773 @flindex /etc/shells
12774 @cindex restricted shell
12775 Do not change the environment variables @env{HOME}, @env{USER},
12776 @env{LOGNAME}, or @env{SHELL}. Run the shell given in the environment
12777 variable @env{SHELL} instead of the shell from @var{user}'s passwd
12778 entry, unless the user running @command{su} is not the superuser and
12779 @var{user}'s shell is restricted. A @dfn{restricted shell} is one that
12780 is not listed in the file @file{/etc/shells}, or in a compiled-in list
12781 if that file does not exist. Parts of what this option does can be
12782 overridden by @option{--login} and @option{--shell}.
12784 @item -s @var{shell}
12785 @itemx --shell=@var{shell}
12788 Run @var{shell} instead of the shell from @var{user}'s passwd entry,
12789 unless the user running @command{su} is not the superuser and @var{user}'s
12790 shell is restricted (see @option{-m} just above).
12794 @cindex exit status of @command{su}
12798 1 if @command{su} itself fails
12799 126 if subshell is found but cannot be invoked
12800 127 if subshell cannot be found
12801 the exit status of the subshell otherwise
12804 @cindex wheel group, not supported
12805 @cindex group wheel, not supported
12807 @subsection Why GNU @command{su} does not support the @samp{wheel} group
12809 (This section is by Richard Stallman.)
12813 Sometimes a few of the users try to hold total power over all the
12814 rest. For example, in 1984, a few users at the MIT AI lab decided to
12815 seize power by changing the operator password on the Twenex system and
12816 keeping it secret from everyone else. (I was able to thwart this coup
12817 and give power back to the users by patching the kernel, but I
12818 wouldn't know how to do that in Unix.)
12820 However, occasionally the rulers do tell someone. Under the usual
12821 @command{su} mechanism, once someone learns the root password who
12822 sympathizes with the ordinary users, he or she can tell the rest. The
12823 ``wheel group'' feature would make this impossible, and thus cement the
12824 power of the rulers.
12826 I'm on the side of the masses, not that of the rulers. If you are
12827 used to supporting the bosses and sysadmins in whatever they do, you
12828 might find this idea strange at first.
12831 @node Process control
12832 @chapter Process control
12834 @cindex processes, commands for controlling
12835 @cindex commands for controlling processes
12838 * kill invocation:: Sending a signal to processes.
12842 @node kill invocation
12843 @section @command{kill}: Send a signal to processes
12846 @cindex send a signal to processes
12848 The @command{kill} command sends a signal to processes, causing them
12849 to terminate or otherwise act upon receiving the signal in some way.
12850 Alternatively, it lists information about signals. Synopses:
12853 kill [-s @var{signal} | --signal @var{signal} | -@var{signal}] @var{pid}@dots{}
12854 kill [-l | --list | -t | --table] [@var{signal}]@dots{}
12857 The first form of the @command{kill} command sends a signal to all
12858 @var{pid} arguments. The default signal to send if none is specified
12859 is @samp{TERM}. The special signal number @samp{0} does not denote a
12860 valid signal, but can be used to test whether the @var{pid} arguments
12861 specify processes to which a signal could be sent.
12863 If @var{pid} is positive, the signal is sent to the process with the
12864 process ID @var{pid}. If @var{pid} is zero, the signal is sent to all
12865 processes in the process group of the current process. If @var{pid}
12866 is @minus{}1, the signal is sent to all processes for which the user has
12867 permission to send a signal. If @var{pid} is less than @minus{}1, the signal
12868 is sent to all processes in the process group that equals the absolute
12869 value of @var{pid}.
12871 If @var{pid} is not positive, a system-dependent set of system
12872 processes is excluded from the list of processes to which the signal
12875 If a negative @var{PID} argument is desired as the first one, it
12876 should be preceded by @option{--}. However, as a common extension to
12877 @acronym{POSIX}, @option{--} is not required with @samp{kill
12878 -@var{signal} -@var{pid}}. The following commands are equivalent:
12887 The first form of the @command{kill} command succeeds if every @var{pid}
12888 argument specifies at least one process that the signal was sent to.
12890 The second form of the @command{kill} command lists signal information.
12891 Either the @option{-l} or @option{--list} option, or the @option{-t}
12892 or @option{--table} option must be specified. Without any
12893 @var{signal} argument, all supported signals are listed. The output
12894 of @option{-l} or @option{--list} is a list of the signal names, one
12895 per line; if @var{signal} is already a name, the signal number is
12896 printed instead. The output of @option{-t} or @option{--table} is a
12897 table of signal numbers, names, and descriptions. This form of the
12898 @command{kill} command succeeds if all @var{signal} arguments are valid
12899 and if there is no output error.
12901 The @command{kill} command also supports the @option{--help} and
12902 @option{--version} options. @xref{Common options}.
12904 A @var{signal} may be a signal name like @samp{HUP}, or a signal
12905 number like @samp{1}, or an exit status of a process terminated by the
12906 signal. A signal name can be given in canonical form or prefixed by
12907 @samp{SIG}. The case of the letters is ignored, except for the
12908 @option{-@var{signal}} option which must use upper case to avoid
12909 ambiguity with lower case option letters. The following signal names
12910 and numbers are supported on all @acronym{POSIX} compliant systems:
12916 2. Terminal interrupt.
12922 9. Kill (cannot be caught or ignored).
12930 Other supported signal names have system-dependent corresponding
12931 numbers. All systems conforming to @acronym{POSIX} 1003.1-2001 also
12932 support the following signals:
12936 Access to an undefined portion of a memory object.
12938 Child process terminated, stopped, or continued.
12940 Continue executing, if stopped.
12942 Erroneous arithmetic operation.
12944 Illegal Instruction.
12946 Write on a pipe with no one to read it.
12948 Invalid memory reference.
12950 Stop executing (cannot be caught or ignored).
12954 Background process attempting read.
12956 Background process attempting write.
12958 High bandwidth data is available at a socket.
12960 User-defined signal 1.
12962 User-defined signal 2.
12966 @acronym{POSIX} 1003.1-2001 systems that support the @acronym{XSI} extension
12967 also support the following signals:
12973 Profiling timer expired.
12977 Trace/breakpoint trap.
12979 Virtual timer expired.
12981 CPU time limit exceeded.
12983 File size limit exceeded.
12987 @acronym{POSIX} 1003.1-2001 systems that support the @acronym{XRT} extension
12988 also support at least eight real-time signals called @samp{RTMIN},
12989 @samp{RTMIN+1}, @dots{}, @samp{RTMAX-1}, @samp{RTMAX}.
12995 @cindex delaying commands
12996 @cindex commands for delaying
12998 @c Perhaps @command{wait} or other commands should be described here also?
13001 * sleep invocation:: Delay for a specified time.
13005 @node sleep invocation
13006 @section @command{sleep}: Delay for a specified time
13009 @cindex delay for a specified time
13011 @command{sleep} pauses for an amount of time specified by the sum of
13012 the values of the command line arguments.
13016 sleep @var{number}[smhd]@dots{}
13020 Each argument is a number followed by an optional unit; the default
13021 is seconds. The units are:
13034 Historical implementations of @command{sleep} have required that
13035 @var{number} be an integer. However, GNU @command{sleep} accepts
13036 arbitrary floating point numbers (using a period before any fractional
13039 The only options are @option{--help} and @option{--version}. @xref{Common
13045 @node Numeric operations
13046 @chapter Numeric operations
13048 @cindex numeric operations
13049 These programs do numerically-related operations.
13052 * factor invocation:: Show factors of numbers.
13053 * seq invocation:: Print sequences of numbers.
13057 @node factor invocation
13058 @section @command{factor}: Print prime factors
13061 @cindex prime factors
13063 @command{factor} prints prime factors. Synopses:
13066 factor [@var{number}]@dots{}
13067 factor @var{option}
13070 If no @var{number} is specified on the command line, @command{factor} reads
13071 numbers from standard input, delimited by newlines, tabs, or spaces.
13073 The only options are @option{--help} and @option{--version}. @xref{Common
13076 The algorithm it uses is not very sophisticated, so for some inputs
13077 @command{factor} runs for a long time. The hardest numbers to factor are
13078 the products of large primes. Factoring the product of the two largest 32-bit
13079 prime numbers takes about 80 seconds of CPU time on a 1.6 GHz Athlon.
13082 $ p=`echo '4294967279 * 4294967291'|bc`
13084 18446743979220271189: 4294967279 4294967291
13087 Similarly, it takes about 80 seconds for GNU factor (from coreutils-5.1.2)
13088 to ``factor'' the largest 64-bit prime:
13091 $ factor 18446744073709551557
13092 18446744073709551557: 18446744073709551557
13095 In contrast, @command{factor} factors the largest 64-bit number in just
13096 over a tenth of a second:
13099 $ factor `echo '2^64-1'|bc`
13100 18446744073709551615: 3 5 17 257 641 65537 6700417
13106 @node seq invocation
13107 @section @command{seq}: Print numeric sequences
13110 @cindex numeric sequences
13111 @cindex sequence of numbers
13113 @command{seq} prints a sequence of numbers to standard output. Synopses:
13116 seq [@var{option}]@dots{} @var{last}
13117 seq [@var{option}]@dots{} @var{first} @var{last}
13118 seq [@var{option}]@dots{} @var{first} @var{increment} @var{last}
13121 @command{seq} prints the numbers from @var{first} to @var{last} by
13122 @var{increment}. By default, each number is printed on a separate line.
13123 When @var{increment} is not specified, it defaults to @samp{1},
13124 even when @var{first} is larger than @var{last}.
13125 @var{first} also defaults to @samp{1}. So @code{seq 1} prints
13126 @samp{1}, but @code{seq 0} and @code{seq 10 5} produce no output.
13127 Floating-point numbers
13128 may be specified (using a period before any fractional digits).
13130 The program accepts the following options. Also see @ref{Common options}.
13131 Options must precede operands.
13134 @item -f @var{format}
13135 @itemx --format=@var{format}
13136 @opindex -f @var{format}
13137 @opindex --format=@var{format}
13138 @cindex formatting of numbers in @command{seq}
13139 Print all numbers using @var{format}; default @samp{%g}.
13140 @var{format} must contain exactly one of the floating point
13141 output formats @samp{%e}, @samp{%f}, or @samp{%g}.
13143 @item -s @var{string}
13144 @itemx --separator=@var{string}
13145 @cindex separator for numbers in @command{seq}
13146 Separate numbers with @var{string}; default is a newline.
13147 The output always terminates with a newline.
13150 @itemx --equal-width
13151 Print all numbers with the same width, by padding with leading zeroes.
13152 (To have other kinds of padding, use @option{--format}).
13156 If you want to use @command{seq} to print sequences of large integer values,
13157 don't use the default @samp{%g} format since it can result in
13161 $ seq 1000000 1000001
13166 Instead, you can use the format, @samp{%1.f},
13167 to print large decimal numbers with no exponent and no decimal point.
13170 $ seq --format=%1.f 1000000 1000001
13175 If you want hexadecimal output, you can use @command{printf}
13176 to perform the conversion:
13179 $ printf %x'\n' `seq -f %1.f 1048575 1024 1050623`
13185 For very long lists of numbers, use xargs to avoid
13186 system limitations on the length of an argument list:
13189 $ seq -f %1.f 1000000 | xargs printf %x'\n' | tail -n 3
13195 To generate octal output, use the printf @code{%o} format instead
13196 of @code{%x}. Note however that using printf might not work for numbers
13197 outside the usual 32-bit range:
13200 $ printf "%x\n" `seq -f %1.f 4294967295 4294967296`
13202 bash: printf: 4294967296: Numerical result out of range
13205 On most systems, seq can produce whole-number output for values up to
13206 @code{2^53}, so here's a more general approach to base conversion that
13207 also happens to be more robust for such large numbers. It works by
13208 using @code{bc} and setting its output radix variable, @var{obase},
13209 to @samp{16} in this case to produce hexadecimal output.
13212 $ (echo obase=16; seq -f %1.f 4294967295 4294967296)|bc
13217 Be careful when using @command{seq} with a fractional @var{increment},
13218 otherwise you may see surprising results. Most people would expect to
13219 see @code{0.3} printed as the last number in this example:
13222 $ seq -s ' ' 0 .1 .3
13226 But that doesn't happen on most systems because @command{seq} is
13227 implemented using binary floating point arithmetic (via the C
13228 @code{double} type)---which means some decimal numbers like @code{.1}
13229 cannot be represented exactly. That in turn means some nonintuitive
13230 conditions like @w{@code{.1 * 3 > .3}} will end up being true.
13232 To work around that in the above example, use a slightly larger number as
13233 the @var{last} value:
13236 $ seq -s ' ' 0 .1 .31
13240 In general, when using an @var{increment} with a fractional part, where
13241 (@var{last} - @var{first}) / @var{increment} is (mathematically) a whole
13242 number, specify a slightly larger (or smaller, if @var{increment} is negative)
13243 value for @var{last} to ensure that @var{last} is the final value printed
13249 @node File permissions
13250 @chapter File permissions
13253 @include getdate.texi
13257 @node Opening the software toolbox
13258 @chapter Opening the Software Toolbox
13260 An earlier version of this chapter appeared in
13261 @uref{http://www.linuxjournal.com/article.php?sid=2762, the
13262 @cite{What's GNU?} column of @cite{Linux Journal}, 2 (June, 1994)}.
13263 It was written by Arnold Robbins.
13266 * Toolbox introduction:: Toolbox introduction
13267 * I/O redirection:: I/O redirection
13268 * The who command:: The @command{who} command
13269 * The cut command:: The @command{cut} command
13270 * The sort command:: The @command{sort} command
13271 * The uniq command:: The @command{uniq} command
13272 * Putting the tools together:: Putting the tools together
13276 @node Toolbox introduction
13277 @unnumberedsec Toolbox Introduction
13279 This month's column is only peripherally related to the GNU Project, in
13280 that it describes a number of the GNU tools on your GNU/Linux system and how they
13281 might be used. What it's really about is the ``Software Tools'' philosophy
13282 of program development and usage.
13284 The software tools philosophy was an important and integral concept
13285 in the initial design and development of Unix (of which Linux and GNU are
13286 essentially clones). Unfortunately, in the modern day press of
13287 Internetworking and flashy GUIs, it seems to have fallen by the
13288 wayside. This is a shame, since it provides a powerful mental model
13289 for solving many kinds of problems.
13291 Many people carry a Swiss Army knife around in their pants pockets (or
13292 purse). A Swiss Army knife is a handy tool to have: it has several knife
13293 blades, a screwdriver, tweezers, toothpick, nail file, corkscrew, and perhaps
13294 a number of other things on it. For the everyday, small miscellaneous jobs
13295 where you need a simple, general purpose tool, it's just the thing.
13297 On the other hand, an experienced carpenter doesn't build a house using
13298 a Swiss Army knife. Instead, he has a toolbox chock full of specialized
13299 tools---a saw, a hammer, a screwdriver, a plane, and so on. And he knows
13300 exactly when and where to use each tool; you won't catch him hammering nails
13301 with the handle of his screwdriver.
13303 The Unix developers at Bell Labs were all professional programmers and trained
13304 computer scientists. They had found that while a one-size-fits-all program
13305 might appeal to a user because there's only one program to use, in practice
13310 difficult to write,
13313 difficult to maintain and
13317 difficult to extend to meet new situations.
13320 Instead, they felt that programs should be specialized tools. In short, each
13321 program ``should do one thing well.'' No more and no less. Such programs are
13322 simpler to design, write, and get right---they only do one thing.
13324 Furthermore, they found that with the right machinery for hooking programs
13325 together, that the whole was greater than the sum of the parts. By combining
13326 several special purpose programs, you could accomplish a specific task
13327 that none of the programs was designed for, and accomplish it much more
13328 quickly and easily than if you had to write a special purpose program.
13329 We will see some (classic) examples of this further on in the column.
13330 (An important additional point was that, if necessary, take a detour
13331 and build any software tools you may need first, if you don't already
13332 have something appropriate in the toolbox.)
13334 @node I/O redirection
13335 @unnumberedsec I/O Redirection
13337 Hopefully, you are familiar with the basics of I/O redirection in the
13338 shell, in particular the concepts of ``standard input,'' ``standard output,''
13339 and ``standard error''. Briefly, ``standard input'' is a data source, where
13340 data comes from. A program should not need to either know or care if the
13341 data source is a disk file, a keyboard, a magnetic tape, or even a punched
13342 card reader. Similarly, ``standard output'' is a data sink, where data goes
13343 to. The program should neither know nor care where this might be.
13344 Programs that only read their standard input, do something to the data,
13345 and then send it on, are called @dfn{filters}, by analogy to filters in a
13348 With the Unix shell, it's very easy to set up data pipelines:
13351 program_to_create_data | filter1 | ... | filterN > final.pretty.data
13354 We start out by creating the raw data; each filter applies some successive
13355 transformation to the data, until by the time it comes out of the pipeline,
13356 it is in the desired form.
13358 This is fine and good for standard input and standard output. Where does the
13359 standard error come in to play? Well, think about @command{filter1} in
13360 the pipeline above. What happens if it encounters an error in the data it
13361 sees? If it writes an error message to standard output, it will just
13362 disappear down the pipeline into @command{filter2}'s input, and the
13363 user will probably never see it. So programs need a place where they can send
13364 error messages so that the user will notice them. This is standard error,
13365 and it is usually connected to your console or window, even if you have
13366 redirected standard output of your program away from your screen.
13368 For filter programs to work together, the format of the data has to be
13369 agreed upon. The most straightforward and easiest format to use is simply
13370 lines of text. Unix data files are generally just streams of bytes, with
13371 lines delimited by the @acronym{ASCII} @sc{lf} (Line Feed) character,
13372 conventionally called a ``newline'' in the Unix literature. (This is
13373 @code{'\n'} if you're a C programmer.) This is the format used by all
13374 the traditional filtering programs. (Many earlier operating systems
13375 had elaborate facilities and special purpose programs for managing
13376 binary data. Unix has always shied away from such things, under the
13377 philosophy that it's easiest to simply be able to view and edit your
13378 data with a text editor.)
13380 OK, enough introduction. Let's take a look at some of the tools, and then
13381 we'll see how to hook them together in interesting ways. In the following
13382 discussion, we will only present those command line options that interest
13383 us. As you should always do, double check your system documentation
13384 for the full story.
13386 @node The who command
13387 @unnumberedsec The @command{who} Command
13389 The first program is the @command{who} command. By itself, it generates a
13390 list of the users who are currently logged in. Although I'm writing
13391 this on a single-user system, we'll pretend that several people are
13396 @print{} arnold console Jan 22 19:57
13397 @print{} miriam ttyp0 Jan 23 14:19(:0.0)
13398 @print{} bill ttyp1 Jan 21 09:32(:0.0)
13399 @print{} arnold ttyp2 Jan 23 20:48(:0.0)
13402 Here, the @samp{$} is the usual shell prompt, at which I typed @samp{who}.
13403 There are three people logged in, and I am logged in twice. On traditional
13404 Unix systems, user names are never more than eight characters long. This
13405 little bit of trivia will be useful later. The output of @command{who} is nice,
13406 but the data is not all that exciting.
13408 @node The cut command
13409 @unnumberedsec The @command{cut} Command
13411 The next program we'll look at is the @command{cut} command. This program
13412 cuts out columns or fields of input data. For example, we can tell it
13413 to print just the login name and full name from the @file{/etc/passwd}
13414 file. The @file{/etc/passwd} file has seven fields, separated by
13418 arnold:xyzzy:2076:10:Arnold D. Robbins:/home/arnold:/bin/bash
13421 To get the first and fifth fields, we would use @command{cut} like this:
13424 $ cut -d: -f1,5 /etc/passwd
13425 @print{} root:Operator
13427 @print{} arnold:Arnold D. Robbins
13428 @print{} miriam:Miriam A. Robbins
13432 With the @option{-c} option, @command{cut} will cut out specific characters
13433 (i.e., columns) in the input lines. This is useful for input data
13434 that has fixed width fields, and does not have a field separator. For
13435 example, list the Monday dates for the current month:
13437 @c Is using cal ok? Looked at gcal, but I don't like it.
13448 @node The sort command
13449 @unnumberedsec The @command{sort} Command
13451 Next we'll look at the @command{sort} command. This is one of the most
13452 powerful commands on a Unix-style system; one that you will often find
13453 yourself using when setting up fancy data plumbing.
13456 command reads and sorts each file named on the command line. It then
13457 merges the sorted data and writes it to standard output. It will read
13458 standard input if no files are given on the command line (thus
13459 making it into a filter). The sort is based on the character collating
13460 sequence or based on user-supplied ordering criteria.
13463 @node The uniq command
13464 @unnumberedsec The @command{uniq} Command
13466 Finally (at least for now), we'll look at the @command{uniq} program. When
13467 sorting data, you will often end up with duplicate lines, lines that
13468 are identical. Usually, all you need is one instance of each line.
13469 This is where @command{uniq} comes in. The @command{uniq} program reads its
13470 standard input. It prints only one
13471 copy of each repeated line. It does have several options. Later on,
13472 we'll use the @option{-c} option, which prints each unique line, preceded
13473 by a count of the number of times that line occurred in the input.
13476 @node Putting the tools together
13477 @unnumberedsec Putting the Tools Together
13479 Now, let's suppose this is a large ISP server system with dozens of users
13480 logged in. The management wants the system administrator to write a program that will
13481 generate a sorted list of logged in users. Furthermore, even if a user
13482 is logged in multiple times, his or her name should only show up in the
13485 The administrator could sit down with the system documentation and write a C
13486 program that did this. It would take perhaps a couple of hundred lines
13487 of code and about two hours to write it, test it, and debug it.
13488 However, knowing the software toolbox, the administrator can instead start out
13489 by generating just a list of logged on users:
13499 Next, sort the list:
13502 $ who | cut -c1-8 | sort
13509 Finally, run the sorted list through @command{uniq}, to weed out duplicates:
13512 $ who | cut -c1-8 | sort | uniq
13518 The @command{sort} command actually has a @option{-u} option that does what
13519 @command{uniq} does. However, @command{uniq} has other uses for which one
13520 cannot substitute @samp{sort -u}.
13522 The administrator puts this pipeline into a shell script, and makes it available for
13523 all the users on the system (@samp{#} is the system administrator,
13524 or @code{root}, prompt):
13527 # cat > /usr/local/bin/listusers
13528 who | cut -c1-8 | sort | uniq
13530 # chmod +x /usr/local/bin/listusers
13533 There are four major points to note here. First, with just four
13534 programs, on one command line, the administrator was able to save about two
13535 hours worth of work. Furthermore, the shell pipeline is just about as
13536 efficient as the C program would be, and it is much more efficient in
13537 terms of programmer time. People time is much more expensive than
13538 computer time, and in our modern ``there's never enough time to do
13539 everything'' society, saving two hours of programmer time is no mean
13542 Second, it is also important to emphasize that with the
13543 @emph{combination} of the tools, it is possible to do a special
13544 purpose job never imagined by the authors of the individual programs.
13546 Third, it is also valuable to build up your pipeline in stages, as we did here.
13547 This allows you to view the data at each stage in the pipeline, which helps
13548 you acquire the confidence that you are indeed using these tools correctly.
13550 Finally, by bundling the pipeline in a shell script, other users can use
13551 your command, without having to remember the fancy plumbing you set up for
13552 them. In terms of how you run them, shell scripts and compiled programs are
13555 After the previous warm-up exercise, we'll look at two additional, more
13556 complicated pipelines. For them, we need to introduce two more tools.
13558 The first is the @command{tr} command, which stands for ``transliterate.''
13559 The @command{tr} command works on a character-by-character basis, changing
13560 characters. Normally it is used for things like mapping upper case to
13564 $ echo ThIs ExAmPlE HaS MIXED case! | tr '[:upper:]' '[:lower:]'
13565 @print{} this example has mixed case!
13568 There are several options of interest:
13572 work on the complement of the listed characters, i.e.,
13573 operations apply to characters not in the given set
13576 delete characters in the first set from the output
13579 squeeze repeated characters in the output into just one character.
13582 We will be using all three options in a moment.
13584 The other command we'll look at is @command{comm}. The @command{comm}
13585 command takes two sorted input files as input data, and prints out the
13586 files' lines in three columns. The output columns are the data lines
13587 unique to the first file, the data lines unique to the second file, and
13588 the data lines that are common to both. The @option{-1}, @option{-2}, and
13589 @option{-3} command line options @emph{omit} the respective columns. (This is
13590 non-intuitive and takes a little getting used to.) For example:
13612 The file name @file{-} tells @command{comm} to read standard input
13613 instead of a regular file.
13615 Now we're ready to build a fancy pipeline. The first application is a word
13616 frequency counter. This helps an author determine if he or she is over-using
13619 The first step is to change the case of all the letters in our input file
13620 to one case. ``The'' and ``the'' are the same word when doing counting.
13623 $ tr '[:upper:]' '[:lower:]' < whats.gnu | ...
13626 The next step is to get rid of punctuation. Quoted words and unquoted words
13627 should be treated identically; it's easiest to just get the punctuation out of
13631 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | ...
13634 The second @command{tr} command operates on the complement of the listed
13635 characters, which are all the letters, the digits, the underscore, and
13636 the blank. The @samp{\n} represents the newline character; it has to
13637 be left alone. (The @acronym{ASCII} tab character should also be included for
13638 good measure in a production script.)
13640 At this point, we have data consisting of words separated by blank space.
13641 The words only contain alphanumeric characters (and the underscore). The
13642 next step is break the data apart so that we have one word per line. This
13643 makes the counting operation much easier, as we will see shortly.
13646 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
13647 > tr -s ' ' '\n' | ...
13650 This command turns blanks into newlines. The @option{-s} option squeezes
13651 multiple newline characters in the output into just one. This helps us
13652 avoid blank lines. (The @samp{>} is the shell's ``secondary prompt.''
13653 This is what the shell prints when it notices you haven't finished
13654 typing in all of a command.)
13656 We now have data consisting of one word per line, no punctuation, all one
13657 case. We're ready to count each word:
13660 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
13661 > tr -s ' ' '\n' | sort | uniq -c | ...
13664 At this point, the data might look something like this:
13677 The output is sorted by word, not by count! What we want is the most
13678 frequently used words first. Fortunately, this is easy to accomplish,
13679 with the help of two more @command{sort} options:
13683 do a numeric sort, not a textual one
13686 reverse the order of the sort
13689 The final pipeline looks like this:
13692 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
13693 > tr -s ' ' '\n' | sort | uniq -c | sort -n -r
13702 Whew! That's a lot to digest. Yet, the same principles apply. With six
13703 commands, on two lines (really one long one split for convenience), we've
13704 created a program that does something interesting and useful, in much
13705 less time than we could have written a C program to do the same thing.
13707 A minor modification to the above pipeline can give us a simple spelling
13708 checker! To determine if you've spelled a word correctly, all you have to
13709 do is look it up in a dictionary. If it is not there, then chances are
13710 that your spelling is incorrect. So, we need a dictionary.
13711 The conventional location for a dictionary is @file{/usr/dict/words}.
13712 On my GNU/Linux system,@footnote{Redhat Linux 6.1, for the November 2000
13713 revision of this article.}
13714 this is a is a sorted, 45,402 word dictionary.
13716 Now, how to compare our file with the dictionary? As before, we generate
13717 a sorted list of words, one per line:
13720 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
13721 > tr -s ' ' '\n' | sort -u | ...
13724 Now, all we need is a list of words that are @emph{not} in the
13725 dictionary. Here is where the @command{comm} command comes in.
13728 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
13729 > tr -s ' ' '\n' | sort -u |
13730 > comm -23 - /usr/dict/words
13733 The @option{-2} and @option{-3} options eliminate lines that are only in the
13734 dictionary (the second file), and lines that are in both files. Lines
13735 only in the first file (standard input, our stream of words), are
13736 words that are not in the dictionary. These are likely candidates for
13737 spelling errors. This pipeline was the first cut at a production
13738 spelling checker on Unix.
13740 There are some other tools that deserve brief mention.
13744 search files for text that matches a regular expression
13747 count lines, words, characters
13750 a T-fitting for data pipes, copies data to files and to standard output
13753 the stream editor, an advanced tool
13756 a data manipulation language, another advanced tool
13759 The software tools philosophy also espoused the following bit of
13760 advice: ``Let someone else do the hard part.'' This means, take
13761 something that gives you most of what you need, and then massage it the
13762 rest of the way until it's in the form that you want.
13768 Each program should do one thing well. No more, no less.
13771 Combining programs with appropriate plumbing leads to results where
13772 the whole is greater than the sum of the parts. It also leads to novel
13773 uses of programs that the authors might never have imagined.
13776 Programs should never print extraneous header or trailer data, since these
13777 could get sent on down a pipeline. (A point we didn't mention earlier.)
13780 Let someone else do the hard part.
13783 Know your toolbox! Use each program appropriately. If you don't have an
13784 appropriate tool, build one.
13787 As of this writing, all the programs we've discussed are available via
13788 anonymous @command{ftp} from: @*
13789 @uref{ftp://gnudist.gnu.org/textutils/textutils-1.22.tar.gz}. (There may
13790 be more recent versions available now.)
13792 None of what I have presented in this column is new. The Software Tools
13793 philosophy was first introduced in the book @cite{Software Tools}, by
13794 Brian Kernighan and P.J. Plauger (Addison-Wesley, ISBN 0-201-03669-X).
13795 This book showed how to write and use software tools. It was written in
13796 1976, using a preprocessor for FORTRAN named @command{ratfor} (RATional
13797 FORtran). At the time, C was not as ubiquitous as it is now; FORTRAN
13798 was. The last chapter presented a @command{ratfor} to FORTRAN
13799 processor, written in @command{ratfor}. @command{ratfor} looks an awful
13800 lot like C; if you know C, you won't have any problem following the
13803 In 1981, the book was updated and made available as @cite{Software Tools
13804 in Pascal} (Addison-Wesley, ISBN 0-201-10342-7). Both books are
13805 still in print and are well worth
13806 reading if you're a programmer. They certainly made a major change in
13807 how I view programming.
13809 The programs in both books are available from
13810 @uref{http://cm.bell-labs.com/who/bwk, Brian Kernighan's home page}.
13811 For a number of years, there was an active
13812 Software Tools Users Group, whose members had ported the original
13813 @command{ratfor} programs to essentially every computer system with a
13814 FORTRAN compiler. The popularity of the group waned in the middle 1980s
13815 as Unix began to spread beyond universities.
13817 With the current proliferation of GNU code and other clones of Unix programs,
13818 these programs now receive little attention; modern C versions are
13819 much more efficient and do more than these programs do. Nevertheless, as
13820 exposition of good programming style, and evangelism for a still-valuable
13821 philosophy, these books are unparalleled, and I recommend them highly.
13823 Acknowledgment: I would like to express my gratitude to Brian Kernighan
13824 of Bell Labs, the original Software Toolsmith, for reviewing this column.
13826 @include doclicense.texi
13837 @c Local variables:
13838 @c texinfo-column-for-description: 32