3 @setfilename coreutils.info
5 @settitle GNU Coreutils @value{VERSION}
6 @documentencoding UTF-8
7 @set txicodequoteundirected
8 @set txicodequotebacktick
13 @include constants.texi
15 @c Define new indices.
19 @c Put everything in one index (arbitrarily chosen to be the concept index).
29 * Coreutils: (coreutils). Core GNU (file, text, shell) utilities.
30 * Common options: (coreutils)Common options.
31 * File permissions: (coreutils)File permissions. Access modes.
32 * Date input formats: (coreutils)Date input formats.
35 @c FIXME: the following need documentation
36 @c * [: (coreutils)[ invocation. File/string tests.
37 @c * pinky: (coreutils)pinky invocation. FIXME.
39 @dircategory Individual utilities
41 * arch: (coreutils)arch invocation. Print machine hardware name.
42 * b2sum: (coreutils)b2sum invocation. Print or check BLAKE2 digests.
43 * base32: (coreutils)base32 invocation. Base32 encode/decode data.
44 * base64: (coreutils)base64 invocation. Base64 encode/decode data.
45 * basename: (coreutils)basename invocation. Strip directory and suffix.
46 * basenc: (coreutils)basenc invocation. Encoding/decoding of data.
47 * cat: (coreutils)cat invocation. Concatenate and write files.
48 * chcon: (coreutils)chcon invocation. Change SELinux CTX of files.
49 * chgrp: (coreutils)chgrp invocation. Change file groups.
50 * chmod: (coreutils)chmod invocation. Change access permissions.
51 * chown: (coreutils)chown invocation. Change file owners and groups.
52 * chroot: (coreutils)chroot invocation. Specify the root directory.
53 * cksum: (coreutils)cksum invocation. Print POSIX CRC checksum.
54 * comm: (coreutils)comm invocation. Compare sorted files by line.
55 * cp: (coreutils)cp invocation. Copy files.
56 * csplit: (coreutils)csplit invocation. Split by context.
57 * cut: (coreutils)cut invocation. Print selected parts of lines.
58 * date: (coreutils)date invocation. Print/set system date and time.
59 * dd: (coreutils)dd invocation. Copy and convert a file.
60 * df: (coreutils)df invocation. Report file system usage.
61 * dir: (coreutils)dir invocation. List directories briefly.
62 * dircolors: (coreutils)dircolors invocation. Color setup for ls.
63 * dirname: (coreutils)dirname invocation. Strip last file name component.
64 * du: (coreutils)du invocation. Report file usage.
65 * echo: (coreutils)echo invocation. Print a line of text.
66 * env: (coreutils)env invocation. Modify the environment.
67 * expand: (coreutils)expand invocation. Convert tabs to spaces.
68 * expr: (coreutils)expr invocation. Evaluate expressions.
69 * factor: (coreutils)factor invocation. Print prime factors
70 * false: (coreutils)false invocation. Do nothing, unsuccessfully.
71 * fmt: (coreutils)fmt invocation. Reformat paragraph text.
72 * fold: (coreutils)fold invocation. Wrap long input lines.
73 * groups: (coreutils)groups invocation. Print group names a user is in.
74 * head: (coreutils)head invocation. Output the first part of files.
75 * hostid: (coreutils)hostid invocation. Print numeric host identifier.
76 * hostname: (coreutils)hostname invocation. Print or set system name.
77 * id: (coreutils)id invocation. Print user identity.
78 * install: (coreutils)install invocation. Copy files and set attributes.
79 * join: (coreutils)join invocation. Join lines on a common field.
80 * kill: (coreutils)kill invocation. Send a signal to processes.
81 * link: (coreutils)link invocation. Make hard links between files.
82 * ln: (coreutils)ln invocation. Make links between files.
83 * logname: (coreutils)logname invocation. Print current login name.
84 * ls: (coreutils)ls invocation. List directory contents.
85 * md5sum: (coreutils)md5sum invocation. Print or check MD5 digests.
86 * mkdir: (coreutils)mkdir invocation. Create directories.
87 * mkfifo: (coreutils)mkfifo invocation. Create FIFOs (named pipes).
88 * mknod: (coreutils)mknod invocation. Create special files.
89 * mktemp: (coreutils)mktemp invocation. Create temporary files.
90 * mv: (coreutils)mv invocation. Rename files.
91 * nice: (coreutils)nice invocation. Modify niceness.
92 * nl: (coreutils)nl invocation. Number lines and write files.
93 * nohup: (coreutils)nohup invocation. Immunize to hangups.
94 * nproc: (coreutils)nproc invocation. Print the number of processors.
95 * numfmt: (coreutils)numfmt invocation. Reformat numbers.
96 * od: (coreutils)od invocation. Dump files in octal, etc.
97 * paste: (coreutils)paste invocation. Merge lines of files.
98 * pathchk: (coreutils)pathchk invocation. Check file name portability.
99 * pr: (coreutils)pr invocation. Paginate or columnate files.
100 * printenv: (coreutils)printenv invocation. Print environment variables.
101 * printf: (coreutils)printf invocation. Format and print data.
102 * ptx: (coreutils)ptx invocation. Produce permuted indexes.
103 * pwd: (coreutils)pwd invocation. Print working directory.
104 * readlink: (coreutils)readlink invocation. Print referent of a symlink.
105 * realpath: (coreutils)realpath invocation. Print resolved file names.
106 * rm: (coreutils)rm invocation. Remove files.
107 * rmdir: (coreutils)rmdir invocation. Remove empty directories.
108 * runcon: (coreutils)runcon invocation. Run in specified SELinux CTX.
109 * seq: (coreutils)seq invocation. Print numeric sequences
110 * sha1sum: (coreutils)sha1sum invocation. Print or check SHA-1 digests.
111 * sha2: (coreutils)sha2 utilities. Print or check SHA-2 digests.
112 * shred: (coreutils)shred invocation. Remove files more securely.
113 * shuf: (coreutils)shuf invocation. Shuffling text files.
114 * sleep: (coreutils)sleep invocation. Delay for a specified time.
115 * sort: (coreutils)sort invocation. Sort text files.
116 * split: (coreutils)split invocation. Split into pieces.
117 * stat: (coreutils)stat invocation. Report file(system) status.
118 * stdbuf: (coreutils)stdbuf invocation. Modify stdio buffering.
119 * stty: (coreutils)stty invocation. Print/change terminal settings.
120 * sum: (coreutils)sum invocation. Print traditional checksum.
121 * sync: (coreutils)sync invocation. Sync files to stable storage.
122 * tac: (coreutils)tac invocation. Reverse files.
123 * tail: (coreutils)tail invocation. Output the last part of files.
124 * tee: (coreutils)tee invocation. Redirect to multiple files.
125 * test: (coreutils)test invocation. File/string tests.
126 * timeout: (coreutils)timeout invocation. Run with time limit.
127 * touch: (coreutils)touch invocation. Change file timestamps.
128 * tr: (coreutils)tr invocation. Translate characters.
129 * true: (coreutils)true invocation. Do nothing, successfully.
130 * truncate: (coreutils)truncate invocation. Shrink/extend size of a file.
131 * tsort: (coreutils)tsort invocation. Topological sort.
132 * tty: (coreutils)tty invocation. Print terminal name.
133 * uname: (coreutils)uname invocation. Print system information.
134 * unexpand: (coreutils)unexpand invocation. Convert spaces to tabs.
135 * uniq: (coreutils)uniq invocation. Uniquify files.
136 * unlink: (coreutils)unlink invocation. Removal via unlink(2).
137 * uptime: (coreutils)uptime invocation. Print uptime and load.
138 * users: (coreutils)users invocation. Print current user names.
139 * vdir: (coreutils)vdir invocation. List directories verbosely.
140 * wc: (coreutils)wc invocation. Line, word, and byte counts.
141 * who: (coreutils)who invocation. Print who is logged in.
142 * whoami: (coreutils)whoami invocation. Print effective user ID.
143 * yes: (coreutils)yes invocation. Print a string indefinitely.
147 This manual documents version @value{VERSION} of the GNU core
148 utilities, including the standard programs for text and file manipulation.
150 Copyright @copyright{} 1994--2022 Free Software Foundation, Inc.
153 Permission is granted to copy, distribute and/or modify this document
154 under the terms of the GNU Free Documentation License, Version 1.3 or
155 any later version published by the Free Software Foundation; with no
156 Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
157 Texts. A copy of the license is included in the section entitled ``GNU
158 Free Documentation License''.
163 @title GNU @code{Coreutils}
164 @subtitle Core GNU utilities
165 @subtitle for version @value{VERSION}, @value{UPDATED}
166 @author David MacKenzie et al.
169 @vskip 0pt plus 1filll
182 @cindex core utilities
183 @cindex text utilities
184 @cindex shell utilities
185 @cindex file utilities
188 * Introduction:: Caveats, overview, and authors
189 * Common options:: Common options
190 * Output of entire files:: cat tac nl od base32 base64 basenc
191 * Formatting file contents:: fmt pr fold
192 * Output of parts of files:: head tail split csplit
193 * Summarizing files:: wc sum cksum b2sum md5sum sha1sum sha2
194 * Operating on sorted files:: sort shuf uniq comm ptx tsort
195 * Operating on fields:: cut paste join
196 * Operating on characters:: tr expand unexpand
197 * Directory listing:: ls dir vdir dircolors
198 * Basic operations:: cp dd install mv rm shred
199 * Special file types:: mkdir rmdir unlink mkfifo mknod ln link readlink
200 * Changing file attributes:: chgrp chmod chown touch
201 * File space usage:: df du stat sync truncate
202 * Printing text:: echo printf yes
203 * Conditions:: false true test expr
205 * File name manipulation:: dirname basename pathchk mktemp realpath
206 * Working context:: pwd stty printenv tty
207 * User information:: id logname whoami groups users who
208 * System context:: date arch nproc uname hostname hostid uptime
209 * SELinux context:: chcon runcon
210 * Modified command invocation:: chroot env nice nohup stdbuf timeout
211 * Process control:: kill
213 * Numeric operations:: factor numfmt seq
214 * File permissions:: Access modes
215 * File timestamps:: File timestamp issues
216 * Date input formats:: Specifying date strings
217 * Version sort ordering:: Details on version-sort algorithm
218 * Opening the software toolbox:: The software tools philosophy
219 * GNU Free Documentation License:: Copying and sharing this manual
220 * Concept index:: General index
223 --- The Detailed Node Listing ---
227 * Exit status:: Indicating program success or failure
228 * Backup options:: Backup options
229 * Block size:: Block size
230 * Floating point:: Floating point number representation
231 * Signal specifications:: Specifying signals
232 * Disambiguating names and IDs:: chgrp, chown, chroot, id: user and group syntax
233 * Random sources:: Sources of random data
234 * Target directory:: Target directory
235 * Trailing slashes:: Trailing slashes
236 * Traversing symlinks:: Traversing symlinks to directories
237 * Treating / specially:: Treating / specially
238 * Standards conformance:: Standards conformance
239 * Multi-call invocation:: Multi-call program invocation
241 Output of entire files
243 * cat invocation:: Concatenate and write files
244 * tac invocation:: Concatenate and write files in reverse
245 * nl invocation:: Number lines and write files
246 * od invocation:: Write files in octal or other formats
247 * base32 invocation:: Transform data into printable data
248 * base64 invocation:: Transform data into printable data
249 * basenc invocation:: Transform data into printable data
251 Formatting file contents
253 * fmt invocation:: Reformat paragraph text
254 * pr invocation:: Paginate or columnate files for printing
255 * fold invocation:: Wrap input lines to fit in specified width
257 Output of parts of files
259 * head invocation:: Output the first part of files
260 * tail invocation:: Output the last part of files
261 * split invocation:: Split a file into fixed-size pieces
262 * csplit invocation:: Split a file into context-determined pieces
266 * wc invocation:: Print newline, word, and byte counts
267 * sum invocation:: Print checksum and block counts
268 * cksum invocation:: Print CRC checksum and byte counts
269 * b2sum invocation:: Print or check BLAKE2 digests
270 * md5sum invocation:: Print or check MD5 digests
271 * sha1sum invocation:: Print or check SHA-1 digests
272 * sha2 utilities:: Print or check SHA-2 digests
274 Operating on sorted files
276 * sort invocation:: Sort text files
277 * shuf invocation:: Shuffle text files
278 * uniq invocation:: Uniquify files
279 * comm invocation:: Compare two sorted files line by line
280 * ptx invocation:: Produce a permuted index of file contents
281 * tsort invocation:: Topological sort
283 @command{ptx}: Produce permuted indexes
285 * General options in ptx:: Options which affect general program behavior
286 * Charset selection in ptx:: Underlying character set considerations
287 * Input processing in ptx:: Input fields, contexts, and keyword selection
288 * Output formatting in ptx:: Types of output format, and sizing the fields
289 * Compatibility in ptx:: The GNU extensions to @command{ptx}
293 * cut invocation:: Print selected parts of lines
294 * paste invocation:: Merge lines of files
295 * join invocation:: Join lines on a common field
297 Operating on characters
299 * tr invocation:: Translate, squeeze, and/or delete characters
300 * expand invocation:: Convert tabs to spaces
301 * unexpand invocation:: Convert spaces to tabs
303 @command{tr}: Translate, squeeze, and/or delete characters
305 * Character arrays:: Specifying arrays of characters
306 * Translating:: Changing one set of characters to another
307 * Squeezing and deleting:: Removing characters
311 * ls invocation:: List directory contents
312 * dir invocation:: Briefly list directory contents
313 * vdir invocation:: Verbosely list directory contents
314 * dircolors invocation:: Color setup for @command{ls}
316 @command{ls}: List directory contents
318 * Which files are listed:: Which files are listed
319 * What information is listed:: What information is listed
320 * Sorting the output:: Sorting the output
321 * General output formatting:: General output formatting
322 * Formatting the file names:: Formatting the file names
326 * cp invocation:: Copy files and directories
327 * dd invocation:: Convert and copy a file
328 * install invocation:: Copy files and set attributes
329 * mv invocation:: Move (rename) files
330 * rm invocation:: Remove files or directories
331 * shred invocation:: Remove files more securely
335 * link invocation:: Make a hard link via the link syscall
336 * ln invocation:: Make links between files
337 * mkdir invocation:: Make directories
338 * mkfifo invocation:: Make FIFOs (named pipes)
339 * mknod invocation:: Make block or character special files
340 * readlink invocation:: Print value of a symlink or canonical file name
341 * rmdir invocation:: Remove empty directories
342 * unlink invocation:: Remove files via unlink syscall
344 Changing file attributes
346 * chown invocation:: Change file owner and group
347 * chgrp invocation:: Change group ownership
348 * chmod invocation:: Change access permissions
349 * touch invocation:: Change file timestamps
353 * df invocation:: Report file system space usage
354 * du invocation:: Estimate file space usage
355 * stat invocation:: Report file or file system status
356 * sync invocation:: Synchronize cached writes to persistent storage
357 * truncate invocation:: Shrink or extend the size of a file
361 * echo invocation:: Print a line of text
362 * printf invocation:: Format and print data
363 * yes invocation:: Print a string until interrupted
367 * false invocation:: Do nothing, unsuccessfully
368 * true invocation:: Do nothing, successfully
369 * test invocation:: Check file types and compare values
370 * expr invocation:: Evaluate expressions
372 @command{test}: Check file types and compare values
374 * File type tests:: File type tests
375 * Access permission tests:: Access permission tests
376 * File characteristic tests:: File characteristic tests
377 * String tests:: String tests
378 * Numeric tests:: Numeric tests
380 @command{expr}: Evaluate expression
382 * String expressions:: + : match substr index length
383 * Numeric expressions:: + - * / %
384 * Relations for expr:: | & < <= = == != >= >
385 * Examples of expr:: Examples of using @command{expr}
389 * tee invocation:: Redirect output to multiple files or processes
391 File name manipulation
393 * basename invocation:: Strip directory and suffix from a file name
394 * dirname invocation:: Strip last file name component
395 * pathchk invocation:: Check file name validity and portability
396 * mktemp invocation:: Create temporary file or directory
397 * realpath invocation:: Print resolved file names
401 * pwd invocation:: Print working directory
402 * stty invocation:: Print or change terminal characteristics
403 * printenv invocation:: Print all or some environment variables
404 * tty invocation:: Print file name of terminal on standard input
406 @command{stty}: Print or change terminal characteristics
408 * Control:: Control settings
409 * Input:: Input settings
410 * Output:: Output settings
411 * Local:: Local settings
412 * Combination:: Combination settings
413 * Characters:: Special characters
414 * Special:: Special settings
418 * id invocation:: Print user identity
419 * logname invocation:: Print current login name
420 * whoami invocation:: Print effective user ID
421 * groups invocation:: Print group names a user is in
422 * users invocation:: Print login names of users currently logged in
423 * who invocation:: Print who is currently logged in
427 * arch invocation:: Print machine hardware name
428 * date invocation:: Print or set system date and time
429 * nproc invocation:: Print the number of processors
430 * uname invocation:: Print system information
431 * hostname invocation:: Print or set system name
432 * hostid invocation:: Print numeric host identifier
433 * uptime invocation:: Print system uptime and load
435 @command{date}: Print or set system date and time
437 * Time conversion specifiers:: %[HIklMNpPrRsSTXzZ]
438 * Date conversion specifiers:: %[aAbBcCdDeFgGhjmuUVwWxyY]
439 * Literal conversion specifiers:: %[%nt]
440 * Padding and other flags:: Pad with zeros, spaces, etc.
441 * Setting the time:: Changing the system clock
442 * Options for date:: Instead of the current time
443 * Date input formats:: Specifying date strings
444 * Examples of date:: Examples
448 * chcon invocation:: Change SELinux context of file
449 * runcon invocation:: Run a command in specified SELinux context
451 Modified command invocation
453 * chroot invocation:: Run a command with a different root directory
454 * env invocation:: Run a command in a modified environment
455 * nice invocation:: Run a command with modified niceness
456 * nohup invocation:: Run a command immune to hangups
457 * stdbuf invocation:: Run a command with modified I/O buffering
458 * timeout invocation:: Run a command with a time limit
462 * kill invocation:: Sending a signal to processes.
466 * sleep invocation:: Delay for a specified time
470 * factor invocation:: Print prime factors
471 * numfmt invocation:: Reformat numbers
472 * seq invocation:: Print numeric sequences
477 * File timestamps:: File timestamp issues
481 * Mode Structure:: Structure of file mode bits
482 * Symbolic Modes:: Mnemonic representation of file mode bits
483 * Numeric Modes:: File mode bits as octal numbers
484 * Directory Setuid and Setgid:: Set-user-ID and set-group-ID on directories
488 * General date syntax:: Common rules
489 * Calendar date items:: 21 Jul 2020
490 * Time of day items:: 9:20pm
491 * Time zone items:: UTC, -0700, +0900, @dots{}
492 * Combined date and time of day items:: 2020-07-21T20:02:00,000000-0400
493 * Day of week items:: Monday and others
494 * Relative items in date strings:: next tuesday, 2 years ago
495 * Pure numbers in date strings:: 20200721, 1440
496 * Seconds since the Epoch:: @@1595289600
497 * Specifying time zone rules:: TZ="America/New_York", TZ="UTC0"
498 * Authors of parse_datetime:: Bellovin, Eggert, Salz, Berets, et al.
500 Version sorting order
502 * Version sort overview::
503 * Version sort implementation::
504 * Differences from Debian version sort::
505 * Advanced version sort topics::
507 Opening the software toolbox
509 * Toolbox introduction:: Toolbox introduction
510 * I/O redirection:: I/O redirection
511 * The who command:: The @command{who} command
512 * The cut command:: The @command{cut} command
513 * The sort command:: The @command{sort} command
514 * The uniq command:: The @command{uniq} command
515 * Putting the tools together:: Putting the tools together
519 * GNU Free Documentation License:: Copying and sharing this manual
526 @chapter Introduction
528 This manual is a work in progress: many sections make no attempt to explain
529 basic concepts in a way suitable for novices. Thus, if you are interested,
530 please get involved in improving this manual. The entire GNU community
534 The GNU utilities documented here are mostly compatible with the
536 @cindex bugs, reporting
538 Please report bugs to @email{bug-coreutils@@gnu.org}.
539 Include the version number, machine architecture, input files, and
540 any other information needed to reproduce the bug: your input, what you
541 expected, what you got, and why it is wrong.
543 If you have a problem with @command{sort} or @command{date}, try using the
544 @option{--debug} option, as it can often help find and fix problems without
545 having to wait for an answer to a bug report. If the debug output
546 does not suffice to fix the problem on your own, please compress and
547 attach it to the rest of your bug report.
549 Although diffs are welcome,
550 please include a description of the problem as well, since this is
551 sometimes difficult to infer. @xref{Bugs, , , gcc, Using and Porting GNU CC}.
557 @cindex MacKenzie, D.
560 This manual was originally derived from the Unix man pages in the
561 distributions, which were written by David MacKenzie and updated by Jim
562 Meyering. What you are reading now is the authoritative documentation
563 for these utilities; the man pages are no longer being maintained. The
564 original @command{fmt} man page was written by Ross Paterson. Fran@,{c}ois
565 Pinard did the initial conversion to Texinfo format. Karl Berry did the
566 indexing, some reorganization, and editing of the results. Brian
567 Youmans of the Free Software Foundation office staff combined the
568 manuals for textutils, fileutils, and sh-utils to produce the present
569 omnibus manual. Richard Stallman contributed his usual invaluable
570 insights to the overall process.
573 @chapter Common options
577 @itemx --backup[=@var{method}]
580 @vindex VERSION_CONTROL
581 @cindex backups, making
582 @xref{Backup options}.
583 Make a backup of each file that would otherwise be overwritten or removed.
586 @macro optBackupSuffix
587 @item -S @var{suffix}
588 @itemx --suffix=@var{suffix}
591 Append @var{suffix} to each backup file made with @option{-b}.
592 @xref{Backup options}.
595 @macro optTargetDirectory
596 @item -t @var{directory}
597 @itemx --target-directory=@var{directory}
599 @opindex --target-directory
600 @cindex target directory
601 @cindex destination directory
602 Specify the destination @var{directory}.
603 @xref{Target directory}.
606 @macro optNoTargetDirectory
608 @itemx --no-target-directory
610 @opindex --no-target-directory
611 @cindex target directory
612 @cindex destination directory
613 Do not treat the last operand specially when it is a directory or a
614 symbolic link to a directory. @xref{Target directory}.
618 @cindex output NUL-byte-terminated lines
619 Output a zero byte (ASCII NUL) at the end of each line,
620 rather than a newline. This option enables other programs to parse the
621 output even when that output would contain data with embedded newlines.
640 @macro optZeroTerminated
642 @itemx --zero-terminated
644 @opindex --zero-terminated
645 @cindex process zero-terminated items
646 Delimit items with a zero byte rather than a newline (ASCII LF).
647 I.e., treat input as items separated by ASCII NUL
648 and terminate output items with ASCII NUL.
649 This option can be useful in conjunction with @samp{perl -0} or
650 @samp{find -print0} and @samp{xargs -0} which do the same in order to
651 reliably handle arbitrary file names (even those containing blanks
652 or other special characters).
659 Append an SI-style abbreviation to each size, such as @samp{M} for
660 megabytes. Powers of 1000 are used, not 1024; @samp{M} stands for
661 1,000,000 bytes. This option is equivalent to
662 @option{--block-size=si}. Use the @option{-h} or
663 @option{--human-readable} option if
664 you prefer powers of 1024.
667 @macro optHumanReadable
669 @itemx --human-readable
671 @opindex --human-readable
672 @cindex human-readable output
673 Append a size letter to each size, such as @samp{M} for mebibytes.
674 Powers of 1024 are used, not 1000; @samp{M} stands for 1,048,576 bytes.
675 This option is equivalent to @option{--block-size=human-readable}.
676 Use the @option{--si} option if you prefer powers of 1000.
679 @macro optStripTrailingSlashes
680 @item --strip-trailing-slashes
681 @opindex --strip-trailing-slashes
682 @cindex stripping trailing slashes
683 Remove any trailing slashes from each @var{source} argument.
684 @xref{Trailing slashes}.
687 @macro mayConflictWithShellBuiltIn{cmd}
688 @cindex conflicts with shell built-ins
689 @cindex built-in shell commands, conflicts with
690 Due to shell aliases and built-in @command{\cmd\} functions, using an
691 unadorned @command{\cmd\} interactively or in a script may get you
692 different functionality than that described here. Invoke it via
693 @command{env} (i.e., @code{env \cmd\ @dots{}}) to avoid interference
698 @macro multiplierSuffixes{varName}
699 @var{\varName\} may be, or may be an integer optionally followed by,
700 one of the following multiplicative suffixes:
702 @samp{b} => 512 ("blocks")
703 @samp{KB} => 1000 (KiloBytes)
704 @samp{K} => 1024 (KibiBytes)
705 @samp{MB} => 1000*1000 (MegaBytes)
706 @samp{M} => 1024*1024 (MebiBytes)
707 @samp{GB} => 1000*1000*1000 (GigaBytes)
708 @samp{G} => 1024*1024*1024 (GibiBytes)
710 and so on for @samp{T}, @samp{P}, @samp{E}, @samp{Z}, and @samp{Y}.
711 Binary prefixes can be used, too: @samp{KiB}=@samp{K}, @samp{MiB}=@samp{M},
715 @c FIXME: same as above, but no ``blocks'' line.
716 @macro multiplierSuffixesNoBlocks{varName}
717 @var{\varName\} may be, or may be an integer optionally followed by,
718 one of the following multiplicative suffixes:
720 @samp{KB} => 1000 (KiloBytes)
721 @samp{K} => 1024 (KibiBytes)
722 @samp{MB} => 1000*1000 (MegaBytes)
723 @samp{M} => 1024*1024 (MebiBytes)
724 @samp{GB} => 1000*1000*1000 (GigaBytes)
725 @samp{G} => 1024*1024*1024 (GibiBytes)
727 and so on for @samp{T}, @samp{P}, @samp{E}, @samp{Z}, and @samp{Y}.
728 Binary prefixes can be used, too: @samp{KiB}=@samp{K}, @samp{MiB}=@samp{M},
732 @cindex common options
734 Certain options are available in all of these programs. Rather than
735 writing identical descriptions for each of the programs, they are
736 described here. (In fact, every GNU program accepts (or should accept)
739 @vindex POSIXLY_CORRECT
740 Normally options and operands can appear in any order, and programs act
741 as if all the options appear before any operands. For example,
742 @samp{sort -r passwd -t :} acts like @samp{sort -r -t : passwd}, since
743 @samp{:} is an option-argument of @option{-t}. However, if the
744 @env{POSIXLY_CORRECT} environment variable is set, options must appear
745 before operands, unless otherwise specified for a particular command.
747 A few programs can usefully have trailing operands with leading
748 @samp{-}. With such a program, options must precede operands even if
749 @env{POSIXLY_CORRECT} is not set, and this fact is noted in the
750 program description. For example, the @command{env} command's options
751 must appear before its operands, since in some cases the operands
752 specify a command that itself contains options.
754 Most programs that accept long options recognize unambiguous
755 abbreviations of those options. For example, @samp{rmdir
756 --ignore-fail-on-non-empty} can be invoked as @samp{rmdir
757 --ignore-fail} or even @samp{rmdir --i}. Ambiguous options, such as
758 @samp{ls --h}, are identified as such.
760 Some of these programs recognize the @option{--help} and @option{--version}
761 options only when one of them is the sole command line argument. For
762 these programs, abbreviations of the long options are not always recognized.
769 Print a usage message listing all available options, then exit successfully.
773 @cindex version number, finding
774 Print the version number, then exit successfully.
778 @cindex option delimiter
779 Delimit the option list. Later arguments, if any, are treated as
780 operands even if they begin with @samp{-}. For example, @samp{sort --
781 -r} reads from the file named @file{-r}.
785 @cindex standard input
786 @cindex standard output
787 A single @samp{-} operand is not really an option, though it looks like one. It
788 stands for a file operand, and some tools treat it as standard input, or as
789 standard output if that is clear from the context. For example, @samp{sort -}
790 reads from standard input, and is equivalent to plain @samp{sort}. Unless
791 otherwise specified, a @samp{-} can appear as any operand that requires a file
795 * Exit status:: Indicating program success or failure.
796 * Backup options:: -b -S, in some programs.
797 * Block size:: BLOCK_SIZE and --block-size, in some programs.
798 * Floating point:: Floating point number representation.
799 * Signal specifications:: Specifying signals using the --signal option.
800 * Disambiguating names and IDs:: chgrp, chown, chroot, id: user and group syntax
801 * Random sources:: --random-source, in some programs.
802 * Target directory:: Specifying a target directory, in some programs.
803 * Trailing slashes:: --strip-trailing-slashes, in some programs.
804 * Traversing symlinks:: -H, -L, or -P, in some programs.
805 * Treating / specially:: --preserve-root and --no-preserve-root.
806 * Special built-in utilities:: @command{break}, @command{:}, @dots{}
807 * Standards conformance:: Conformance to the POSIX standard.
808 * Multi-call invocation:: Multi-call program invocation.
816 An exit status of zero indicates success,
817 and a nonzero value indicates failure.
820 Nearly every command invocation yields an integral @dfn{exit status}
821 that can be used to change how other commands work.
822 For the vast majority of commands, an exit status of zero indicates
823 success. Failure is indicated by a nonzero value---typically
824 @samp{1}, though it may differ on unusual platforms as POSIX
825 requires only that it be nonzero.
827 However, some of the programs documented here do produce
828 other exit status values and a few associate different
829 meanings with the values @samp{0} and @samp{1}.
830 Here are some of the exceptions:
831 @command{chroot}, @command{env}, @command{expr}, @command{nice},
832 @command{nohup}, @command{numfmt}, @command{printenv}, @command{sort},
833 @command{stdbuf}, @command{test}, @command{timeout}, @command{tty}.
837 @section Backup options
839 @cindex backup options
841 Some GNU programs (at least @command{cp}, @command{install},
842 @command{ln}, and @command{mv}) optionally make backups of files
843 before writing new versions.
844 These options control the details of these backups. The options are also
845 briefly mentioned in the descriptions of the particular programs.
850 @itemx --backup[=@var{method}]
853 @vindex VERSION_CONTROL
854 @cindex backups, making
855 Make a backup of each file that would otherwise be overwritten or removed.
856 Without this option, the original versions are destroyed.
857 Use @var{method} to determine the type of backups to make.
858 When this option is used but @var{method} is not specified,
859 then the value of the @env{VERSION_CONTROL}
860 environment variable is used. And if @env{VERSION_CONTROL} is not set,
861 the default backup type is @samp{existing}.
863 Note that the short form of this option, @option{-b} does not accept any
864 argument. Using @option{-b} is equivalent to using @option{--backup=existing}.
866 @vindex version-control @r{Emacs variable}
867 This option corresponds to the Emacs variable @samp{version-control};
868 the values for @var{method} are the same as those used in Emacs.
869 This option also accepts more descriptive names.
870 The valid @var{method}s are (unique abbreviations are accepted):
875 @opindex none @r{backup method}
880 @opindex numbered @r{backup method}
881 Always make numbered backups.
885 @opindex existing @r{backup method}
886 Make numbered backups of files that already have them, simple backups
891 @opindex simple @r{backup method}
892 Always make simple backups. Please note @samp{never} is not to be
893 confused with @samp{none}.
897 @item -S @var{suffix}
898 @itemx --suffix=@var{suffix}
901 @cindex backup suffix
902 @vindex SIMPLE_BACKUP_SUFFIX
903 Append @var{suffix} to each backup file made with @option{-b}. If this
904 option is not specified, the value of the @env{SIMPLE_BACKUP_SUFFIX}
905 environment variable is used. And if @env{SIMPLE_BACKUP_SUFFIX} is not
906 set, the default is @samp{~}, just as in Emacs.
915 Some GNU programs (at least @command{df}, @command{du}, and
916 @command{ls}) display sizes in ``blocks''. You can adjust the block size
917 and method of display to make sizes easier to read. The block size
918 used for display is independent of any file system block size.
919 Fractional block counts are rounded up to the nearest integer.
921 @opindex --block-size=@var{size}
924 @vindex DF_BLOCK_SIZE
925 @vindex DU_BLOCK_SIZE
926 @vindex LS_BLOCK_SIZE
927 @vindex POSIXLY_CORRECT@r{, and block size}
929 The default block size is chosen by examining the following environment
930 variables in turn; the first one that is set determines the block size.
935 This specifies the default block size for the @command{df} command.
936 Similarly, @env{DU_BLOCK_SIZE} specifies the default for @command{du} and
937 @env{LS_BLOCK_SIZE} for @command{ls}.
940 This specifies the default block size for all three commands, if the
941 above command-specific environment variables are not set.
944 This specifies the default block size for all values that are normally
945 printed as blocks, if neither @env{BLOCK_SIZE} nor the above
946 command-specific environment variables are set. Unlike the other
947 environment variables, @env{BLOCKSIZE} does not affect values that are
948 normally printed as byte counts, e.g., the file sizes contained in
951 @item POSIXLY_CORRECT
952 If neither @env{@var{command}_BLOCK_SIZE}, nor @env{BLOCK_SIZE}, nor
953 @env{BLOCKSIZE} is set, but this variable is set, the block size
958 If none of the above environment variables are set, the block size
959 currently defaults to 1024 bytes in most contexts, but this number may
960 change in the future. For @command{ls} file sizes, the block size
963 @cindex human-readable output
966 A block size specification can be a positive integer specifying the number
967 of bytes per block, or it can be @code{human-readable} or @code{si} to
968 select a human-readable format. Integers may be followed by suffixes
969 that are upward compatible with the
970 @uref{http://www.bipm.org/en/publications/si-brochure/chapter3.html,
972 for decimal multiples and with the
973 @uref{https://physics.nist.gov/cuu/Units/binary.html, ISO/IEC 80000-13
974 (formerly IEC 60027-2) prefixes} for binary multiples.
976 With human-readable formats, output sizes are followed by a size letter
977 such as @samp{M} for megabytes. @code{BLOCK_SIZE=human-readable} uses
978 powers of 1024; @samp{M} stands for 1,048,576 bytes.
979 @code{BLOCK_SIZE=si} is similar, but uses powers of 1000 and appends
980 @samp{B}; @samp{MB} stands for 1,000,000 bytes.
983 A block size specification preceded by @samp{'} causes output sizes to
984 be displayed with thousands separators. The @env{LC_NUMERIC} locale
985 specifies the thousands separator and grouping. For example, in an
986 American English locale, @samp{--block-size="'1kB"} would cause a size
987 of 1234000 bytes to be displayed as @samp{1,234}. In the default C
988 locale, there is no thousands separator so a leading @samp{'} has no
991 An integer block size can be followed by a suffix to specify a
992 multiple of that size. A bare size letter,
993 or one followed by @samp{iB}, specifies
994 a multiple using powers of 1024. A size letter followed by @samp{B}
995 specifies powers of 1000 instead. For example, @samp{1M} and
996 @samp{1MiB} are equivalent to @samp{1048576}, whereas @samp{1MB} is
997 equivalent to @samp{1000000}.
999 A plain suffix without a preceding integer acts as if @samp{1} were
1000 prepended, except that it causes a size indication to be appended to
1001 the output. For example, @samp{--block-size="kB"} displays 3000 as
1004 The following suffixes are defined. Large sizes like @code{1Y}
1005 may be rejected by your computer due to limitations of its arithmetic.
1009 @cindex kilobyte, definition of
1010 kilobyte: @math{10^3 = 1000}.
1014 @cindex kibibyte, definition of
1015 kibibyte: @math{2^{10} = 1024}. @samp{K} is special: the SI prefix is
1016 @samp{k} and the ISO/IEC 80000-13 prefix is @samp{Ki}, but tradition and
1017 POSIX use @samp{k} to mean @samp{KiB}.
1019 @cindex megabyte, definition of
1020 megabyte: @math{10^6 = 1,000,000}.
1023 @cindex mebibyte, definition of
1024 mebibyte: @math{2^{20} = 1,048,576}.
1026 @cindex gigabyte, definition of
1027 gigabyte: @math{10^9 = 1,000,000,000}.
1030 @cindex gibibyte, definition of
1031 gibibyte: @math{2^{30} = 1,073,741,824}.
1033 @cindex terabyte, definition of
1034 terabyte: @math{10^{12} = 1,000,000,000,000}.
1037 @cindex tebibyte, definition of
1038 tebibyte: @math{2^{40} = 1,099,511,627,776}.
1040 @cindex petabyte, definition of
1041 petabyte: @math{10^{15} = 1,000,000,000,000,000}.
1044 @cindex pebibyte, definition of
1045 pebibyte: @math{2^{50} = 1,125,899,906,842,624}.
1047 @cindex exabyte, definition of
1048 exabyte: @math{10^{18} = 1,000,000,000,000,000,000}.
1051 @cindex exbibyte, definition of
1052 exbibyte: @math{2^{60} = 1,152,921,504,606,846,976}.
1054 @cindex zettabyte, definition of
1055 zettabyte: @math{10^{21} = 1,000,000,000,000,000,000,000}
1058 @math{2^{70} = 1,180,591,620,717,411,303,424}.
1060 @cindex yottabyte, definition of
1061 yottabyte: @math{10^{24} = 1,000,000,000,000,000,000,000,000}.
1064 @math{2^{80} = 1,208,925,819,614,629,174,706,176}.
1069 @opindex --block-size
1070 @opindex --human-readable
1073 Block size defaults can be overridden by an explicit
1074 @option{--block-size=@var{size}} option. The @option{-k}
1075 option is equivalent to @option{--block-size=1K}, which
1076 is the default unless the @env{POSIXLY_CORRECT} environment variable is
1077 set. The @option{-h} or @option{--human-readable} option is equivalent to
1078 @option{--block-size=human-readable}. The @option{--si} option is
1079 equivalent to @option{--block-size=si}. Note for @command{ls}
1080 the @option{-k} option does not control the display of the
1081 apparent file sizes, whereas the @option{--block-size} option does.
1083 @node Floating point
1084 @section Floating point numbers
1085 @cindex floating point
1086 @cindex IEEE floating point
1088 Commands that accept or produce floating point numbers employ the
1089 floating point representation of the underlying system, and suffer
1090 from rounding error, overflow, and similar floating-point issues.
1091 Almost all modern systems use IEEE-754 floating point, and it is
1092 typically portable to assume IEEE-754 behavior these days. IEEE-754
1093 has positive and negative infinity, distinguishes positive from
1094 negative zero, and uses special values called NaNs to represent
1095 invalid computations such as dividing zero by itself. For more
1096 information, please see David Goldberg's paper
1097 @uref{https://@/docs.oracle.com/@/cd/@/E19957-01/@/806-3568/@/ncg_goldberg.html,
1098 What Every Computer Scientist Should Know About Floating-Point Arithmetic}.
1100 Commands that accept floating point numbers as options, operands or
1101 input use the standard C functions @code{strtod} and @code{strtold} to
1102 convert from text to floating point numbers. These floating point
1103 numbers therefore can use scientific notation like @code{1.0e-34} and
1104 @code{-10e100}. Commands that parse floating point also understand
1105 case-insensitive @code{inf}, @code{infinity}, and @code{NaN}, although
1106 whether such values are useful depends on the command in question.
1107 Modern C implementations also accept hexadecimal floating point
1108 numbers such as @code{-0x.ep-3}, which stands for @minus{}14/16 times
1109 @math{2^-3}, which equals @minus{}0.109375. @xref{Parsing of
1110 Floats,,, libc, The GNU C Library Reference Manual}.
1113 Normally the @env{LC_NUMERIC} locale determines the decimal-point
1114 character. However, some commands' descriptions specify that they
1115 accept numbers in either the current or the C locale; for example,
1116 they treat @samp{3.14} like @samp{3,14} if the current locale uses
1117 comma as a decimal point.
1119 @node Signal specifications
1120 @section Signal specifications
1121 @cindex signals, specifying
1123 A @var{signal} may be a signal name like @samp{HUP}, or a signal
1124 number like @samp{1}, or an exit status of a process terminated by the
1125 signal. A signal name can be given in canonical form or prefixed by
1126 @samp{SIG}@. The case of the letters is ignored. The following signal names
1127 and numbers are supported on all POSIX compliant systems:
1133 2. Terminal interrupt.
1139 9. Kill (cannot be caught or ignored).
1147 Other supported signal names have system-dependent corresponding
1148 numbers. All systems conforming to POSIX 1003.1-2001 also
1149 support the following signals:
1153 Access to an undefined portion of a memory object.
1155 Child process terminated, stopped, or continued.
1157 Continue executing, if stopped.
1159 Erroneous arithmetic operation.
1161 Illegal Instruction.
1163 Write on a pipe with no one to read it.
1165 Invalid memory reference.
1167 Stop executing (cannot be caught or ignored).
1171 Background process attempting read.
1173 Background process attempting write.
1175 High bandwidth data is available at a socket.
1177 User-defined signal 1.
1179 User-defined signal 2.
1183 POSIX 1003.1-2001 systems that support the XSI extension
1184 also support the following signals:
1190 Profiling timer expired.
1194 Trace/breakpoint trap.
1196 Virtual timer expired.
1198 CPU time limit exceeded.
1200 File size limit exceeded.
1204 POSIX 1003.1-2001 systems that support the XRT extension
1205 also support at least eight real-time signals called @samp{RTMIN},
1206 @samp{RTMIN+1}, @dots{}, @samp{RTMAX-1}, @samp{RTMAX}.
1208 @node Disambiguating names and IDs
1209 @section chown, chgrp, chroot, id: Disambiguating user names and IDs
1210 @cindex user names, disambiguating
1211 @cindex user IDs, disambiguating
1212 @cindex group names, disambiguating
1213 @cindex group IDs, disambiguating
1214 @cindex disambiguating group names and IDs
1216 Since the @var{user} and @var{group} arguments to these commands
1217 may be specified as names or numeric IDs, there is an
1219 What if a user or group @emph{name} is a string of digits?
1220 Should the command interpret it as a user name or as an ID@?
1221 (Using a number as a user name is common in some environments.)
1222 POSIX requires that these commands
1223 first attempt to resolve the specified string as a name, and
1224 only once that fails, then try to interpret it as an ID@.
1225 This is troublesome when you want to specify a numeric ID, say 42,
1226 and it must work even in a pathological situation where
1227 @samp{42} is a user name that maps to some other user ID, say 1000.
1228 Simply invoking @code{chown 42 F}, will set @file{F}s owner ID to
1229 1000---not what you intended.
1231 GNU @command{chown}, @command{chgrp}, @command{chroot}, and @command{id}
1232 provide a way to work around this, that at the same time may result in a
1233 significant performance improvement by eliminating a database look-up.
1234 Simply precede each numeric user ID and/or group ID with a @samp{+},
1235 in order to force its interpretation as an integer:
1239 chgrp +$numeric_group_id another-file
1243 The name look-up process is skipped for each @samp{+}-prefixed string,
1244 because a string containing @samp{+} is never a valid user or group name.
1245 This syntax is accepted on most common Unix systems, but not on Solaris 10.
1247 @node Random sources
1248 @section Sources of random data
1250 @cindex random sources
1252 The @command{shuf}, @command{shred}, and @command{sort} commands
1253 sometimes need random data to do their work. For example, @samp{sort
1254 -R} must choose a hash function at random, and it needs random data to
1255 make this selection.
1257 By default these commands use an internal pseudo-random generator
1258 initialized by a small amount of entropy, but can be directed to use
1259 an external source with the @option{--random-source=@var{file}} option.
1260 An error is reported if @var{file} does not contain enough bytes.
1262 For example, the device file @file{/dev/urandom} could be used as the
1263 source of random data. Typically, this device gathers environmental
1264 noise from device drivers and other sources into an entropy pool, and
1265 uses the pool to generate random bits. If the pool is short of data,
1266 the device reuses the internal pool to produce more bits, using a
1267 cryptographically secure pseudo-random number generator. But be aware
1268 that this device is not designed for bulk random data generation
1269 and is relatively slow.
1271 @file{/dev/urandom} suffices for most practical uses, but applications
1272 requiring high-value or long-term protection of private data may
1273 require an alternate data source like @file{/dev/random} or
1274 @file{/dev/arandom}. The set of available sources depends on your
1277 To reproduce the results of an earlier invocation of a command, you
1278 can save some random data into a file and then use that file as the
1279 random source in earlier and later invocations of the command.
1281 Rather than depending on a file, one can generate a reproducible
1282 arbitrary amount of pseudo-random data given a seed value, using
1289 openssl enc -aes-256-ctr -pass pass:"$seed" -nosalt \
1290 </dev/zero 2>/dev/null
1293 shuf -i1-100 --random-source=<(get_seeded_random 42)
1296 @node Target directory
1297 @section Target directory
1299 @cindex target directory
1301 The @command{cp}, @command{install}, @command{ln}, and @command{mv}
1302 commands normally treat the last operand specially when it is a
1303 directory or a symbolic link to a directory. For example, @samp{cp
1304 source dest} is equivalent to @samp{cp source dest/source} if
1305 @file{dest} is a directory. Sometimes this behavior is not exactly
1306 what is wanted, so these commands support the following options to
1307 allow more fine-grained control:
1312 @itemx --no-target-directory
1313 @opindex --no-target-directory
1314 @cindex target directory
1315 @cindex destination directory
1316 Do not treat the last operand specially when it is a directory or a
1317 symbolic link to a directory. This can help avoid race conditions in
1318 programs that operate in a shared area. For example, when the command
1319 @samp{mv /tmp/source /tmp/dest} succeeds, there is no guarantee that
1320 @file{/tmp/source} was renamed to @file{/tmp/dest}: it could have been
1321 renamed to @file{/tmp/dest/source} instead, if some other process
1322 created @file{/tmp/dest} as a directory. However, if @file{mv
1323 -T /tmp/source /tmp/dest} succeeds, there is no
1324 question that @file{/tmp/source} was renamed to @file{/tmp/dest}.
1326 In the opposite situation, where you want the last operand to be
1327 treated as a directory and want a diagnostic otherwise, you can use
1328 the @option{--target-directory} (@option{-t}) option.
1330 @item -t @var{directory}
1331 @itemx --target-directory=@var{directory}
1332 @opindex --target-directory
1333 @cindex target directory
1334 @cindex destination directory
1335 Use @var{directory} as the directory component of each destination
1338 The interface for most programs is that after processing options and a
1339 finite (possibly zero) number of fixed-position arguments, the remaining
1340 argument list is either expected to be empty, or is a list of items
1341 (usually files) that will all be handled identically. The @command{xargs}
1342 program is designed to work well with this convention.
1344 The commands in the @command{mv}-family are unusual in that they take
1345 a variable number of arguments with a special case at the @emph{end}
1346 (namely, the target directory). This makes it nontrivial to perform some
1347 operations, e.g., ``move all files from here to ../d/'', because
1348 @code{mv * ../d/} might exhaust the argument space, and @code{ls | xargs ...}
1349 doesn't have a clean way to specify an extra final argument for each
1350 invocation of the subject command. (It can be done by going through a
1351 shell command, but that requires more human labor and brain power than
1354 The @option{--target-directory} (@option{-t}) option allows the @command{cp},
1355 @command{install}, @command{ln}, and @command{mv} programs to be used
1356 conveniently with @command{xargs}. For example, you can move the files
1357 from the current directory to a sibling directory, @code{d} like this:
1360 ls | xargs mv -t ../d --
1363 However, this doesn't move files whose names begin with @samp{.}.
1364 If you use the GNU @command{find} program, you can move those
1365 files too, with this command:
1368 find . -mindepth 1 -maxdepth 1 \
1372 But both of the above approaches fail if there are no files in the
1373 current directory, or if any file has a name containing a blank or
1374 some other special characters.
1375 The following example removes those limitations and requires both
1376 GNU @command{find} and GNU @command{xargs}:
1379 find . -mindepth 1 -maxdepth 1 -print0 \
1380 | xargs --null --no-run-if-empty \
1387 The @option{--target-directory} (@option{-t}) and
1388 @option{--no-target-directory} (@option{-T})
1389 options cannot be combined.
1391 @node Trailing slashes
1392 @section Trailing slashes
1394 @cindex trailing slashes
1396 Some GNU programs (at least @command{cp} and @command{mv}) allow you to
1397 remove any trailing slashes from each @var{source} argument before
1398 operating on it. The @option{--strip-trailing-slashes} option enables
1401 This is useful when a @var{source} argument may have a trailing slash and
1402 @c FIXME: mv's behavior in this case is system-dependent
1403 specify a symbolic link to a directory. This scenario is in fact rather
1404 common because some shells can automatically append a trailing slash when
1405 performing file name completion on such symbolic links. Without this
1406 option, @command{mv}, for example, (via the system's rename function) must
1407 interpret a trailing slash as a request to dereference the symbolic link
1408 and so must rename the indirectly referenced @emph{directory} and not
1409 the symbolic link. Although it may seem surprising that such behavior
1410 be the default, it is required by POSIX and is consistent with
1411 other parts of that standard.
1413 @node Traversing symlinks
1414 @section Traversing symlinks
1416 @cindex symbolic link to directory, controlling traversal of
1418 The following options modify how @command{chown} and @command{chgrp}
1419 @c FIXME: note that 'du' has these options, too, but they have slightly
1420 @c different meaning.
1421 traverse a hierarchy when the @option{--recursive} (@option{-R})
1422 option is also specified.
1423 If more than one of the following options is specified, only the final
1425 These options specify whether processing a symbolic link to a directory
1426 entails operating on just the symbolic link or on all files in the
1427 hierarchy rooted at that directory.
1429 These options are independent of @option{--dereference} and
1430 @option{--no-dereference} (@option{-h}), which control whether to modify
1431 a symlink or its referent.
1438 @cindex symbolic link to directory, traverse if on the command line
1439 If @option{--recursive} (@option{-R}) is specified and
1440 a command line argument is a symbolic link to a directory, traverse it.
1447 @cindex symbolic link to directory, traverse each that is encountered
1448 In a recursive traversal, traverse every symbolic link to a directory
1449 that is encountered.
1452 @c Append the following warning to -L where appropriate (e.g. chown).
1453 @macro warnOptDerefWithRec
1455 Combining this dereferencing option with the @option{--recursive} option
1456 may create a security risk:
1457 During the traversal of the directory tree, an attacker may be able to
1458 introduce a symlink to an arbitrary target; when the tool reaches that,
1459 the operation will be performed on the target of that symlink,
1460 possibly allowing the attacker to escalate privileges.
1469 @cindex symbolic link to directory, never traverse
1470 Do not traverse any symbolic links.
1471 This is the default if none of @option{-H}, @option{-L},
1472 or @option{-P} is specified.
1479 @node Treating / specially
1480 @section Treating @file{/} specially
1482 Certain commands can operate destructively on entire hierarchies.
1483 For example, if a user with appropriate privileges mistakenly runs
1484 @samp{rm -rf / tmp/junk}, that may remove
1485 all files on the entire system. Since there are so few
1486 legitimate uses for such a command,
1487 GNU @command{rm} normally declines to operate on any directory
1488 that resolves to @file{/}. If you really want to try to remove all
1489 the files on your system, you can use the @option{--no-preserve-root}
1490 option, but the default behavior, specified by the
1491 @option{--preserve-root} option, is safer for most purposes.
1493 The commands @command{chgrp}, @command{chmod} and @command{chown}
1494 can also operate destructively on entire hierarchies, so they too
1495 support these options. Although, unlike @command{rm}, they don't
1496 actually unlink files, these commands are arguably more dangerous
1497 when operating recursively on @file{/}, since they often work much
1498 more quickly, and hence damage more files before an alert user can
1499 interrupt them. Tradition and POSIX require these commands
1500 to operate recursively on @file{/}, so they default to
1501 @option{--no-preserve-root}, but using the @option{--preserve-root}
1502 option makes them safer for most purposes. For convenience you can
1503 specify @option{--preserve-root} in an alias or in a shell function.
1505 Note that the @option{--preserve-root} option also ensures
1506 that @command{chgrp} and @command{chown} do not modify @file{/}
1507 even when dereferencing a symlink pointing to @file{/}.
1509 @node Special built-in utilities
1510 @section Special built-in utilities
1512 Some programs like @command{nice} can invoke other programs; for
1513 example, the command @samp{nice cat file} invokes the program
1514 @command{cat} by executing the command @samp{cat file}. However,
1515 @dfn{special built-in utilities} like @command{exit} cannot be invoked
1516 this way. For example, the command @samp{nice exit} does not have a
1517 well-defined behavior: it may generate an error message instead of
1520 Here is a list of the special built-in utilities that are standardized
1521 by POSIX 1003.1-2004.
1524 @t{.@: : break continue eval exec exit export readonly
1525 return set shift times trap unset}
1528 For example, because @samp{.}, @samp{:}, and @samp{exec} are special,
1529 the commands @samp{nice . foo.sh}, @samp{nice :}, and @samp{nice exec
1530 pwd} do not work as you might expect.
1532 Many shells extend this list. For example, Bash has several extra
1533 special built-in utilities like @command{history}, and
1534 @command{suspend}, and with Bash the command @samp{nice suspend}
1535 generates an error message instead of suspending.
1537 @node Standards conformance
1538 @section Standards conformance
1540 @vindex POSIXLY_CORRECT
1541 In a few cases, the GNU utilities' default behavior is
1542 incompatible with the POSIX standard. To suppress these
1543 incompatibilities, define the @env{POSIXLY_CORRECT} environment
1544 variable. Unless you are checking for POSIX conformance, you
1545 probably do not need to define @env{POSIXLY_CORRECT}.
1547 Newer versions of POSIX are occasionally incompatible with older
1548 versions. For example, older versions of POSIX required the
1549 command @samp{sort +1} to sort based on the second and succeeding
1550 fields in each input line, but in POSIX 1003.1-2001
1551 the same command is required to sort the file named @file{+1}, and you
1552 must instead use the command @samp{sort -k 2} to get the field-based
1553 sort. To complicate things further, POSIX 1003.1-2008 allows an
1554 implementation to have either the old or the new behavior.
1556 @vindex _POSIX2_VERSION
1557 The GNU utilities normally conform to the version of POSIX
1558 that is standard for your system. To cause them to conform to a
1559 different version of POSIX, define the @env{_POSIX2_VERSION}
1560 environment variable to a value of the form @var{yyyymm} specifying
1561 the year and month the standard was adopted. Three values are currently
1562 supported for @env{_POSIX2_VERSION}: @samp{199209} stands for
1563 POSIX 1003.2-1992, @samp{200112} stands for POSIX
1564 1003.1-2001, and @samp{200809} stands for POSIX 1003.1-2008.
1565 For example, if you have a POSIX 1003.1-2001 system but are running software
1566 containing traditional usage like @samp{sort +1} or @samp{tail +10},
1567 you can work around the compatibility problems by setting
1568 @samp{_POSIX2_VERSION=200809} in your environment.
1570 @c This node is named "Multi-call invocation", not the usual
1571 @c "coreutils invocation", so that shell commands like
1572 @c 'info coreutils "touch invocation"' work as expected.
1573 @node Multi-call invocation
1574 @section @command{coreutils}: Multi-call program
1578 @cindex calling combined multi-call program
1580 The @command{coreutils} command invokes an individual utility, either
1581 implicitly selected by the last component of the name used to invoke
1582 @command{coreutils}, or explicitly with the
1583 @option{--coreutils-prog} option. Synopsis:
1586 coreutils @option{--coreutils-prog=PROGRAM} @dots{}
1589 The @command{coreutils} command is not installed by default, so
1590 portable scripts should not rely on its existence.
1592 @node Output of entire files
1593 @chapter Output of entire files
1595 @cindex output of entire files
1596 @cindex entire files, output of
1598 These commands read and write entire files, possibly transforming them
1602 * cat invocation:: Concatenate and write files.
1603 * tac invocation:: Concatenate and write files in reverse.
1604 * nl invocation:: Number lines and write files.
1605 * od invocation:: Write files in octal or other formats.
1606 * base32 invocation:: Transform data into printable data.
1607 * base64 invocation:: Transform data into printable data.
1608 * basenc invocation:: Transform data into printable data.
1611 @node cat invocation
1612 @section @command{cat}: Concatenate and write files
1615 @cindex concatenate and write files
1616 @cindex copying files
1618 @command{cat} copies each @var{file} (@samp{-} means standard input), or
1619 standard input if none are given, to standard output. Synopsis:
1622 cat [@var{option}] [@var{file}]@dots{}
1625 The program accepts the following options. Also see @ref{Common options}.
1633 Equivalent to @option{-vET}.
1636 @itemx --number-nonblank
1638 @opindex --number-nonblank
1639 Number all nonempty output lines, starting with 1.
1643 Equivalent to @option{-vE}.
1648 @opindex --show-ends
1649 Display a @samp{$} after the end of each line.
1650 The @code{\r\n} combination is shown as @samp{^M$}.
1656 Number all output lines, starting with 1. This option is ignored
1657 if @option{-b} is in effect.
1660 @itemx --squeeze-blank
1662 @opindex --squeeze-blank
1663 @cindex squeezing empty lines
1664 @cindex squeezing blank lines
1665 Suppress repeated adjacent blank lines; output just one empty line
1670 Equivalent to @option{-vT}.
1675 @opindex --show-tabs
1676 Display TAB characters as @samp{^I}.
1680 Ignored; for POSIX compatibility.
1683 @itemx --show-nonprinting
1685 @opindex --show-nonprinting
1686 Display control characters except for LFD and TAB using
1687 @samp{^} notation and precede characters that have the high bit set with
1692 On systems like MS-DOS that distinguish between text and binary files,
1693 @command{cat} normally reads and writes in binary mode. However,
1694 @command{cat} reads in text mode if one of the options
1695 @option{-bensAE} is used or if @command{cat} is reading from standard
1696 input and standard input is a terminal. Similarly, @command{cat}
1697 writes in text mode if one of the options @option{-bensAE} is used or
1698 if standard output is a terminal.
1705 # Output f's contents, then standard input, then g's contents.
1708 # Copy standard input to standard output.
1713 @node tac invocation
1714 @section @command{tac}: Concatenate and write files in reverse
1717 @cindex reversing files
1719 @command{tac} copies each @var{file} (@samp{-} means standard input), or
1720 standard input if none are given, to standard output, reversing the
1721 records (lines by default) in each separately. Synopsis:
1724 tac [@var{option}]@dots{} [@var{file}]@dots{}
1727 @dfn{Records} are separated by instances of a string (newline by
1728 default). By default, this separator string is attached to the end of
1729 the record that it follows in the file.
1731 The program accepts the following options. Also see @ref{Common options}.
1739 The separator is attached to the beginning of the record that it
1740 precedes in the file.
1746 Treat the separator string as a regular expression.
1748 @item -s @var{separator}
1749 @itemx --separator=@var{separator}
1751 @opindex --separator
1752 Use @var{separator} as the record separator, instead of newline.
1753 Note an empty @var{separator} is treated as a zero byte.
1754 I.e., input and output items are delimited with ASCII NUL.
1758 On systems like MS-DOS that distinguish between text and binary files,
1759 @command{tac} reads and writes in binary mode.
1766 # Reverse a file character by character.
1772 @section @command{nl}: Number lines and write files
1775 @cindex numbering lines
1776 @cindex line numbering
1778 @command{nl} writes each @var{file} (@samp{-} means standard input), or
1779 standard input if none are given, to standard output, with line numbers
1780 added to some or all of the lines. Synopsis:
1783 nl [@var{option}]@dots{} [@var{file}]@dots{}
1786 @cindex logical pages, numbering on
1787 @command{nl} decomposes its input into (logical) page sections;
1788 by default, the line number is reset to 1 at each logical page section.
1789 @command{nl} treats all of the input files as a single document;
1790 it does not reset line numbers or logical pages between files.
1792 @cindex headers, numbering
1793 @cindex body, numbering
1794 @cindex footers, numbering
1795 A logical page consists of three sections: header, body, and footer.
1796 Any of the sections can be empty. Each can be numbered in a different
1797 style from the others.
1799 The beginnings of the sections of logical pages are indicated in the
1800 input file by a line containing exactly one of these delimiter strings:
1811 The characters from which these strings are made can be changed from
1812 @samp{\} and @samp{:} via options (see below), but the pattern
1813 of each string cannot be changed.
1815 A section delimiter is replaced by an empty line on output. Any text
1816 that comes before the first section delimiter string in the input file
1817 is considered to be part of a body section, so @command{nl} treats a
1818 file that contains no section delimiters as a single body section.
1820 The program accepts the following options. Also see @ref{Common options}.
1824 @item -b @var{style}
1825 @itemx --body-numbering=@var{style}
1827 @opindex --body-numbering
1828 Select the numbering style for lines in the body section of each
1829 logical page. When a line is not numbered, the current line number
1830 is not incremented, but the line number separator character is still
1831 prepended to the line. The styles are:
1837 number only nonempty lines (default for body),
1839 do not number lines (default for header and footer),
1841 number only lines that contain a match for the basic regular
1842 expression @var{bre}.
1843 @xref{Regular Expressions, , Regular Expressions, grep, The GNU Grep Manual}.
1847 @itemx --section-delimiter=@var{cd}
1849 @opindex --section-delimiter
1850 @cindex section delimiters of pages
1851 Set the section delimiter characters to @var{cd}; default is
1852 @samp{\:}. If only @var{c} is given, the second remains @samp{:}.
1853 As a GNU extension more than two characters can be specified,
1854 and also if @var{cd} is empty (@option{-d ''}), then section
1855 matching is disabled.
1856 (Remember to protect @samp{\} or other metacharacters from shell
1857 expansion with quotes or extra backslashes.)
1859 @item -f @var{style}
1860 @itemx --footer-numbering=@var{style}
1862 @opindex --footer-numbering
1863 Analogous to @option{--body-numbering}.
1865 @item -h @var{style}
1866 @itemx --header-numbering=@var{style}
1868 @opindex --header-numbering
1869 Analogous to @option{--body-numbering}.
1871 @item -i @var{number}
1872 @itemx --line-increment=@var{number}
1874 @opindex --line-increment
1875 Increment line numbers by @var{number} (default 1).
1876 @var{number} can be negative to decrement.
1878 @item -l @var{number}
1879 @itemx --join-blank-lines=@var{number}
1881 @opindex --join-blank-lines
1882 @cindex empty lines, numbering
1883 @cindex blank lines, numbering
1884 Consider @var{number} (default 1) consecutive empty lines to be one
1885 logical line for numbering, and only number the last one. Where fewer
1886 than @var{number} consecutive empty lines occur, do not number them.
1887 An empty line is one that contains no characters, not even spaces
1890 @item -n @var{format}
1891 @itemx --number-format=@var{format}
1893 @opindex --number-format
1894 Select the line numbering format (default is @code{rn}):
1898 @opindex ln @r{format for @command{nl}}
1899 left justified, no leading zeros;
1901 @opindex rn @r{format for @command{nl}}
1902 right justified, no leading zeros;
1904 @opindex rz @r{format for @command{nl}}
1905 right justified, leading zeros.
1909 @itemx --no-renumber
1911 @opindex --no-renumber
1912 Do not reset the line number at the start of a logical page.
1914 @item -s @var{string}
1915 @itemx --number-separator=@var{string}
1917 @opindex --number-separator
1918 Separate the line number from the text line in the output with
1919 @var{string} (default is the TAB character).
1921 @item -v @var{number}
1922 @itemx --starting-line-number=@var{number}
1924 @opindex --starting-line-number
1925 Set the initial line number on each logical page to @var{number} (default 1).
1926 The starting @var{number} can be negative.
1928 @item -w @var{number}
1929 @itemx --number-width=@var{number}
1931 @opindex --number-width
1932 Use @var{number} characters for line numbers (default 6).
1940 @section @command{od}: Write files in octal or other formats
1943 @cindex octal dump of files
1944 @cindex hex dump of files
1945 @cindex ASCII dump of files
1946 @cindex file contents, dumping unambiguously
1948 @command{od} writes an unambiguous representation of each @var{file}
1949 (@samp{-} means standard input), or standard input if none are given.
1953 od [@var{option}]@dots{} [@var{file}]@dots{}
1954 od [-abcdfilosx]@dots{} [@var{file}] [[+]@var{offset}[.][b]]
1955 od [@var{option}]@dots{} --traditional [@var{file}]@c
1956 [[+]@var{offset}[.][b] [[+]@var{label}[.][b]]]
1959 Each line of output consists of the offset in the input, followed by
1960 groups of data from the file. By default, @command{od} prints the offset in
1961 octal, and each group of file data is a C @code{short int}'s worth of input
1962 printed as a single octal number.
1964 If @var{offset} is given, it specifies how many input bytes to skip
1965 before formatting and writing. By default, it is interpreted as an
1966 octal number, but the optional trailing decimal point causes it to be
1967 interpreted as decimal. If no decimal is specified and the offset
1968 begins with @samp{0x} or @samp{0X} it is interpreted as a hexadecimal
1969 number. If there is a trailing @samp{b}, the number of bytes skipped
1970 will be @var{offset} multiplied by 512.
1972 If a command is of both the first and second forms, the second form is
1973 assumed if the last operand begins with @samp{+} or (if there are two
1974 operands) a digit. For example, in @samp{od foo 10} and @samp{od +10}
1975 the @samp{10} is an offset, whereas in @samp{od 10} the @samp{10} is a
1978 The program accepts the following options. Also see @ref{Common options}.
1982 @item -A @var{radix}
1983 @itemx --address-radix=@var{radix}
1985 @opindex --address-radix
1986 @cindex radix for file offsets
1987 @cindex file offset radix
1988 Select the base in which file offsets are printed. @var{radix} can
1989 be one of the following:
1999 none (do not print offsets).
2002 The default is octal.
2004 @item --endian=@var{order}
2006 @cindex byte-swapping
2008 Reorder input bytes, to handle inputs with differing byte orders,
2009 or to provide consistent output independent of the endian convention
2010 of the current system. Swapping is performed according to the
2011 specified @option{--type} size and endian @var{order}, which can be
2012 @samp{little} or @samp{big}.
2014 @item -j @var{bytes}
2015 @itemx --skip-bytes=@var{bytes}
2017 @opindex --skip-bytes
2018 Skip @var{bytes} input bytes before formatting and writing. If
2019 @var{bytes} begins with @samp{0x} or @samp{0X}, it is interpreted in
2020 hexadecimal; otherwise, if it begins with @samp{0}, in octal; otherwise,
2022 @multiplierSuffixes{bytes}
2024 @item -N @var{bytes}
2025 @itemx --read-bytes=@var{bytes}
2027 @opindex --read-bytes
2028 Output at most @var{bytes} bytes of the input. Prefixes and suffixes on
2029 @code{bytes} are interpreted as for the @option{-j} option.
2031 @item -S @var{bytes}
2032 @itemx --strings[=@var{bytes}]
2035 @cindex string constants, outputting
2036 Instead of the normal output, output only @dfn{string constants}: at
2037 least @var{bytes} consecutive ASCII graphic characters,
2038 followed by a zero byte (ASCII NUL).
2039 Prefixes and suffixes on @var{bytes} are interpreted as for the
2042 If @var{bytes} is omitted with @option{--strings}, the default is 3.
2045 @itemx --format=@var{type}
2048 Select the format in which to output the file data. @var{type} is a
2049 string of one or more of the below type indicator characters. If you
2050 include more than one type indicator character in a single @var{type}
2051 string, or use this option more than once, @command{od} writes one copy
2052 of each output line using each of the data types that you specified,
2053 in the order that you specified.
2055 Adding a trailing ``z'' to any type specification appends a display
2056 of the single byte character representation of the printable characters
2057 to the output line generated by the type specification.
2061 named character, ignoring high-order bit
2063 printable single byte character, C backslash escape
2064 or a 3 digit octal sequence
2068 floating point (@pxref{Floating point})
2077 The type @code{a} outputs things like @samp{sp} for space, @samp{nl} for
2078 newline, and @samp{nul} for a zero byte. Only the least significant
2079 seven bits of each byte is used; the high-order bit is ignored.
2080 Type @code{c} outputs
2081 @samp{ }, @samp{\n}, and @code{\0}, respectively.
2084 Except for types @samp{a} and @samp{c}, you can specify the number
2085 of bytes to use in interpreting each number in the given data type
2086 by following the type indicator character with a decimal integer.
2087 Alternately, you can specify the size of one of the C compiler's
2088 built-in data types by following the type indicator character with
2089 one of the following characters. For integers (@samp{d}, @samp{o},
2090 @samp{u}, @samp{x}):
2103 For floating point (@code{f}):
2115 @itemx --output-duplicates
2117 @opindex --output-duplicates
2118 Output consecutive lines that are identical. By default, when two or
2119 more consecutive output lines would be identical, @command{od} outputs only
2120 the first line, and puts just an asterisk on the following line to
2121 indicate the elision.
2124 @itemx --width[=@var{n}]
2127 Dump @code{n} input bytes per output line. This must be a multiple of
2128 the least common multiple of the sizes associated with the specified
2131 If this option is not given at all, the default is 16. If @var{n} is
2132 omitted, the default is 32.
2136 The next several options are shorthands for format specifications.
2137 GNU @command{od} accepts any combination of shorthands and format
2138 specification options. These options accumulate.
2144 Output as named characters. Equivalent to @samp{-t a}.
2148 Output as octal bytes. Equivalent to @samp{-t o1}.
2152 Output as printable single byte characters, C backslash escapes
2153 or 3 digit octal sequences. Equivalent to @samp{-t c}.
2157 Output as unsigned decimal two-byte units. Equivalent to @samp{-t u2}.
2161 Output as floats. Equivalent to @samp{-t fF}.
2165 Output as decimal ints. Equivalent to @samp{-t dI}.
2169 Output as decimal long ints. Equivalent to @samp{-t dL}.
2173 Output as octal two-byte units. Equivalent to @option{-t o2}.
2177 Output as decimal two-byte units. Equivalent to @option{-t d2}.
2181 Output as hexadecimal two-byte units. Equivalent to @samp{-t x2}.
2184 @opindex --traditional
2185 Recognize the non-option label argument that traditional @command{od}
2186 accepted. The following syntax:
2189 od --traditional [@var{file}] [[+]@var{offset}[.][b] [[+]@var{label}[.][b]]]
2193 can be used to specify at most one file and optional arguments
2194 specifying an offset and a pseudo-start address, @var{label}.
2195 The @var{label} argument is interpreted
2196 just like @var{offset}, but it specifies an initial pseudo-address. The
2197 pseudo-addresses are displayed in parentheses following any normal
2205 @node base32 invocation
2206 @section @command{base32}: Transform data into printable data
2209 @cindex base32 encoding
2211 @command{base32} transforms data read from a file, or standard input,
2212 into (or from) base32 encoded form. The base32 encoded form uses
2213 printable ASCII characters to represent binary data.
2214 The usage and options of this command are precisely the
2215 same as for @command{base64}. @xref{base64 invocation}.
2218 @node base64 invocation
2219 @section @command{base64}: Transform data into printable data
2222 @cindex base64 encoding
2224 @command{base64} transforms data read from a file, or standard input,
2225 into (or from) base64 encoded form. The base64 encoded form uses
2226 printable ASCII characters to represent binary data.
2230 base64 [@var{option}]@dots{} [@var{file}]
2231 base64 --decode [@var{option}]@dots{} [@var{file}]
2234 The base64 encoding expands data to roughly 133% of the original.
2235 The base32 encoding expands data to roughly 160% of the original.
2236 The format conforms to
2237 @uref{https://tools.ietf.org/search/rfc4648, RFC 4648}.
2239 The program accepts the following options. Also see @ref{Common options}.
2244 @itemx --wrap=@var{cols}
2248 @cindex column to wrap data after
2249 During encoding, wrap lines after @var{cols} characters. This must be
2252 The default is to wrap after 76 characters. Use the value 0 to
2253 disable line wrapping altogether.
2259 @cindex Decode base64 data
2260 @cindex Base64 decoding
2261 Change the mode of operation, from the default of encoding data, to
2262 decoding data. Input is expected to be base64 encoded data, and the
2263 output will be the original data.
2266 @itemx --ignore-garbage
2268 @opindex --ignore-garbage
2269 @cindex Ignore garbage in base64 stream
2270 When decoding, newlines are always accepted.
2271 During decoding, ignore unrecognized bytes,
2272 to permit distorted data to be decoded.
2278 @node basenc invocation
2279 @section @command{basenc}: Transform data into printable data
2282 @cindex base32 encoding
2284 @command{basenc} transforms data read from a file, or standard input,
2285 into (or from) various common encoding forms. The encoded form uses
2286 printable ASCII characters to represent binary data.
2291 basenc @var{encoding} [@var{option}]@dots{} [@var{file}]
2292 basenc @var{encoding} --decode [@var{option}]@dots{} [@var{file}]
2295 The @var{encoding} argument is required. If @var{file} is omitted,
2296 @command{basenc} reads from standard input.
2297 The @option{-w/--wrap},@option{-i/--ignore-garbage},
2298 @option{-d/--decode} options of this command are precisely the same as
2299 for @command{base64}. @xref{base64 invocation}.
2302 Supported @var{encoding}s are:
2308 Encode into (or decode from with @option{-d/--decode}) base64 form.
2309 The format conforms to
2310 @uref{https://tools.ietf.org/search/rfc4648#section-4, RFC 4648#4}.
2311 Equivalent to the @command{base64} command.
2314 @opindex --base64url
2315 Encode into (or decode from with @option{-d/--decode}) file-and-url-safe
2316 base64 form (using @samp{_} and @samp{-} instead of @samp{+} and @samp{/}).
2317 The format conforms to
2318 @uref{https://tools.ietf.org/search/rfc4648#section-5, RFC 4648#5}.
2322 Encode into (or decode from with @option{-d/--decode}) base32 form.
2323 The encoded data uses the @samp{ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=} characters.
2324 The format conforms to
2325 @uref{https://tools.ietf.org/search/rfc4648#section-6, RFC 4648#6}.
2326 Equivalent to the @command{base32} command.
2329 @opindex --base32hex
2330 Encode into (or decode from with @option{-d/--decode}) Extended Hex Alphabet
2331 base32 form. The encoded data uses the
2332 @samp{0123456789ABCDEFGHIJKLMNOPQRSTUV=} characters. The format conforms to
2333 @uref{https://tools.ietf.org/search/rfc4648#section-7, RFC 4648#7}.
2337 Encode into (or decode from with @option{-d/--decode}) base16 (hexadecimal)
2338 form. The encoded data uses the @samp{0123456789ABCDEF} characters. The format
2340 @uref{https://tools.ietf.org/search/rfc4648#section-8, RFC 4648#8}.
2343 @opindex --base2lsbf
2344 Encode into (or decode from with @option{-d/--decode}) binary string form
2345 (@samp{0} and @samp{1}) with the @emph{least} significant bit of every byte
2349 @opindex --base2msbf
2350 Encode into (or decode from with @option{-d/--decode}) binary string form
2351 (@samp{0} and @samp{1}) with the @emph{most} significant bit of every byte
2356 Encode into (or decode from with @option{-d/--decode}) Z85 form
2357 (a modified Ascii85 form). The encoded data uses the
2358 @samp{0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU@
2359 VWXYZ.-:+=^!/*?&<>()[]@{@}@@%$#}.
2360 characters. The format conforms to
2361 @uref{https://rfc.zeromq.org/spec:32/Z85/, ZeroMQ spec:32/Z85}.
2363 When encoding with @option{--z85}, input length must be a multiple of 4;
2364 when decoding with @option{--z85}, input length must be a multiple of 5.
2370 Encoding/decoding examples:
2373 $ printf '\376\117\202' | basenc --base64
2376 $ printf '\376\117\202' | basenc --base64url
2379 $ printf '\376\117\202' | basenc --base32
2382 $ printf '\376\117\202' | basenc --base32hex
2385 $ printf '\376\117\202' | basenc --base16
2388 $ printf '\376\117\202' | basenc --base2lsbf
2389 011111111111001001000001
2391 $ printf '\376\117\202' | basenc --base2msbf
2392 111111100100111110000010
2394 $ printf '\376\117\202\000' | basenc --z85
2397 $ printf 01010100 | basenc --base2msbf --decode
2400 $ printf 01010100 | basenc --base2lsbf --decode
2406 @node Formatting file contents
2407 @chapter Formatting file contents
2409 @cindex formatting file contents
2411 These commands reformat the contents of files.
2414 * fmt invocation:: Reformat paragraph text.
2415 * pr invocation:: Paginate or columnate files for printing.
2416 * fold invocation:: Wrap input lines to fit in specified width.
2420 @node fmt invocation
2421 @section @command{fmt}: Reformat paragraph text
2424 @cindex reformatting paragraph text
2425 @cindex paragraphs, reformatting
2426 @cindex text, reformatting
2428 @command{fmt} fills and joins lines to produce output lines of (at most)
2429 a given number of characters (75 by default). Synopsis:
2432 fmt [@var{option}]@dots{} [@var{file}]@dots{}
2435 @command{fmt} reads from the specified @var{file} arguments (or standard
2436 input if none are given), and writes to standard output.
2438 By default, blank lines, spaces between words, and indentation are
2439 preserved in the output; successive input lines with different
2440 indentation are not joined; tabs are expanded on input and introduced on
2443 @cindex line-breaking
2444 @cindex sentences and line-breaking
2445 @cindex Knuth, Donald E.
2446 @cindex Plass, Michael F.
2447 @command{fmt} prefers breaking lines at the end of a sentence, and tries to
2448 avoid line breaks after the first word of a sentence or before the last
2449 word of a sentence. A @dfn{sentence break} is defined as either the end
2450 of a paragraph or a word ending in any of @samp{.?!}, followed by two
2451 spaces or end of line, ignoring any intervening parentheses or quotes.
2452 Like @TeX{}, @command{fmt} reads entire ``paragraphs'' before choosing line
2453 breaks; the algorithm is a variant of that given by Donald E. Knuth
2454 and Michael F. Plass in ``Breaking Paragraphs Into Lines'',
2455 @cite{Software---Practice & Experience} @b{11}, 11 (November 1981),
2458 The program accepts the following options. Also see @ref{Common options}.
2463 @itemx --crown-margin
2465 @opindex --crown-margin
2466 @cindex crown margin
2467 @dfn{Crown margin} mode: preserve the indentation of the first two
2468 lines within a paragraph, and align the left margin of each subsequent
2469 line with that of the second line.
2472 @itemx --tagged-paragraph
2474 @opindex --tagged-paragraph
2475 @cindex tagged paragraphs
2476 @dfn{Tagged paragraph} mode: like crown margin mode, except that if
2477 indentation of the first line of a paragraph is the same as the
2478 indentation of the second, the first line is treated as a one-line
2484 @opindex --split-only
2485 Split lines only. Do not join short lines to form longer ones. This
2486 prevents sample lines of code, and other such ``formatted'' text from
2487 being unduly combined.
2490 @itemx --uniform-spacing
2492 @opindex --uniform-spacing
2493 Uniform spacing. Reduce spacing between words to one space, and spacing
2494 between sentences to two spaces.
2497 @itemx -w @var{width}
2498 @itemx --width=@var{width}
2499 @opindex -@var{width}
2502 Fill output lines up to @var{width} characters (default 75 or @var{goal}
2503 plus 10, if @var{goal} is provided).
2506 @itemx --goal=@var{goal}
2509 @command{fmt} initially tries to make lines @var{goal} characters wide.
2510 By default, this is 7% shorter than @var{width}.
2512 @item -p @var{prefix}
2513 @itemx --prefix=@var{prefix}
2514 Only lines beginning with @var{prefix} (possibly preceded by whitespace)
2515 are subject to formatting. The prefix and any preceding whitespace are
2516 stripped for the formatting and then re-attached to each formatted output
2517 line. One use is to format certain kinds of program comments, while
2518 leaving the code unchanged.
2525 @section @command{pr}: Paginate or columnate files for printing
2528 @cindex printing, preparing files for
2529 @cindex multicolumn output, generating
2530 @cindex merging files in parallel
2532 @command{pr} writes each @var{file} (@samp{-} means standard input), or
2533 standard input if none are given, to standard output, paginating and
2534 optionally outputting in multicolumn format; optionally merges all
2535 @var{file}s, printing all in parallel, one per column. Synopsis:
2538 pr [@var{option}]@dots{} [@var{file}]@dots{}
2542 By default, a 5-line header is printed at each page: two blank lines;
2543 a line with the date, the file name, and the page count; and two more
2544 blank lines. A footer of five blank lines is also printed.
2545 The default @var{page_length} is 66
2546 lines. The default number of text lines is therefore 56.
2547 The text line of the header takes the form
2548 @samp{@var{date} @var{string} @var{page}}, with spaces inserted around
2549 @var{string} so that the line takes up the full @var{page_width}. Here,
2550 @var{date} is the date (see the @option{-D} or @option{--date-format}
2551 option for details), @var{string} is the centered header string, and
2552 @var{page} identifies the page number. The @env{LC_MESSAGES} locale
2553 category affects the spelling of @var{page}; in the default C locale, it
2554 is @samp{Page @var{number}} where @var{number} is the decimal page
2557 Form feeds in the input cause page breaks in the output. Multiple form
2558 feeds produce empty pages.
2560 Columns are of equal width, separated by an optional string (default
2561 is @samp{space}). For multicolumn output, lines will always be truncated to
2562 @var{page_width} (default 72), unless you use the @option{-J} option.
2564 column output no line truncation occurs by default. Use @option{-W} option to
2565 truncate lines in that case.
2567 The program accepts the following options. Also see @ref{Common options}.
2571 @item +@var{first_page}[:@var{last_page}]
2572 @itemx --pages=@var{first_page}[:@var{last_page}]
2573 @c The two following @opindex lines evoke warnings because they contain ':'
2574 @c The 'info' spec does not permit that. If we use those lines, we end
2575 @c up with truncated index entries that don't work.
2576 @c @opindex +@var{first_page}[:@var{last_page}]
2577 @c @opindex --pages=@var{first_page}[:@var{last_page}]
2578 @opindex +@var{page_range}
2579 @opindex --pages=@var{page_range}
2580 Begin printing with page @var{first_page} and stop with @var{last_page}.
2581 Missing @samp{:@var{last_page}} implies end of file. While estimating
2582 the number of skipped pages each form feed in the input file results
2583 in a new page. Page counting with and without @samp{+@var{first_page}}
2584 is identical. By default, counting starts with the first page of input
2585 file (not first page printed). Line numbering may be altered by @option{-N}
2589 @itemx --columns=@var{column}
2590 @opindex -@var{column}
2592 @cindex down columns
2593 With each single @var{file}, produce @var{column} columns of output
2594 (default is 1) and print columns down, unless @option{-a} is used. The
2595 column width is automatically decreased as @var{column} increases; unless
2596 you use the @option{-W/-w} option to increase @var{page_width} as well.
2597 This option might well cause some lines to be truncated. The number of
2598 lines in the columns on each page are balanced. The options @option{-e}
2599 and @option{-i} are on for multiple text-column output. Together with
2600 @option{-J} option column alignment and line truncation is turned off.
2601 Lines of full length are joined in a free field format and @option{-S}
2602 option may set field separators. @option{-@var{column}} may not be used
2603 with @option{-m} option.
2609 @cindex across columns
2610 With each single @var{file}, print columns across rather than down. The
2611 @option{-@var{column}} option must be given with @var{column} greater than one.
2612 If a line is too long to fit in a column, it is truncated.
2615 @itemx --show-control-chars
2617 @opindex --show-control-chars
2618 Print control characters using hat notation (e.g., @samp{^G}); print
2619 other nonprinting characters in octal backslash notation. By default,
2620 nonprinting characters are not changed.
2623 @itemx --double-space
2625 @opindex --double-space
2626 @cindex double spacing
2627 Double space the output.
2629 @item -D @var{format}
2630 @itemx --date-format=@var{format}
2631 @cindex time formats
2632 @cindex formatting times
2633 Format header dates using @var{format}, using the same conventions as
2634 for the command @samp{date +@var{format}}. @xref{date invocation}.
2635 Except for directives, which start with
2636 @samp{%}, characters in @var{format} are printed unchanged. You can use
2637 this option to specify an arbitrary string in place of the header date,
2638 e.g., @option{--date-format="Monday morning"}.
2640 @vindex POSIXLY_CORRECT
2642 The default date format is @samp{%Y-%m-%d %H:%M} (for example,
2643 @samp{2020-07-09 23:59});
2644 but if the @env{POSIXLY_CORRECT} environment variable is set
2645 and the @env{LC_TIME} locale category specifies the POSIX
2646 locale, the default is @samp{%b %e %H:%M %Y} (for example,
2647 @samp{Jul@ @ 9 23:59 2020}.
2650 Timestamps are listed according to the time zone rules specified by
2651 the @env{TZ} environment variable, or by the system default rules if
2652 @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
2653 with @env{TZ}, libc, The GNU C Library Reference Manual}.
2655 @item -e[@var{in-tabchar}[@var{in-tabwidth}]]
2656 @itemx --expand-tabs[=@var{in-tabchar}[@var{in-tabwidth}]]
2658 @opindex --expand-tabs
2660 Expand @var{tab}s to spaces on input. Optional argument @var{in-tabchar} is
2661 the input tab character (default is the TAB character). Second optional
2662 argument @var{in-tabwidth} is the input tab character's width (default
2670 @opindex --form-feed
2671 Use a form feed instead of newlines to separate output pages. This does
2672 not alter the default page length of 66 lines.
2674 @item -h @var{header}
2675 @itemx --header=@var{header}
2678 Replace the file name in the header with the centered string @var{header}.
2679 When using the shell, @var{header} should be quoted and should be
2680 separated from @option{-h} by a space.
2682 @item -i[@var{out-tabchar}[@var{out-tabwidth}]]
2683 @itemx --output-tabs[=@var{out-tabchar}[@var{out-tabwidth}]]
2685 @opindex --output-tabs
2687 Replace spaces with @var{tab}s on output. Optional argument @var{out-tabchar}
2688 is the output tab character (default is the TAB character). Second optional
2689 argument @var{out-tabwidth} is the output tab character's width (default
2695 @opindex --join-lines
2696 Merge lines of full length. Used together with the column options
2697 @option{-@var{column}}, @option{-a -@var{column}} or @option{-m}. Turns off
2698 @option{-W/-w} line truncation;
2699 no column alignment used; may be used with
2700 @option{--sep-string[=@var{string}]}. @option{-J} has been introduced
2701 (together with @option{-W} and @option{--sep-string})
2702 to disentangle the old (POSIX-compliant) options @option{-w} and
2703 @option{-s} along with the three column options.
2706 @item -l @var{page_length}
2707 @itemx --length=@var{page_length}
2710 Set the page length to @var{page_length} (default 66) lines, including
2711 the lines of the header [and the footer]. If @var{page_length} is less
2712 than or equal to 10, the header and footer are omitted, as if the
2713 @option{-t} option had been given.
2719 Merge and print all @var{file}s in parallel, one in each column. If a
2720 line is too long to fit in a column, it is truncated, unless the @option{-J}
2721 option is used. @option{--sep-string[=@var{string}]} may be used.
2723 some @var{file}s (form feeds set) produce empty columns, still marked
2724 by @var{string}. The result is a continuous line numbering and column
2725 marking throughout the whole merged file. Completely empty merged pages
2726 show no separators or line numbers. The default header becomes
2727 @samp{@var{date} @var{page}} with spaces inserted in the middle; this
2728 may be used with the @option{-h} or @option{--header} option to fill up
2729 the middle blank part.
2731 @item -n[@var{number-separator}[@var{digits}]]
2732 @itemx --number-lines[=@var{number-separator}[@var{digits}]]
2734 @opindex --number-lines
2735 Provide @var{digits} digit line numbering (default for @var{digits} is
2736 5). With multicolumn output the number occupies the first @var{digits}
2737 column positions of each text column or only each line of @option{-m}
2738 output. With single column output the number precedes each line just as
2739 @option{-m} does. Default counting of the line numbers starts with the
2740 first line of the input file (not the first line printed, compare the
2741 @option{--page} option and @option{-N} option).
2742 Optional argument @var{number-separator} is the character appended to
2743 the line number to separate it from the text followed. The default
2744 separator is the TAB character. In a strict sense a TAB is always
2745 printed with single column output only. The TAB width varies
2746 with the TAB position, e.g., with the left @var{margin} specified
2747 by @option{-o} option. With multicolumn output priority is given to
2748 @samp{equal width of output columns} (a POSIX specification).
2749 The TAB width is fixed to the value of the first column and does
2750 not change with different values of left @var{margin}. That means a
2751 fixed number of spaces is always printed in the place of the
2752 @var{number-separator} TAB@. The tabification depends upon the output
2755 @item -N @var{line_number}
2756 @itemx --first-line-number=@var{line_number}
2758 @opindex --first-line-number
2759 Start line counting with the number @var{line_number} at first line of
2760 first page printed (in most cases not the first line of the input file).
2762 @item -o @var{margin}
2763 @itemx --indent=@var{margin}
2766 @cindex indenting lines
2768 Indent each line with a margin @var{margin} spaces wide (default is zero).
2769 The total page width is the size of the margin plus the @var{page_width}
2770 set with the @option{-W/-w} option. A limited overflow may occur with
2771 numbered single column output (compare @option{-n} option).
2774 @itemx --no-file-warnings
2776 @opindex --no-file-warnings
2777 Do not print a warning message when an argument @var{file} cannot be
2778 opened. (The exit status will still be nonzero, however.)
2780 @item -s[@var{char}]
2781 @itemx --separator[=@var{char}]
2783 @opindex --separator
2784 Separate columns by a single character @var{char}. The default for
2785 @var{char} is the TAB character without @option{-w} and @samp{no
2786 character} with @option{-w}. Without @option{-s} the default separator
2787 @samp{space} is set. @option{-s[char]} turns off line truncation of all
2788 three column options (@option{-COLUMN}|@option{-a -COLUMN}|@option{-m}) unless
2789 @option{-w} is set. This is a POSIX-compliant formulation.
2792 @item -S[@var{string}]
2793 @itemx --sep-string[=@var{string}]
2795 @opindex --sep-string
2796 Use @var{string} to separate output columns. The @option{-S} option doesn't
2797 affect the @option{-W/-w} option, unlike the @option{-s} option which does. It
2798 does not affect line truncation or column alignment.
2799 Without @option{-S}, and with @option{-J}, @command{pr} uses the default output
2801 Without @option{-S} or @option{-J}, @command{pr} uses a @samp{space}
2802 (same as @option{-S"@w{ }"}).
2803 If no @samp{@var{string}} argument is specified, @samp{""} is assumed.
2806 @itemx --omit-header
2808 @opindex --omit-header
2809 Do not print the usual header [and footer] on each page, and do not fill
2810 out the bottom of pages (with blank lines or a form feed). No page
2811 structure is produced, but form feeds set in the input files are retained.
2812 The predefined pagination is not changed. @option{-t} or @option{-T} may be
2813 useful together with other options; e.g.: @option{-t -e4}, expand TAB characters
2814 in the input file to 4 spaces but don't make any other changes. Use of
2815 @option{-t} overrides @option{-h}.
2818 @itemx --omit-pagination
2820 @opindex --omit-pagination
2821 Do not print header [and footer]. In addition eliminate all form feeds
2822 set in the input files.
2825 @itemx --show-nonprinting
2827 @opindex --show-nonprinting
2828 Print nonprinting characters in octal backslash notation.
2830 @item -w @var{page_width}
2831 @itemx --width=@var{page_width}
2834 Set page width to @var{page_width} characters for multiple text-column
2835 output only (default for @var{page_width} is 72). The specified
2836 @var{page_width} is rounded down so that columns have equal width.
2837 @option{-s[CHAR]} turns off the default page width and any line truncation
2838 and column alignment.
2839 Lines of full length are merged, regardless of the column options
2840 set. No @var{page_width} setting is possible with single column output.
2841 A POSIX-compliant formulation.
2843 @item -W @var{page_width}
2844 @itemx --page_width=@var{page_width}
2846 @opindex --page_width
2847 Set the page width to @var{page_width} characters, honored with and
2848 without a column option. With a column option, the specified @var{page_width}
2849 is rounded down so that columns have equal width. Text lines are truncated,
2850 unless @option{-J} is used. Together with one of the three column options
2851 (@option{-@var{column}}, @option{-a -@var{column}} or @option{-m}) column
2852 alignment is always used. The separator options @option{-S} or @option{-s}
2853 don't disable the @option{-W} option. Default is 72 characters. Without
2854 @option{-W @var{page_width}} and without any of the column options NO line
2855 truncation is used (defined to keep downward compatibility and to meet
2856 most frequent tasks). That's equivalent to @option{-W 72 -J}@. The header
2857 line is never truncated.
2864 @node fold invocation
2865 @section @command{fold}: Wrap input lines to fit in specified width
2868 @cindex wrapping long input lines
2869 @cindex folding long input lines
2871 @command{fold} writes each @var{file} (@option{-} means standard input), or
2872 standard input if none are given, to standard output, breaking long
2876 fold [@var{option}]@dots{} [@var{file}]@dots{}
2879 By default, @command{fold} breaks lines wider than 80 columns. The output
2880 is split into as many lines as necessary.
2882 @cindex screen columns
2883 @command{fold} counts screen columns by default; thus, a tab may count more
2884 than one column, backspace decreases the column count, and carriage
2885 return sets the column to zero.
2887 The program accepts the following options. Also see @ref{Common options}.
2895 Count bytes rather than columns, so that tabs, backspaces, and carriage
2896 returns are each counted as taking up one column, just like other
2903 Break at word boundaries: the line is broken after the last blank before
2904 the maximum line length. If the line contains no such blanks, the line
2905 is broken at the maximum line length as usual.
2907 @item -w @var{width}
2908 @itemx --width=@var{width}
2911 Use a maximum line length of @var{width} columns instead of 80.
2913 For compatibility @command{fold} supports an obsolete option syntax
2914 @option{-@var{width}}. New scripts should use @option{-w @var{width}}
2922 @node Output of parts of files
2923 @chapter Output of parts of files
2925 @cindex output of parts of files
2926 @cindex parts of files, output of
2928 These commands output pieces of the input.
2931 * head invocation:: Output the first part of files.
2932 * tail invocation:: Output the last part of files.
2933 * split invocation:: Split a file into pieces.
2934 * csplit invocation:: Split a file into context-determined pieces.
2937 @node head invocation
2938 @section @command{head}: Output the first part of files
2941 @cindex initial part of files, outputting
2942 @cindex first part of files, outputting
2944 @command{head} prints the first part (10 lines by default) of each
2945 @var{file}; it reads from standard input if no files are given or
2946 when given a @var{file} of @option{-}. Synopsis:
2949 head [@var{option}]@dots{} [@var{file}]@dots{}
2952 If more than one @var{file} is specified, @command{head} prints a
2953 one-line header consisting of:
2956 ==> @var{file name} <==
2960 before the output for each @var{file}.
2962 The program accepts the following options. Also see @ref{Common options}.
2966 @item -c [-]@var{num}
2967 @itemx --bytes=[-]@var{num}
2970 Print the first @var{num} bytes, instead of initial lines.
2971 However, if @var{num} is prefixed with a @samp{-},
2972 print all but the last @var{num} bytes of each file.
2973 @multiplierSuffixes{num}
2975 @item -n [-]@var{num}
2976 @itemx --lines=[-]@var{num}
2979 Output the first @var{num} lines.
2980 However, if @var{num} is prefixed with a @samp{-},
2981 print all but the last @var{num} lines of each file.
2982 Size multiplier suffixes are the same as with the @option{-c} option.
2990 Never print file name headers.
2996 Always print file name headers.
3002 For compatibility @command{head} also supports an obsolete option syntax
3003 @option{-[@var{num}][bkm][cqv]}, which is recognized only if it is
3004 specified first. @var{num} is a decimal number optionally followed
3005 by a size letter (@samp{b}, @samp{k}, @samp{m}) as in @option{-c}, or
3006 @samp{l} to mean count by lines, or other option letters (@samp{cqv}).
3007 Scripts intended for standard hosts should use @option{-c @var{num}}
3008 or @option{-n @var{num}} instead. If your script must also run on
3009 hosts that support only the obsolete syntax, it is usually simpler to
3010 avoid @command{head}, e.g., by using @samp{sed 5q} instead of
3016 @node tail invocation
3017 @section @command{tail}: Output the last part of files
3020 @cindex last part of files, outputting
3022 @command{tail} prints the last part (10 lines by default) of each
3023 @var{file}; it reads from standard input if no files are given or
3024 when given a @var{file} of @samp{-}. Synopsis:
3027 tail [@var{option}]@dots{} [@var{file}]@dots{}
3030 If more than one @var{file} is specified, @command{tail} prints a
3031 one-line header before the output for each @var{file}, consisting of:
3034 ==> @var{file name} <==
3037 For further processing of tail output, it can be useful to convert the
3038 file headers to line prefixes, which can be done like:
3043 /^==> .* <==$/ @{prefix=substr($0,5,length-8)":"; next@}
3048 @cindex BSD @command{tail}
3049 GNU @command{tail} can output any amount of data (some other versions of
3050 @command{tail} cannot). It also has no @option{-r} option (print in
3051 reverse), since reversing a file is really a different job from printing
3052 the end of a file; BSD @command{tail} (which is the one with @option{-r}) can
3053 only reverse files that are at most as large as its buffer, which is
3054 typically 32 KiB@. A more reliable and versatile way to reverse files is
3055 the GNU @command{tac} command.
3057 The program accepts the following options. Also see @ref{Common options}.
3061 @item -c [+]@var{num}
3062 @itemx --bytes=[+]@var{num}
3065 Output the last @var{num} bytes, instead of final lines.
3066 However, if @var{num} is prefixed with a @samp{+}, start printing with
3067 byte @var{num} from the start of each file, instead of from the end.
3068 @multiplierSuffixes{num}
3071 @itemx --follow[=@var{how}]
3074 @cindex growing files
3075 @vindex name @r{follow option}
3076 @vindex descriptor @r{follow option}
3077 Loop forever trying to read more characters at the end of the file,
3078 presumably because the file is growing.
3079 If more than one file is given, @command{tail} prints a header whenever it
3080 gets output from a different file, to indicate which file that output is
3083 There are two ways to specify how you'd like to track files with this option,
3084 but that difference is noticeable only when a followed file is removed or
3086 If you'd like to continue to track the end of a growing file even after
3087 it has been unlinked, use @option{--follow=descriptor}. This is the default
3088 behavior, but it is not useful if you're tracking a log file that may be
3089 rotated (removed or renamed, then reopened). In that case, use
3090 @option{--follow=name} to track the named file, perhaps by reopening it
3091 periodically to see if it has been removed and recreated by some other program.
3092 Note that the inotify-based implementation handles this case without
3093 the need for any periodic reopening.
3095 No matter which method you use, if the tracked file is determined to have
3096 shrunk, @command{tail} prints a message saying the file has been truncated
3097 and resumes tracking from the start of the file, assuming it has been
3098 truncated to 0, which is the usual truncation operation for log files.
3100 When a file is removed, @command{tail}'s behavior depends on whether it is
3101 following the name or the descriptor. When following by name, tail can
3102 detect that a file has been removed and gives a message to that effect,
3103 and if @option{--retry} has been specified it will continue checking
3104 periodically to see if the file reappears.
3105 When following a descriptor, tail does not detect that the file has
3106 been unlinked or renamed and issues no message; even though the file
3107 may no longer be accessible via its original name, it may still be
3110 The option values @samp{descriptor} and @samp{name} may be specified only
3111 with the long form of the option, not with @option{-f}.
3113 The @option{-f} option is ignored if
3114 no @var{file} operand is specified and standard input is a FIFO or a pipe.
3115 Likewise, the @option{-f} option has no effect for any
3116 operand specified as @samp{-}, when standard input is a FIFO or a pipe.
3118 With kernel inotify support, output is triggered by file changes
3119 and is generally very prompt.
3120 Otherwise, @command{tail} sleeps for one second between checks---
3121 use @option{--sleep-interval=@var{n}} to change that default---which can
3122 make the output appear slightly less responsive or bursty.
3123 When using tail without inotify support, you can make it more responsive
3124 by using a sub-second sleep interval, e.g., via an alias like this:
3127 alias tail='tail -s.1'
3132 This option is the same as @option{--follow=name --retry}. That is, tail
3133 will attempt to reopen a file when it is removed. Should this fail, tail
3134 will keep trying until it becomes accessible again.
3136 @item --max-unchanged-stats=@var{n}
3137 @opindex --max-unchanged-stats
3138 When tailing a file by name, if there have been @var{n} (default
3139 n=@value{DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS}) consecutive
3140 iterations for which the file has not changed, then
3141 @code{open}/@code{fstat} the file to determine if that file name is
3142 still associated with the same device/inode-number pair as before.
3143 When following a log file that is rotated, this is approximately the
3144 number of seconds between when tail prints the last pre-rotation lines
3145 and when it prints the lines that have accumulated in the new log file.
3146 This option is meaningful only when polling (i.e., without inotify)
3147 and when following by name.
3149 @item -n [+]@var{num}
3150 @itemx --lines=[+]@var{}
3153 Output the last @var{num} lines.
3154 However, if @var{num} is prefixed with a @samp{+}, start printing with
3155 line @var{num} from the start of each file, instead of from the end.
3156 Size multiplier suffixes are the same as with the @option{-c} option.
3158 @item --pid=@var{pid}
3160 When following by name or by descriptor, you may specify the process ID,
3161 @var{pid}, of the sole writer of all @var{file} arguments. Then, shortly
3162 after that process terminates, tail will also terminate. This will
3163 work properly only if the writer and the tailing process are running on
3164 the same machine. For example, to save the output of a build in a file
3165 and to watch the file grow, if you invoke @command{make} and @command{tail}
3166 like this then the tail process will stop when your build completes.
3167 Without this option, you would have had to kill the @code{tail -f}
3171 $ make >& makerr & tail --pid=$! -f makerr
3174 If you specify a @var{pid} that is not in use or that does not correspond
3175 to the process that is writing to the tailed files, then @command{tail}
3176 may terminate long before any @var{file}s stop growing or it may not
3177 terminate until long after the real writer has terminated.
3178 Note that @option{--pid} cannot be supported on some systems; @command{tail}
3179 will print a warning if this is the case.
3187 Never print file name headers.
3191 Indefinitely try to open the specified file.
3192 This option is useful mainly when following (and otherwise issues a warning).
3194 When following by file descriptor (i.e., with @option{--follow=descriptor}),
3195 this option only affects the initial open of the file, as after a successful
3196 open, @command{tail} will start following the file descriptor.
3198 When following by name (i.e., with @option{--follow=name}), @command{tail}
3199 infinitely retries to re-open the given files until killed.
3201 Without this option, when @command{tail} encounters a file that doesn't
3202 exist or is otherwise inaccessible, it reports that fact and
3203 never checks it again.
3205 @item -s @var{number}
3206 @itemx --sleep-interval=@var{number}
3208 @opindex --sleep-interval
3209 Change the number of seconds to wait between iterations (the default is 1.0).
3210 During one iteration, every specified file is checked to see if it has
3212 When @command{tail} uses inotify, this polling-related option
3213 is usually ignored. However, if you also specify @option{--pid=@var{p}},
3214 @command{tail} checks whether process @var{p} is alive at least
3215 every @var{number} seconds.
3216 The @var{number} must be non-negative and can be a floating-point number
3217 in either the current or the C locale. @xref{Floating point}.
3223 Always print file name headers.
3229 For compatibility @command{tail} also supports an obsolete usage
3230 @samp{tail -[@var{num}][bcl][f] [@var{file}]}, which is recognized
3231 only if it does not conflict with the usage described
3232 above. This obsolete form uses exactly one option and at most one
3233 file. In the option, @var{num} is an optional decimal number optionally
3234 followed by a size letter (@samp{b}, @samp{c}, @samp{l}) to mean count
3235 by 512-byte blocks, bytes, or lines, optionally followed by @samp{f}
3236 which has the same meaning as @option{-f}.
3238 @vindex _POSIX2_VERSION
3239 On systems not conforming to POSIX 1003.1-2001, the leading @samp{-}
3240 can be replaced by @samp{+} in the traditional option syntax with the
3241 same meaning as in counts, and on obsolete systems predating POSIX
3242 1003.1-2001 traditional usage overrides normal usage when the two
3243 conflict. This behavior can be controlled with the
3244 @env{_POSIX2_VERSION} environment variable (@pxref{Standards
3247 Scripts intended for use on standard hosts should avoid traditional
3248 syntax and should use @option{-c @var{num}[b]}, @option{-n
3249 @var{num}}, and/or @option{-f} instead. If your script must also
3250 run on hosts that support only the traditional syntax, you can often
3251 rewrite it to avoid problematic usages, e.g., by using @samp{sed -n
3252 '$p'} rather than @samp{tail -1}. If that's not possible, the script
3253 can use a test like @samp{if tail -c +1 </dev/null >/dev/null 2>&1;
3254 then @dots{}} to decide which syntax to use.
3256 Even if your script assumes the standard behavior, you should still
3257 beware usages whose behaviors differ depending on the POSIX
3258 version. For example, avoid @samp{tail - main.c}, since it might be
3259 interpreted as either @samp{tail main.c} or as @samp{tail -- -
3260 main.c}; avoid @samp{tail -c 4}, since it might mean either @samp{tail
3261 -c4} or @samp{tail -c 10 4}; and avoid @samp{tail +4}, since it might
3262 mean either @samp{tail ./+4} or @samp{tail -n +4}.
3267 @node split invocation
3268 @section @command{split}: Split a file into pieces.
3271 @cindex splitting a file into pieces
3272 @cindex pieces, splitting a file into
3274 @command{split} creates output files containing consecutive or interleaved
3275 sections of @var{input} (standard input if none is given or @var{input}
3276 is @samp{-}). Synopsis:
3279 split [@var{option}] [@var{input} [@var{prefix}]]
3282 By default, @command{split} puts 1000 lines of @var{input} (or whatever is
3283 left over for the last section), into each output file.
3285 @cindex output file name prefix
3286 The output files' names consist of @var{prefix} (@samp{x} by default)
3287 followed by a group of characters (@samp{aa}, @samp{ab}, @dots{} by
3288 default), such that concatenating the output files in traditional
3289 sorted order by file name produces the original input file (except
3290 @option{-nr/@var{n}}). By default split will initially create files
3291 with two generated suffix characters, and will increase this width by two
3292 when the next most significant position reaches the last character.
3293 (@samp{yz}, @samp{zaaa}, @samp{zaab}, @dots{}). In this way an arbitrary
3294 number of output files are supported, which sort as described above,
3295 even in the presence of an @option{--additional-suffix} option.
3296 If the @option{-a} option is specified and the output file names are
3297 exhausted, @command{split} reports an error without deleting the
3298 output files that it did create.
3300 The program accepts the following options. Also see @ref{Common options}.
3304 @item -l @var{lines}
3305 @itemx --lines=@var{lines}
3308 Put @var{lines} lines of @var{input} into each output file.
3309 If @option{--separator} is specified, then @var{lines} determines
3310 the number of records.
3312 For compatibility @command{split} also supports an obsolete
3313 option syntax @option{-@var{lines}}. New scripts should use
3314 @option{-l @var{lines}} instead.
3317 @itemx --bytes=@var{size}
3320 Put @var{size} bytes of @var{input} into each output file.
3321 @multiplierSuffixes{size}
3324 @itemx --line-bytes=@var{size}
3326 @opindex --line-bytes
3327 Put into each output file as many complete lines of @var{input} as
3328 possible without exceeding @var{size} bytes. Individual lines or records
3329 longer than @var{size} bytes are broken into multiple files.
3330 @var{size} has the same format as for the @option{--bytes} option.
3331 If @option{--separator} is specified, then @var{lines} determines
3332 the number of records.
3334 @item --filter=@var{command}
3336 With this option, rather than simply writing to each output file,
3337 write through a pipe to the specified shell @var{command} for each output file.
3338 @var{command} should use the $FILE environment variable, which is set
3339 to a different output file name for each invocation of the command.
3340 For example, imagine that you have a 1TiB compressed file
3341 that, if uncompressed, would be too large to reside on secondary storage,
3342 yet you must split it into individually-compressed pieces
3343 of a more manageable size.
3344 To do that, you might run this command:
3347 xz -dc BIG.xz | split -b200G --filter='xz > $FILE.xz' - big-
3350 Assuming a 10:1 compression ratio, that would create about fifty 20GiB files
3351 with names @file{big-aa.xz}, @file{big-ab.xz}, @file{big-ac.xz}, etc.
3353 @item -n @var{chunks}
3354 @itemx --number=@var{chunks}
3358 Split @var{input} to @var{chunks} output files where @var{chunks} may be:
3361 @var{n} generate @var{n} files based on current size of @var{input}
3362 @var{k}/@var{n} output only @var{k}th of @var{n} to standard output
3363 l/@var{n} generate @var{n} files without splitting lines or records
3364 l/@var{k}/@var{n} likewise but output only @var{k}th of @var{n} to stdout
3365 r/@var{n} like @samp{l} but use round robin distribution
3366 r/@var{k}/@var{n} likewise but output only @var{k}th of @var{n} to stdout
3369 Any excess bytes remaining after dividing the @var{input}
3370 into @var{n} chunks, are assigned to the last chunk.
3371 Any excess bytes appearing after the initial calculation are discarded
3372 (except when using @samp{r} mode).
3374 All @var{n} files are created even if there are fewer than @var{n} lines,
3375 or the @var{input} is truncated.
3377 For @samp{l} mode, chunks are approximately @var{input} size / @var{n}.
3378 The @var{input} is partitioned into @var{n} equal sized portions, with
3379 the last assigned any excess. If a line @emph{starts} within a partition
3380 it is written completely to the corresponding file. Since lines or records
3381 are not split even if they overlap a partition, the files written
3382 can be larger or smaller than the partition size, and even empty
3383 if a line/record is so long as to completely overlap the partition.
3385 For @samp{r} mode, the size of @var{input} is irrelevant,
3386 and so can be a pipe for example.
3388 @item -a @var{length}
3389 @itemx --suffix-length=@var{length}
3391 @opindex --suffix-length
3392 Use suffixes of length @var{length}. If a @var{length} of 0 is specified,
3393 this is the same as if (any previous) @option{-a} was not specified, and
3394 thus enables the default behavior, which starts the suffix length at 2,
3395 and unless @option{-n} or @option{--numeric-suffixes=@var{from}} is
3396 specified, will auto increase the length by 2 as required.
3399 @itemx --numeric-suffixes[=@var{from}]
3401 @opindex --numeric-suffixes
3402 Use digits in suffixes rather than lower-case letters. The numerical
3403 suffix counts from @var{from} if specified, 0 otherwise.
3405 @var{from} is supported with the long form option, and is used to either set the
3406 initial suffix for a single run, or to set the suffix offset for independently
3407 split inputs, and consequently the auto suffix length expansion described above
3408 is disabled. Therefore you may also want to use option @option{-a} to allow
3409 suffixes beyond @samp{99}. Note if option @option{--number} is specified and
3410 the number of files is less than @var{from}, a single run is assumed and the
3411 minimum suffix length required is automatically determined.
3414 @itemx --hex-suffixes[=@var{from}]
3416 @opindex --hex-suffixes
3417 Like @option{--numeric-suffixes}, but use hexadecimal numbers (in lower case).
3419 @item --additional-suffix=@var{suffix}
3420 @opindex --additional-suffix
3421 Append an additional @var{suffix} to output file names. @var{suffix}
3422 must not contain slash.
3425 @itemx --elide-empty-files
3427 @opindex --elide-empty-files
3428 Suppress the generation of zero-length output files. This can happen
3429 with the @option{--number} option if a file is (truncated to be) shorter
3430 than the number requested, or if a line is so long as to completely
3431 span a chunk. The output file sequence numbers, always run consecutively
3432 even when this option is specified.
3434 @item -t @var{separator}
3435 @itemx --separator=@var{separator}
3437 @opindex --separator
3438 @cindex line separator character
3439 @cindex record separator character
3440 Use character @var{separator} as the record separator instead of the default
3441 newline character (ASCII LF).
3442 To specify ASCII NUL as the separator, use the two-character string @samp{\0},
3443 e.g., @samp{split -t '\0'}.
3448 @opindex --unbuffered
3449 Immediately copy input to output in @option{--number r/@dots{}} mode,
3450 which is a much slower mode of operation.
3454 Write a diagnostic just before each output file is opened.
3460 Here are a few examples to illustrate how the
3461 @option{--number} (@option{-n}) option works:
3463 Notice how, by default, one line may be split onto two or more:
3466 $ seq -w 6 10 > k; split -n3 k; head xa?
3479 Use the "l/" modifier to suppress that:
3482 $ seq -w 6 10 > k; split -nl/3 k; head xa?
3495 Use the "r/" modifier to distribute lines in a round-robin fashion:
3498 $ seq -w 6 10 > k; split -nr/3 k; head xa?
3511 You can also extract just the Kth chunk.
3512 This extracts and prints just the 7th "chunk" of 33:
3515 $ seq 100 > k; split -nl/7/33 k
3522 @node csplit invocation
3523 @section @command{csplit}: Split a file into context-determined pieces
3526 @cindex context splitting
3527 @cindex splitting a file into pieces by context
3529 @command{csplit} creates zero or more output files containing sections of
3530 @var{input} (standard input if @var{input} is @samp{-}). Synopsis:
3533 csplit [@var{option}]@dots{} @var{input} @var{pattern}@dots{}
3536 The contents of the output files are determined by the @var{pattern}
3537 arguments, as detailed below. An error occurs if a @var{pattern}
3538 argument refers to a nonexistent line of the input file (e.g., if no
3539 remaining line matches a given regular expression). After every
3540 @var{pattern} has been matched, any remaining input is copied into one
3543 By default, @command{csplit} prints the number of bytes written to each
3544 output file after it has been created.
3546 The types of pattern arguments are:
3551 Create an output file containing the input up to but not including line
3552 @var{n} (a positive integer). If followed by a repeat count, also
3553 create an output file containing the next @var{n} lines of the input
3554 file once for each repeat.
3556 @item /@var{regexp}/[@var{offset}]
3557 Create an output file containing the current line up to (but not
3558 including) the next line of the input file that contains a match for
3559 @var{regexp}. The optional @var{offset} is an integer, that can
3560 be preceded by @samp{+} or @samp{-}.
3561 If it is given, the input up to (but not including) the
3562 matching line plus or minus @var{offset} is put into the output file,
3563 and the line after that begins the next section of input.
3564 Note lines within a negative offset of a regexp pattern
3565 are not matched in subsequent regexp patterns.
3567 @item %@var{regexp}%[@var{offset}]
3568 Like the previous type, except that it does not create an output
3569 file, so that section of the input file is effectively ignored.
3571 @item @{@var{repeat-count}@}
3572 Repeat the previous pattern @var{repeat-count} additional
3573 times. The @var{repeat-count} can either be a positive integer or an
3574 asterisk, meaning repeat as many times as necessary until the input is
3579 The output files' names consist of a prefix (@samp{xx} by default)
3580 followed by a suffix. By default, the suffix is an ascending sequence
3581 of two-digit decimal numbers from @samp{00} to @samp{99}. In any case,
3582 concatenating the output files in sorted order by file name produces the
3583 original input file, excluding portions skipped with a %@var{regexp}%
3584 pattern or the @option{--suppress-matched} option.
3586 By default, if @command{csplit} encounters an error or receives a hangup,
3587 interrupt, quit, or terminate signal, it removes any output files
3588 that it has created so far before it exits.
3590 The program accepts the following options. Also see @ref{Common options}.
3594 @item -f @var{prefix}
3595 @itemx --prefix=@var{prefix}
3598 @cindex output file name prefix
3599 Use @var{prefix} as the output file name prefix.
3601 @item -b @var{format}
3602 @itemx --suffix-format=@var{format}
3604 @opindex --suffix-format
3605 @cindex output file name suffix
3606 Use @var{format} as the output file name suffix. When this option is
3607 specified, the suffix string must include exactly one
3608 @code{printf(3)}-style conversion specification, possibly including
3609 format specification flags, a field width, a precision specification,
3610 or all of these kinds of modifiers. The format letter must convert a
3611 binary unsigned integer argument to readable form. The format letters
3612 @samp{d} and @samp{i} are aliases for @samp{u}, and the
3613 @samp{u}, @samp{o}, @samp{x}, and @samp{X} conversions are allowed. The
3614 entire @var{format} is given (with the current output file number) to
3615 @code{sprintf(3)} to form the file name suffixes for each of the
3616 individual output files in turn. If this option is used, the
3617 @option{--digits} option is ignored.
3619 @item -n @var{digits}
3620 @itemx --digits=@var{digits}
3623 Use output file names containing numbers that are @var{digits} digits
3624 long instead of the default 2.
3629 @opindex --keep-files
3630 Do not remove output files when errors are encountered.
3632 @item --suppress-matched
3633 @opindex --suppress-matched
3634 Do not output lines matching the specified @var{pattern}.
3635 I.e., suppress the boundary line from the start of the second
3636 and subsequent splits.
3639 @itemx --elide-empty-files
3641 @opindex --elide-empty-files
3642 Suppress the generation of zero-length output files. (In cases where
3643 the section delimiters of the input file are supposed to mark the first
3644 lines of each of the sections, the first output file will generally be a
3645 zero-length file unless you use this option.) The output file sequence
3646 numbers always run consecutively starting from 0, even when this option
3657 Do not print counts of output file sizes.
3663 Here is an example of its usage.
3664 First, create an empty directory for the exercise,
3671 Now, split the sequence of 1..14 on lines that end with 0 or 5:
3674 $ seq 14 | csplit - '/[05]$/' '@{*@}'
3680 Each number printed above is the size of an output
3681 file that csplit has just created.
3682 List the names of those output files:
3689 Use @command{head} to show their contents:
3714 Example of splitting input by empty lines:
3717 $ csplit --suppress-matched @var{input.txt} '/^$/' '@{*@}'
3721 @c TODO: "uniq" already supports "--group".
3722 @c when it gets the "--key" option, uncomment this example.
3724 @c Example of splitting input file, based on the value of column 2:
3727 @c $ cat @var{input.txt} |
3729 @c uniq --group -k2,2 |
3730 @c csplit -m '/^$/' '@{*@}'
3733 @node Summarizing files
3734 @chapter Summarizing files
3736 @cindex summarizing files
3738 These commands generate just a few numbers representing entire
3742 * wc invocation:: Print newline, word, and byte counts.
3743 * sum invocation:: Print checksum and block counts.
3744 * cksum invocation:: Print CRC checksum and byte counts.
3745 * b2sum invocation:: Print or check BLAKE2 digests.
3746 * md5sum invocation:: Print or check MD5 digests.
3747 * sha1sum invocation:: Print or check SHA-1 digests.
3748 * sha2 utilities:: Print or check SHA-2 digests.
3753 @section @command{wc}: Print newline, word, and byte counts
3757 @cindex character count
3761 @command{wc} counts the number of bytes, characters, words, and newlines
3762 in each given @var{file}, or standard input if none are given
3763 or for a @var{file} of @samp{-}. A word is a nonzero length
3764 sequence of printable characters delimited by white space. Synopsis:
3767 wc [@var{option}]@dots{} [@var{file}]@dots{}
3770 @cindex total counts
3771 @command{wc} prints one line of counts for each file, and if the file was
3772 given as an argument, it prints the file name following the counts. If
3773 more than one @var{file} is given, @command{wc} prints a final line
3774 containing the cumulative counts, with the file name @file{total}. The
3775 counts are printed in this order: newlines, words, characters, bytes,
3776 maximum line length.
3777 Each count is printed right-justified in a field with at least one
3778 space between fields so that the numbers and file names normally line
3779 up nicely in columns. The width of the count fields varies depending
3780 on the inputs, so you should not depend on a particular field width.
3781 However, as a GNU extension, if only one count is printed,
3782 it is guaranteed to be printed without leading spaces.
3784 By default, @command{wc} prints three counts: the newline, words, and byte
3785 counts. Options can specify that only certain counts be printed.
3786 Options do not undo others previously given, so
3793 prints both the byte counts and the word counts.
3795 With the @option{--max-line-length} option, @command{wc} prints the length
3796 of the longest line per file, and if there is more than one file it
3797 prints the maximum (not the sum) of those lengths. The line lengths here
3798 are measured in screen columns, according to the current locale and
3799 assuming tab positions in every 8th column.
3801 The program accepts the following options. Also see @ref{Common options}.
3809 Print only the byte counts.
3815 Print only the character counts, as per the current locale.
3816 Invalid characters are not counted.
3822 Print only the word counts. A word is a nonzero length
3823 sequence of printable characters separated by white space.
3829 Print only the newline character counts.
3830 Note a file without a trailing newline character,
3831 will not have that last portion included in the line count.
3834 @itemx --max-line-length
3836 @opindex --max-line-length
3837 Print only the maximum display widths.
3838 Tabs are set at every 8th column.
3839 Display widths of wide characters are considered.
3840 Non-printable characters are given 0 width.
3842 @macro filesZeroFromOption{cmd,withTotalOption,subListOutput}
3843 @item --files0-from=@var{file}
3844 @opindex --files0-from=@var{file}
3845 @c This is commented out to avoid a texi2dvi failure.
3846 @c texi2dvi (GNU Texinfo 4.11) 1.104
3847 @c @cindex including files from @command{\cmd\}
3848 Disallow processing files named on the command line, and instead process
3849 those named in file @var{file}; each name being terminated by a zero byte
3851 This is useful \withTotalOption\
3852 when the list of file names is so long that it may exceed a command line
3854 In such cases, running @command{\cmd\} via @command{xargs} is undesirable
3855 because it splits the list into pieces and makes @command{\cmd\} print
3856 \subListOutput\ for each sublist rather than for the entire list.
3857 One way to produce a list of ASCII NUL terminated file
3859 @command{find}, using its @option{-print0} predicate.
3860 If @var{file} is @samp{-} then the ASCII NUL terminated
3861 file names are read from standard input.
3863 @filesZeroFromOption{wc,,a total}
3865 For example, to find the length of the longest line in any @file{.c} or
3866 @file{.h} file in the current hierarchy, do this:
3869 find . -name '*.[ch]' -print0 |
3870 wc -L --files0-from=- | tail -n1
3878 @node sum invocation
3879 @section @command{sum}: Print checksum and block counts
3882 @cindex 16-bit checksum
3883 @cindex checksum, 16-bit
3885 @command{sum} computes a 16-bit checksum for each given @var{file}, or
3886 standard input if none are given or for a @var{file} of @samp{-}. Synopsis:
3889 sum [@var{option}]@dots{} [@var{file}]@dots{}
3892 @command{sum} prints the checksum for each @var{file} followed by the
3893 number of blocks in the file (rounded up). If at least one @var{file}
3894 is given, file names are also printed.
3896 By default, GNU @command{sum} computes checksums using an algorithm
3897 compatible with BSD @command{sum} and prints file sizes in units of
3900 The program accepts the following options. Also see @ref{Common options}.
3906 @cindex BSD @command{sum}
3907 Use the default (BSD compatible) algorithm. This option is included for
3908 compatibility with the System V @command{sum}. Unless @option{-s} was also
3909 given, it has no effect.
3915 @cindex System V @command{sum}
3916 Compute checksums using an algorithm compatible with System V
3917 @command{sum}'s default, and print file sizes in units of 512-byte blocks.
3921 @command{sum} is provided for compatibility; the @command{cksum} program (see
3922 next section) is preferable in new applications.
3927 @node cksum invocation
3928 @section @command{cksum}: Print and verify file checksums
3931 @cindex cyclic redundancy check
3932 @cindex CRC checksum
3935 @command{cksum} by default computes a cyclic redundancy check (CRC) checksum
3936 for each given @var{file}, or standard input if none are given or for a
3937 @var{file} of @samp{-}.
3939 cksum also supports the @option{-a,--algorithm} option to select the
3940 digest algorithm to use. @command{cksum} is the preferred interface
3941 to these digests, subsuming the other standalone checksumming utilities,
3942 which can be emulated using @code{cksum -a md5 --untagged "$@@"} etc.
3946 cksum [@var{option}]@dots{} [@var{file}]@dots{}
3949 @command{cksum} is typically used to ensure that files have not been corrupted,
3950 by comparing the @command{cksum} output for the received files with the
3951 @command{cksum} output for the original files (typically given in the
3954 @command{cksum} by default prints the POSIX standard CRC checksum
3955 for each file along with the number of bytes in the file,
3956 and the file name unless no arguments were given.
3958 The same usage and options as the @command{b2sum}
3959 command are supported. @xref{b2sum invocation}.
3960 In addition @command{cksum} supports the following options.
3967 @opindex --algorithm
3968 @cindex digest algorithm
3969 Compute checksums using the specified digest algorithm.
3971 Supported legacy checksums (which are not supported by @option{--check}):
3973 @samp{sysv} equivalent to @command{sum -s}
3974 @samp{bsd} equivalent to @command{sum -r}
3975 @samp{crc} equivalent to @command{cksum} (the default)
3978 Supported more modern digest algorithms are:
3980 @samp{md5} equivalent to @command{md5sum}
3981 @samp{sha1} equivalent to @command{sha1sum}
3982 @samp{sha224} equivalent to @command{sha224sum}
3983 @samp{sha256} equivalent to @command{sha256sum}
3984 @samp{sha384} equivalent to @command{sha384sum}
3985 @samp{sha512} equivalent to @command{sha512sum}
3986 @samp{blake2b} equivalent to @command{b2sum}
3987 @samp{sm3} only available through @command{cksum}
3992 Output extra information to stderr, like the checksum implementation being used.
3996 Output using the original Coreutils format used by the other
3997 standalone checksum utilities like @command{md5sum} for example.
3998 This format has the checksum at the start of the line, and may be
3999 more amenable to further processing by other utilities,
4000 especially in combination with the @option{--zero} option.
4001 Note this does not identify the digest algorithm used for the checksum.
4002 @xref{md5sum invocation} for details of this format.
4006 @node b2sum invocation
4007 @section @command{b2sum}: Print or check BLAKE2 digests
4011 @cindex 512-bit checksum
4012 @cindex checksum, 512-bit
4013 @cindex fingerprint, 512-bit
4014 @cindex message-digest, 512-bit
4016 @command{b2sum} computes a 512-bit checksum for each specified
4017 @var{file}. The same usage and options as the @command{md5sum}
4018 command are supported. @xref{md5sum invocation}.
4019 In addition @command{b2sum} supports the following options.
4026 @cindex BLAKE2 hash length
4027 Change (shorten) the default digest length.
4028 This is specified in bits and thus must be a multiple of 8.
4029 This option is ignored when @option{--check} is specified,
4030 as the length is automatically determined when checking.
4033 @node md5sum invocation
4034 @section @command{md5sum}: Print or check MD5 digests
4038 @cindex 128-bit checksum
4039 @cindex checksum, 128-bit
4040 @cindex fingerprint, 128-bit
4041 @cindex message-digest, 128-bit
4043 @command{md5sum} computes a 128-bit checksum (or @dfn{fingerprint} or
4044 @dfn{message-digest}) for each specified @var{file}.
4046 @macro weakHash{hash}
4047 Note: The \hash\ digest is more reliable than a simple CRC (provided by
4048 the @command{cksum} command) for detecting accidental file corruption,
4049 as the chances of accidentally having two files with identical \hash\
4050 are vanishingly small. However, it should not be considered secure
4051 against malicious tampering: although finding a file with a given \hash\
4052 fingerprint is considered infeasible at the moment, it is known how
4053 to modify certain files, including digital certificates, so that they
4054 appear valid when signed with an \hash\ digest. For more secure hashes,
4055 consider using SHA-2, or the newer @command{b2sum} command.
4056 @xref{sha2 utilities}. @xref{b2sum invocation}.
4060 If a @var{file} is specified as @samp{-} or if no files are given
4061 @command{md5sum} computes the checksum for the standard input.
4062 @command{md5sum} can also determine whether a file and checksum are
4063 consistent. Synopsis:
4066 md5sum [@var{option}]@dots{} [@var{file}]@dots{}
4069 For each @var{file}, @samp{md5sum} outputs by default, the MD5 checksum,
4070 a space, a flag indicating binary or text input mode, and the file name.
4071 Binary mode is indicated with @samp{*}, text mode with @samp{ } (space).
4072 Binary mode is the default on systems where it's significant,
4073 otherwise text mode is the default. The @command{cksum} command always
4074 uses binary mode and a @samp{ } (space) flag.
4076 Without @option{--zero}, if @var{file} contains a backslash, newline,
4077 or carriage return, the line is started with a backslash, and each
4078 problematic character in the file name is escaped with a backslash,
4079 making the output unambiguous even in the presence of arbitrary file names.
4081 If @var{file} is omitted or specified as @samp{-}, standard input is read.
4083 The program accepts the following options. Also see @ref{Common options}.
4091 @cindex binary input files
4092 Note this option is not supported by the @command{cksum} command,
4093 as it operates in binary mode exclusively.
4094 Treat each input file as binary, by reading it in binary mode and
4095 outputting a @samp{*} flag. This is the inverse of @option{--text}.
4096 On systems like GNU that do not distinguish between binary
4097 and text files, this option merely flags each input mode as binary:
4098 the MD5 checksum is unaffected. This option is the default on systems
4099 like MS-DOS that distinguish between binary and text files, except
4100 for reading standard input when standard input is a terminal.
4104 Read file names and checksum information (not data) from each
4105 @var{file} (or from standard input if no @var{file} was specified) and report
4106 whether the checksums match the contents of the named files.
4107 The input to this mode of @command{md5sum} is usually the output of
4108 a prior, checksum-generating run of @samp{md5sum}.
4110 Three input formats are supported. Either the default output
4111 format described above, the @option{--tag} output format,
4112 or the BSD reversed mode format which is similar to the default mode,
4113 but doesn't use a character to distinguish binary and text modes.
4115 For the @command{cksum} command, the @option{--check} option
4116 supports auto-detecting the digest algorithm to use,
4117 when presented with checksum information in the @option{--tag} output format.
4119 Output with @option{--zero} enabled is not supported by @option{--check}.
4121 For each such line, @command{md5sum} reads the named file and computes its
4122 MD5 checksum. Then, if the computed message digest does not match the
4123 one on the line with the file name, the file is noted as having
4124 failed the test. Otherwise, the file passes the test.
4125 By default, for each valid line, one line is written to standard
4126 output indicating whether the named file passed the test.
4127 After all checks have been performed, if there were any failures,
4128 a warning is issued to standard error.
4129 Use the @option{--status} option to inhibit that output.
4130 If any listed file cannot be opened or read, if any valid line has
4131 an MD5 checksum inconsistent with the associated file, or if no valid
4132 line is found, @command{md5sum} exits with nonzero status. Otherwise,
4133 it exits successfully.
4134 Note the @command{cksum} command doesn't support @option{--check}
4135 with the older @samp{sysv}, @samp{bsd}, or @samp{crc} algorithms.
4137 @item --ignore-missing
4138 @opindex --ignore-missing
4139 @cindex verifying MD5 checksums
4140 This option is useful only when verifying checksums.
4141 When verifying checksums, don't fail or report any status
4142 for missing files. This is useful when verifying a subset
4143 of downloaded files given a larger list of checksums.
4147 @cindex verifying MD5 checksums
4148 This option is useful only when verifying checksums.
4149 When verifying checksums, don't generate an 'OK' message per successfully
4150 checked file. Files that fail the verification are reported in the
4151 default one-line-per-file format. If there is any checksum mismatch,
4152 print a warning summarizing the failures to standard error.
4156 @cindex verifying MD5 checksums
4157 This option is useful only when verifying checksums.
4158 When verifying checksums, don't generate the default one-line-per-file
4159 diagnostic and don't output the warning summarizing any failures.
4160 Failures to open or read a file still evoke individual diagnostics to
4162 If all listed files are readable and are consistent with the associated
4163 MD5 checksums, exit successfully. Otherwise exit with a status code
4164 indicating there was a failure.
4169 Output BSD style checksums, which indicate the checksum algorithm used.
4170 As a GNU extension, if @option{--zero} is not used, file names with problematic
4171 characters are escaped as described above, with the same escaping indicator of
4172 @samp{\} at the start of the line, being used.
4173 The @option{--tag} option implies binary mode, and is disallowed with
4174 @option{--text} mode as supporting that would unnecessarily complicate
4175 the output format, while providing little benefit.
4176 The @command{cksum} command, uses @option{--tag} as its default output format.
4182 @cindex text input files
4183 Note this option is not supported by the @command{cksum} command.
4184 Treat each input file as text, by reading it in text mode and
4185 outputting a @samp{ } flag. This is the inverse of @option{--binary}.
4186 This option is the default on systems like GNU that do not
4187 distinguish between binary and text files. On other systems, it is
4188 the default for reading standard input when standard input is a
4189 terminal. This mode is never defaulted to if @option{--tag} is used.
4195 @cindex verifying MD5 checksums
4196 When verifying checksums, warn about improperly formatted MD5 checksum lines.
4197 This option is useful only if all but a few lines in the checked input
4202 @cindex verifying MD5 checksums
4203 When verifying checksums,
4204 if one or more input line is invalid,
4205 exit nonzero after all warnings have been issued.
4208 Also file name escaping is not used.
4214 @node sha1sum invocation
4215 @section @command{sha1sum}: Print or check SHA-1 digests
4219 @cindex 160-bit checksum
4220 @cindex checksum, 160-bit
4221 @cindex fingerprint, 160-bit
4222 @cindex message-digest, 160-bit
4224 @command{sha1sum} computes a 160-bit checksum for each specified
4225 @var{file}. The usage and options of this command are precisely the
4226 same as for @command{md5sum}. @xref{md5sum invocation}.
4231 @node sha2 utilities
4232 @section sha2 utilities: Print or check SHA-2 digests
4239 @cindex 224-bit checksum
4240 @cindex 256-bit checksum
4241 @cindex 384-bit checksum
4242 @cindex 512-bit checksum
4243 @cindex checksum, 224-bit
4244 @cindex checksum, 256-bit
4245 @cindex checksum, 384-bit
4246 @cindex checksum, 512-bit
4247 @cindex fingerprint, 224-bit
4248 @cindex fingerprint, 256-bit
4249 @cindex fingerprint, 384-bit
4250 @cindex fingerprint, 512-bit
4251 @cindex message-digest, 224-bit
4252 @cindex message-digest, 256-bit
4253 @cindex message-digest, 384-bit
4254 @cindex message-digest, 512-bit
4256 The commands @command{sha224sum}, @command{sha256sum},
4257 @command{sha384sum} and @command{sha512sum} compute checksums of
4258 various lengths (respectively 224, 256, 384 and 512 bits),
4259 collectively known as the SHA-2 hashes. The usage and options of
4260 these commands are precisely the same as for @command{md5sum}
4261 and @command{sha1sum}.
4262 @xref{md5sum invocation}.
4265 @node Operating on sorted files
4266 @chapter Operating on sorted files
4268 @cindex operating on sorted files
4269 @cindex sorted files, operations on
4271 These commands work with (or produce) sorted files.
4274 * sort invocation:: Sort text files.
4275 * shuf invocation:: Shuffle text files.
4276 * uniq invocation:: Uniquify files.
4277 * comm invocation:: Compare two sorted files line by line.
4278 * ptx invocation:: Produce a permuted index of file contents.
4279 * tsort invocation:: Topological sort.
4283 @node sort invocation
4284 @section @command{sort}: Sort text files
4287 @cindex sorting files
4289 @command{sort} sorts, merges, or compares all the lines from the given
4290 files, or standard input if none are given or for a @var{file} of
4291 @samp{-}. By default, @command{sort} writes the results to standard
4295 sort [@var{option}]@dots{} [@var{file}]@dots{}
4298 @cindex sort stability
4299 @cindex sort's last-resort comparison
4300 Many options affect how @command{sort} compares lines; if the results
4301 are unexpected, try the @option{--debug} option to see what happened.
4302 A pair of lines is compared as follows:
4303 @command{sort} compares each pair of fields (see @option{--key}), in the
4304 order specified on the command line, according to the associated
4305 ordering options, until a difference is found or no fields are left.
4306 If no key fields are specified, @command{sort} uses a default key of
4307 the entire line. Finally, as a last resort when all keys compare
4308 equal, @command{sort} compares entire lines as if no ordering options
4309 other than @option{--reverse} (@option{-r}) were specified. The
4310 @option{--stable} (@option{-s}) option disables this @dfn{last-resort
4311 comparison} so that lines in which all fields compare equal are left
4312 in their original relative order. The @option{--unique}
4313 (@option{-u}) option also disables the last-resort comparison.
4317 Unless otherwise specified, all comparisons use the character collating
4318 sequence specified by the @env{LC_COLLATE} locale.@footnote{If you
4319 use a non-POSIX locale (e.g., by setting @env{LC_ALL}
4320 to @samp{en_US}), then @command{sort} may produce output that is sorted
4321 differently than you're accustomed to. In that case, set the @env{LC_ALL}
4322 environment variable to @samp{C}@. Note that setting only @env{LC_COLLATE}
4323 has two problems. First, it is ineffective if @env{LC_ALL} is also set.
4324 Second, it has undefined behavior if @env{LC_CTYPE} (or @env{LANG}, if
4325 @env{LC_CTYPE} is unset) is set to an incompatible value. For example,
4326 you get undefined behavior if @env{LC_CTYPE} is @code{ja_JP.PCK} but
4327 @env{LC_COLLATE} is @code{en_US.UTF-8}.}
4328 A line's trailing newline is not part of the line for comparison
4329 purposes. If the final byte of an input file is not a newline, GNU
4330 @command{sort} silently supplies one. GNU @command{sort} (as
4331 specified for all GNU utilities) has no limit on input line length or
4332 restrictions on bytes allowed within lines.
4334 @command{sort} has three modes of operation: sort (the default), merge,
4335 and check for sortedness. The following options change the operation
4342 @itemx --check=diagnose-first
4345 @cindex checking for sortedness
4346 Check whether the given file is already sorted: if it is not all
4347 sorted, print a diagnostic containing the first out-of-order line and
4348 exit with a status of 1.
4349 Otherwise, exit successfully.
4350 At most one input file can be given.
4353 @itemx --check=quiet
4354 @itemx --check=silent
4357 @cindex checking for sortedness
4358 Exit successfully if the given file is already sorted, and
4359 exit with status 1 otherwise.
4360 At most one input file can be given.
4361 This is like @option{-c}, except it does not print a diagnostic.
4367 @cindex merging sorted files
4368 Merge the given files by sorting them as a group. Each input file must
4369 always be individually sorted. It always works to sort instead of
4370 merge; merging is provided because it is faster, in the case where it
4375 @cindex exit status of @command{sort}
4379 0 if no error occurred
4380 1 if invoked with @option{-c} or @option{-C} and the input is not sorted
4381 2 if an error occurred
4385 If the environment variable @env{TMPDIR} is set, @command{sort} uses its
4386 value as the directory for temporary files instead of @file{/tmp}. The
4387 @option{--temporary-directory} (@option{-T}) option in turn overrides
4388 the environment variable.
4390 The following options affect the ordering of output lines. They may be
4391 specified globally or as part of a specific key field. If no key
4392 fields are specified, global options apply to comparison of entire
4393 lines; otherwise the global options are inherited by key fields that do
4394 not specify any special options of their own. In pre-POSIX
4395 versions of @command{sort}, global options affect only later key fields,
4396 so portable shell scripts should specify global options first.
4401 @itemx --ignore-leading-blanks
4403 @opindex --ignore-leading-blanks
4404 @cindex blanks, ignoring leading
4406 Ignore leading blanks when finding sort keys in each line.
4407 By default a blank is a space or a tab, but the @env{LC_CTYPE} locale
4408 can change this. Note blanks may be ignored by your locale's collating
4409 rules, but without this option they will be significant for character
4410 positions specified in keys with the @option{-k} option.
4413 @itemx --dictionary-order
4415 @opindex --dictionary-order
4416 @cindex dictionary order
4417 @cindex phone directory order
4418 @cindex telephone directory order
4420 Sort in @dfn{phone directory} order: ignore all characters except
4421 letters, digits and blanks when sorting.
4422 By default letters and digits are those of ASCII and a blank
4423 is a space or a tab, but the @env{LC_CTYPE} locale can change this.
4426 @itemx --ignore-case
4428 @opindex --ignore-case
4429 @cindex ignoring case
4430 @cindex case folding
4432 Fold lowercase characters into the equivalent uppercase characters when
4433 comparing so that, for example, @samp{b} and @samp{B} sort as equal.
4434 The @env{LC_CTYPE} locale determines character types.
4435 When used with @option{--unique} those lower case equivalent lines are
4436 thrown away. (There is currently no way to throw away the upper case
4437 equivalent instead. (Any @option{--reverse} given would only affect
4438 the final result, after the throwing away.))
4441 @itemx --general-numeric-sort
4442 @itemx --sort=general-numeric
4444 @opindex --general-numeric-sort
4446 @cindex general numeric sort
4448 Sort numerically, converting a prefix of each line to a long
4449 double-precision floating point number. @xref{Floating point}.
4450 Do not report overflow, underflow, or conversion errors.
4451 Use the following collating sequence:
4455 Lines that do not start with numbers (all considered to be equal).
4457 NaNs (``Not a Number'' values, in IEEE floating point arithmetic)
4458 in a consistent but machine-dependent order.
4462 Finite numbers in ascending numeric order (with @math{-0} and @math{+0} equal).
4467 Use this option only if there is no alternative; it is much slower than
4468 @option{--numeric-sort} (@option{-n}) and it can lose information when
4469 converting to floating point.
4471 You can use this option to sort hexadecimal numbers prefixed with
4472 @samp{0x} or @samp{0X}, where those numbers are not fixed width,
4473 or of varying case. However for hex numbers of consistent case,
4474 and left padded with @samp{0} to a consistent width, a standard
4475 lexicographic sort will be faster.
4478 @itemx --human-numeric-sort
4479 @itemx --sort=human-numeric
4481 @opindex --human-numeric-sort
4483 @cindex human numeric sort
4485 Sort numerically, first by numeric sign (negative, zero, or positive);
4486 then by SI suffix (either empty, or @samp{k} or @samp{K}, or
4487 one of @samp{MGTPEZY}, in that order; @pxref{Block size}); and finally
4488 by numeric value. For example, @samp{1023M} sorts before @samp{1G}
4489 because @samp{M} (mega) precedes @samp{G} (giga) as an SI
4490 suffix. This option sorts values that are consistently scaled to the
4491 nearest suffix, regardless of whether suffixes denote powers of 1000
4492 or 1024, and it therefore sorts the output of any single invocation of
4493 the @command{df}, @command{du}, or @command{ls} commands that are
4494 invoked with their @option{--human-readable} or @option{--si} options.
4495 The syntax for numbers is the same as for the @option{--numeric-sort}
4496 option; the SI suffix must immediately follow the number.
4497 Note also the @command{numfmt} command, which can be used to reformat
4498 numbers to human format @emph{after} the sort, thus often allowing
4499 sort to operate on more accurate numbers.
4502 @itemx --ignore-nonprinting
4504 @opindex --ignore-nonprinting
4505 @cindex nonprinting characters, ignoring
4506 @cindex unprintable characters, ignoring
4508 Ignore nonprinting characters.
4509 The @env{LC_CTYPE} locale determines character types.
4510 This option has no effect if the stronger @option{--dictionary-order}
4511 (@option{-d}) option is also given.
4517 @opindex --month-sort
4519 @cindex months, sorting by
4521 An initial string, consisting of any amount of blanks, followed
4522 by a month name abbreviation, is folded to UPPER case and
4523 compared in the order @samp{JAN} < @samp{FEB} < @dots{} < @samp{DEC}@.
4524 Invalid names compare low to valid names. The @env{LC_TIME} locale
4525 category determines the month spellings.
4526 By default a blank is a space or a tab, but the @env{LC_CTYPE} locale
4530 @itemx --numeric-sort
4531 @itemx --sort=numeric
4533 @opindex --numeric-sort
4535 @cindex numeric sort
4537 Sort numerically. The number begins each line and consists
4538 of optional blanks, an optional @samp{-} sign, and zero or more
4539 digits possibly separated by thousands separators, optionally followed
4540 by a decimal-point character and zero or more digits. An empty
4541 number is treated as @samp{0}. The @env{LC_NUMERIC}
4542 locale specifies the decimal-point character and thousands separator.
4543 By default a blank is a space or a tab, but the @env{LC_CTYPE} locale
4546 Comparison is exact; there is no rounding error.
4548 Neither a leading @samp{+} nor exponential notation is recognized.
4549 To compare such strings numerically, use the
4550 @option{--general-numeric-sort} (@option{-g}) option.
4553 @itemx --version-sort
4555 @opindex --version-sort
4556 @cindex version number sort
4557 Sort by version name and number. It behaves like a standard sort,
4558 except that each sequence of decimal digits is treated numerically
4559 as an index/version number. (@xref{Version sort ordering}.)
4565 @cindex reverse sorting
4566 Reverse the result of comparison, so that lines with greater key values
4567 appear earlier in the output instead of later.
4570 @itemx --random-sort
4571 @itemx --sort=random
4573 @opindex --random-sort
4576 Sort by hashing the input keys and then sorting the hash values.
4577 Choose the hash function at random, ensuring that it is free of
4578 collisions so that differing keys have differing hash values. This is
4579 like a random permutation of the inputs (@pxref{shuf invocation}),
4580 except that keys with the same value sort together.
4582 If multiple random sort fields are specified, the same random hash
4583 function is used for all fields. To use different random hash
4584 functions for different fields, you can invoke @command{sort} more
4587 The choice of hash function is affected by the
4588 @option{--random-source} option.
4596 @item --compress-program=@var{prog}
4597 Compress any temporary files with the program @var{prog}.
4599 With no arguments, @var{prog} must compress standard input to standard
4600 output, and when given the @option{-d} option it must decompress
4601 standard input to standard output.
4603 Terminate with an error if @var{prog} exits with nonzero status.
4605 White space and the backslash character should not appear in
4606 @var{prog}; they are reserved for future use.
4608 @filesZeroFromOption{sort,,sorted output}
4610 @item -k @var{pos1}[,@var{pos2}]
4611 @itemx --key=@var{pos1}[,@var{pos2}]
4615 Specify a sort field that consists of the part of the line between
4616 @var{pos1} and @var{pos2} (or the end of the line, if @var{pos2} is
4617 omitted), @emph{inclusive}.
4619 In its simplest form @var{pos} specifies a field number (starting with 1),
4620 with fields being separated by runs of blank characters, and by default
4621 those blanks being included in the comparison at the start of each field.
4622 To adjust the handling of blank characters see the @option{-b} and
4623 @option{-t} options.
4626 each @var{pos} has the form @samp{@var{f}[.@var{c}][@var{opts}]},
4627 where @var{f} is the number of the field to use, and @var{c} is the number
4628 of the first character from the beginning of the field. Fields and character
4629 positions are numbered starting with 1; a character position of zero in
4630 @var{pos2} indicates the field's last character. If @samp{.@var{c}} is
4631 omitted from @var{pos1}, it defaults to 1 (the beginning of the field);
4632 if omitted from @var{pos2}, it defaults to 0 (the end of the field).
4633 @var{opts} are ordering options, allowing individual keys to be sorted
4634 according to different rules; see below for details. Keys can span
4637 Example: To sort on the second field, use @option{--key=2,2}
4638 (@option{-k 2,2}). See below for more notes on keys and more examples.
4639 See also the @option{--debug} option to help determine the part
4640 of the line being used in the sort.
4643 Highlight the portion of each line used for sorting.
4644 Also issue warnings about questionable usage to standard error.
4646 @item --batch-size=@var{nmerge}
4647 @opindex --batch-size
4648 @cindex number of inputs to merge, nmerge
4649 Merge at most @var{nmerge} inputs at once.
4651 When @command{sort} has to merge more than @var{nmerge} inputs,
4652 it merges them in groups of @var{nmerge}, saving the result in
4653 a temporary file, which is then used as an input in a subsequent merge.
4655 A large value of @var{nmerge} may improve merge performance and decrease
4656 temporary storage utilization at the expense of increased memory usage
4657 and I/O@. Conversely a small value of @var{nmerge} may reduce memory
4658 requirements and I/O at the expense of temporary storage consumption and
4661 The value of @var{nmerge} must be at least 2. The default value is
4662 currently 16, but this is implementation-dependent and may change in
4665 The value of @var{nmerge} may be bounded by a resource limit for open
4666 file descriptors. The commands @samp{ulimit -n} or @samp{getconf
4667 OPEN_MAX} may display limits for your systems; these limits may be
4668 modified further if your program already has some files open, or if
4669 the operating system has other limits on the number of open files. If
4670 the value of @var{nmerge} exceeds the resource limit, @command{sort}
4671 silently uses a smaller value.
4673 @item -o @var{output-file}
4674 @itemx --output=@var{output-file}
4677 @cindex overwriting of input, allowed
4678 Write output to @var{output-file} instead of standard output.
4679 Normally, @command{sort} reads all input before opening
4680 @var{output-file}, so you can sort a file in place by using
4681 commands like @code{sort -o F F} and @code{cat F | sort -o F}@.
4682 However, it is often safer to output to an otherwise-unused file, as
4683 data may be lost if the system crashes or @command{sort} encounters
4684 an I/O or other serious error while a file is being sorted in place.
4685 Also, @command{sort} with @option{--merge} (@option{-m}) can open
4686 the output file before reading all input, so a command like @code{cat
4687 F | sort -m -o F - G} is not safe as @command{sort} might start
4688 writing @file{F} before @command{cat} is done reading it.
4690 @vindex POSIXLY_CORRECT
4691 On newer systems, @option{-o} cannot appear after an input file if
4692 @env{POSIXLY_CORRECT} is set, e.g., @samp{sort F -o F}@. Portable
4693 scripts should specify @option{-o @var{output-file}} before any input
4696 @item --random-source=@var{file}
4697 @opindex --random-source
4698 @cindex random source for sorting
4699 Use @var{file} as a source of random data used to determine which
4700 random hash function to use with the @option{-R} option. @xref{Random
4707 @cindex sort stability
4708 @cindex sort's last-resort comparison
4710 Make @command{sort} stable by disabling its last-resort comparison.
4711 This option has no effect if no fields or global ordering options
4712 other than @option{--reverse} (@option{-r}) are specified.
4715 @itemx --buffer-size=@var{size}
4717 @opindex --buffer-size
4718 @cindex size for main memory sorting
4719 Use a main-memory sort buffer of the given @var{size}. By default,
4720 @var{size} is in units of 1024 bytes. Appending @samp{%} causes
4721 @var{size} to be interpreted as a percentage of physical memory.
4722 Appending @samp{K} multiplies @var{size} by 1024 (the default),
4723 @samp{M} by 1,048,576, @samp{G} by 1,073,741,824, and so on for
4724 @samp{T}, @samp{P}, @samp{E}, @samp{Z}, and @samp{Y}@. Appending
4725 @samp{b} causes @var{size} to be interpreted as a byte count, with no
4728 This option can improve the performance of @command{sort} by causing it
4729 to start with a larger or smaller sort buffer than the default.
4730 However, this option affects only the initial buffer size. The buffer
4731 grows beyond @var{size} if @command{sort} encounters input lines larger
4734 @item -t @var{separator}
4735 @itemx --field-separator=@var{separator}
4737 @opindex --field-separator
4738 @cindex field separator character
4739 Use character @var{separator} as the field separator when finding the
4740 sort keys in each line. By default, fields are separated by the empty
4741 string between a non-blank character and a blank character.
4742 By default a blank is a space or a tab, but the @env{LC_CTYPE} locale
4745 That is, given the input line @w{@samp{ foo bar}}, @command{sort} breaks it
4746 into fields @w{@samp{ foo}} and @w{@samp{ bar}}. The field separator is
4747 not considered to be part of either the field preceding or the field
4748 following, so with @samp{sort @w{-t " "}} the same input line has
4749 three fields: an empty field, @samp{foo}, and @samp{bar}.
4750 However, fields that extend to the end of the line,
4751 as @option{-k 2}, or fields consisting of a range, as @option{-k 2,3},
4752 retain the field separators present between the endpoints of the range.
4754 To specify ASCII NUL as the field separator,
4755 use the two-character string @samp{\0}, e.g., @samp{sort -t '\0'}.
4757 @item -T @var{tempdir}
4758 @itemx --temporary-directory=@var{tempdir}
4760 @opindex --temporary-directory
4761 @cindex temporary directory
4763 Use directory @var{tempdir} to store temporary files, overriding the
4764 @env{TMPDIR} environment variable. If this option is given more than
4765 once, temporary files are stored in all the directories given. If you
4766 have a large sort or merge that is I/O-bound, you can often improve
4767 performance by using this option to specify directories on different
4770 @item --parallel=@var{n}
4772 @cindex multithreaded sort
4773 Set the number of sorts run in parallel to @var{n}. By default,
4774 @var{n} is set to the number of available processors, but limited
4775 to 8, as there are diminishing performance gains after that.
4776 Note also that using @var{n} threads increases the memory usage by
4777 a factor of log @var{n}. Also see @ref{nproc invocation}.
4783 @cindex uniquifying output
4785 Normally, output only the first of a sequence of lines that compare
4786 equal. For the @option{--check} (@option{-c} or @option{-C}) option,
4787 check that no pair of consecutive lines compares equal.
4789 This option also disables the default last-resort comparison.
4791 The commands @code{sort -u} and @code{sort | uniq} are equivalent, but
4792 this equivalence does not extend to arbitrary @command{sort} options.
4793 For example, @code{sort -n -u} inspects only the value of the initial
4794 numeric string when checking for uniqueness, whereas @code{sort -n |
4795 uniq} inspects the entire line. @xref{uniq invocation}.
4798 @macro newlineFieldSeparator
4799 Note with @option{-z} the newline character is treated as a field separator.
4804 Historical (BSD and System V) implementations of @command{sort} have
4805 differed in their interpretation of some options, particularly
4806 @option{-b}, @option{-f}, and @option{-n}.
4807 GNU sort follows the POSIX
4808 behavior, which is usually (but not always!) like the System V behavior.
4809 According to POSIX, @option{-n} no longer implies @option{-b}. For
4810 consistency, @option{-M} has been changed in the same way. This may
4811 affect the meaning of character positions in field specifications in
4812 obscure cases. The only fix is to add an explicit @option{-b}.
4814 A position in a sort field specified with @option{-k} may have any
4815 of the option letters @samp{MbdfghinRrV} appended to it, in which case no
4816 global ordering options are inherited by that particular field. The
4817 @option{-b} option may be independently attached to either or both of
4818 the start and end positions of a field specification, and if it is
4819 inherited from the global options it will be attached to both.
4820 If input lines can contain leading or adjacent blanks and @option{-t}
4821 is not used, then @option{-k} is typically combined with @option{-b} or
4822 an option that implicitly ignores leading blanks (@samp{Mghn}) as otherwise
4823 the varying numbers of leading blanks in fields can cause confusing results.
4825 If the start position in a sort field specifier falls after the end of
4826 the line or after the end field, the field is empty. If the @option{-b}
4827 option was specified, the @samp{.@var{c}} part of a field specification
4828 is counted from the first nonblank character of the field.
4830 @vindex _POSIX2_VERSION
4831 @vindex POSIXLY_CORRECT
4832 On systems not conforming to POSIX 1003.1-2001,
4833 @command{sort} supports a traditional origin-zero
4834 syntax @samp{+@var{pos1} [-@var{pos2}]} for specifying sort keys.
4835 The traditional command @samp{sort +@var{a}.@var{x} -@var{b}.@var{y}}
4836 is equivalent to @samp{sort -k @var{a+1}.@var{x+1},@var{b}} if @var{y}
4837 is @samp{0} or absent, otherwise it is equivalent to @samp{sort -k
4838 @var{a+1}.@var{x+1},@var{b+1}.@var{y}}.
4840 This traditional behavior can be controlled with the
4841 @env{_POSIX2_VERSION} environment variable (@pxref{Standards
4842 conformance}); it can also be enabled when @env{POSIXLY_CORRECT} is
4843 not set by using the traditional syntax with @samp{-@var{pos2}} present.
4845 Scripts intended for use on standard hosts should avoid traditional
4846 syntax and should use @option{-k} instead. For example, avoid
4847 @samp{sort +2}, since it might be interpreted as either @samp{sort
4848 ./+2} or @samp{sort -k 3}. If your script must also run on hosts that
4849 support only the traditional syntax, it can use a test like @samp{if sort
4850 -k 1 </dev/null >/dev/null 2>&1; then @dots{}} to decide which syntax
4853 Here are some examples to illustrate various combinations of options.
4858 Sort in descending (reverse) numeric order.
4865 Run no more than 4 sorts concurrently, using a buffer size of 10M.
4868 sort --parallel=4 -S 10M
4872 Sort alphabetically, omitting the first and second fields
4873 and the blanks at the start of the third field.
4874 This uses a single key composed of the characters beginning
4875 at the start of the first nonblank character in field three
4876 and extending to the end of each line.
4883 Sort numerically on the second field and resolve ties by sorting
4884 alphabetically on the third and fourth characters of field five.
4885 Use @samp{:} as the field delimiter.
4888 sort -t : -k 2,2n -k 5.3,5.4
4891 Note that if you had written @option{-k 2n} instead of @option{-k 2,2n}
4892 @command{sort} would have used all characters beginning in the second field
4893 and extending to the end of the line as the primary @emph{numeric}
4894 key. For the large majority of applications, treating keys spanning
4895 more than one field as numeric will not do what you expect.
4897 Also note that the @samp{n} modifier was applied to the field-end
4898 specifier for the first key. It would have been equivalent to
4899 specify @option{-k 2n,2} or @option{-k 2n,2n}. All modifiers except
4900 @samp{b} apply to the associated @emph{field}, regardless of whether
4901 the modifier character is attached to the field-start and/or the
4902 field-end part of the key specifier.
4905 Sort the password file on the fifth field and ignore any
4906 leading blanks. Sort lines with equal values in field five
4907 on the numeric user ID in field three. Fields are separated
4911 sort -t : -k 5b,5 -k 3,3n /etc/passwd
4912 sort -t : -n -k 5b,5 -k 3,3 /etc/passwd
4913 sort -t : -b -k 5,5 -k 3,3n /etc/passwd
4916 These three commands have equivalent effect. The first specifies that
4917 the first key's start position ignores leading blanks and the second
4918 key is sorted numerically. The other two commands rely on global
4919 options being inherited by sort keys that lack modifiers. The inheritance
4920 works in this case because @option{-k 5b,5b} and @option{-k 5b,5} are
4921 equivalent, as the location of a field-end lacking a @samp{.@var{c}}
4922 character position is not affected by whether initial blanks are
4926 Sort a set of log files, primarily by IPv4 address and secondarily by
4927 timestamp. If two lines' primary and secondary keys are identical,
4928 output the lines in the same order that they were input. The log
4929 files contain lines that look like this:
4932 4.150.156.3 - - [01/Apr/2020:06:31:51 +0000] message 1
4933 211.24.3.231 - - [24/Apr/2020:20:17:39 +0000] message 2
4936 Fields are separated by exactly one space. Sort IPv4 addresses
4937 lexicographically, e.g., 212.61.52.2 sorts before 212.129.233.201
4938 because 61 is less than 129.
4941 sort -s -t ' ' -k 4.9n -k 4.5M -k 4.2n -k 4.14,4.21 file*.log |
4942 sort -s -t '.' -k 1,1n -k 2,2n -k 3,3n -k 4,4n
4945 This example cannot be done with a single @command{sort} invocation,
4946 since IPv4 address components are separated by @samp{.} while dates
4947 come just after a space. So it is broken down into two invocations of
4948 @command{sort}: the first sorts by timestamp and the second by IPv4
4949 address. The timestamp is sorted by year, then month, then day, and
4950 finally by hour-minute-second field, using @option{-k} to isolate each
4951 field. Except for hour-minute-second there's no need to specify the
4952 end of each key field, since the @samp{n} and @samp{M} modifiers sort
4953 based on leading prefixes that cannot cross field boundaries. The
4954 IPv4 addresses are sorted lexicographically. The second sort uses
4955 @samp{-s} so that ties in the primary key are broken by the secondary
4956 key; the first sort uses @samp{-s} so that the combination of the two
4960 Generate a tags file in case-insensitive sorted order.
4963 find src -type f -print0 | sort -z -f | xargs -0 etags --append
4966 The use of @option{-print0}, @option{-z}, and @option{-0} in this case means
4967 that file names that contain blanks or other special characters are
4969 by the sort operation.
4971 @c This example is a bit contrived and needs more explanation.
4973 @c Sort records separated by an arbitrary string by using a pipe to convert
4974 @c each record delimiter string to @samp{\0}, then using sort's -z option,
4975 @c and converting each @samp{\0} back to the original record delimiter.
4978 @c printf 'c\n\nb\n\na\n' |
4979 @c perl -0pe 's/\n\n/\n\0/g' |
4981 @c perl -0pe 's/\0/\n/g'
4985 Use the common DSU, Decorate Sort Undecorate idiom to
4986 sort lines according to their length.
4989 awk '@{print length, $0@}' /etc/passwd | sort -n | cut -f2- -d' '
4992 In general this technique can be used to sort data that the @command{sort}
4993 command does not support, or is inefficient at, sorting directly.
4996 Shuffle a list of directories, but preserve the order of files within
4997 each directory. For instance, one could use this to generate a music
4998 playlist in which albums are shuffled but the songs of each album are
5002 ls */* | sort -t / -k 1,1R -k 2,2
5008 @node shuf invocation
5009 @section @command{shuf}: Shuffling text
5012 @cindex shuffling files
5014 @command{shuf} shuffles its input by outputting a random permutation
5015 of its input lines. Each output permutation is equally likely.
5019 shuf [@var{option}]@dots{} [@var{file}]
5020 shuf -e [@var{option}]@dots{} [@var{arg}]@dots{}
5021 shuf -i @var{lo}-@var{hi} [@var{option}]@dots{}
5024 @command{shuf} has three modes of operation that affect where it
5025 obtains its input lines. By default, it reads lines from standard
5026 input. The following options change the operation mode:
5034 @cindex command-line operands to shuffle
5035 Treat each command-line operand as an input line.
5037 @item -i @var{lo}-@var{hi}
5038 @itemx --input-range=@var{lo}-@var{hi}
5040 @opindex --input-range
5041 @cindex input range to shuffle
5042 Act as if input came from a file containing the range of unsigned
5043 decimal integers @var{lo}@dots{}@var{hi}, one per line.
5047 @command{shuf}'s other options can affect its behavior in all
5052 @item -n @var{count}
5053 @itemx --head-count=@var{count}
5055 @opindex --head-count
5056 @cindex head of output
5057 Output at most @var{count} lines. By default, all input lines are
5060 @item -o @var{output-file}
5061 @itemx --output=@var{output-file}
5064 @cindex overwriting of input, allowed
5065 Write output to @var{output-file} instead of standard output.
5066 @command{shuf} reads all input before opening
5067 @var{output-file}, so you can safely shuffle a file in place by using
5068 commands like @code{shuf -o F <F} and @code{cat F | shuf -o F}.
5070 @item --random-source=@var{file}
5071 @opindex --random-source
5072 @cindex random source for shuffling
5073 Use @var{file} as a source of random data used to determine which
5074 permutation to generate. @xref{Random sources}.
5080 @cindex repeat output values
5081 Repeat output values, that is, select with replacement. With this
5082 option the output is not a permutation of the input; instead, each
5083 output line is randomly chosen from all the inputs. This option is
5084 typically combined with @option{--head-count}; if
5085 @option{--head-count} is not given, @command{shuf} repeats
5104 might produce the output
5114 Similarly, the command:
5117 shuf -e clubs hearts diamonds spades
5131 and the command @samp{shuf -i 1-4} might output:
5141 The above examples all have four input lines, so @command{shuf} might
5142 produce any of the twenty-four possible permutations of the input. In
5143 general, if there are @var{n} input lines, there are @var{n}! (i.e.,
5144 @var{n} factorial, or @var{n} * (@var{n} - 1) * @dots{} * 1) possible
5145 output permutations.
5148 To output 50 random numbers each in the range 0 through 9, use:
5151 shuf -r -n 50 -i 0-9
5155 To simulate 100 coin flips, use:
5158 shuf -r -n 100 -e Head Tail
5164 @node uniq invocation
5165 @section @command{uniq}: Uniquify files
5168 @cindex uniquify files
5170 @command{uniq} writes the unique lines in the given @file{input}, or
5171 standard input if nothing is given or for an @var{input} name of
5175 uniq [@var{option}]@dots{} [@var{input} [@var{output}]]
5178 By default, @command{uniq} prints its input lines, except that
5179 it discards all but the first of adjacent repeated lines, so that
5180 no output lines are repeated. Optionally, it can instead discard
5181 lines that are not repeated, or all repeated lines.
5183 The input need not be sorted, but repeated input lines are detected
5184 only if they are adjacent. If you want to discard non-adjacent
5185 duplicate lines, perhaps you want to use @code{sort -u}.
5186 @xref{sort invocation}.
5189 Comparisons honor the rules specified by the @env{LC_COLLATE}
5192 If no @var{output} file is specified, @command{uniq} writes to standard
5195 The program accepts the following options. Also see @ref{Common options}.
5200 @itemx --skip-fields=@var{n}
5202 @opindex --skip-fields
5203 Skip @var{n} fields on each line before checking for uniqueness. Use
5204 a null string for comparison if a line has fewer than @var{n} fields.
5205 Fields are a sequence of blank characters followed by non-blank characters.
5206 Field numbers are one based, i.e., @option{-f 1} will skip the first
5207 field (which may optionally have leading blanks).
5209 For compatibility @command{uniq} supports a traditional option syntax
5210 @option{-@var{n}}. New scripts should use @option{-f @var{n}} instead.
5213 @itemx --skip-chars=@var{n}
5215 @opindex --skip-chars
5216 Skip @var{n} characters before checking for uniqueness. Use a null string
5217 for comparison if a line has fewer than @var{n} characters. If you use both
5218 the field and character skipping options, fields are skipped over first.
5220 @vindex _POSIX2_VERSION
5221 On systems not conforming to POSIX 1003.1-2001,
5222 @command{uniq} supports a traditional option syntax
5224 Although this traditional behavior can be controlled with the
5225 @env{_POSIX2_VERSION} environment variable (@pxref{Standards
5226 conformance}), portable scripts should avoid commands whose
5227 behavior depends on this variable.
5228 For example, use @samp{uniq ./+10} or @samp{uniq -s 10} rather than
5229 the ambiguous @samp{uniq +10}.
5235 Print the number of times each line occurred along with the line.
5238 @itemx --ignore-case
5240 @opindex --ignore-case
5241 Ignore differences in case when comparing lines.
5247 @cindex repeated lines, outputting
5248 Discard lines that are not repeated. When used by itself, this option
5249 causes @command{uniq} to print the first copy of each repeated line,
5253 @itemx --all-repeated[=@var{delimit-method}]
5255 @opindex --all-repeated
5256 @cindex all repeated lines, outputting
5257 Do not discard the second and subsequent repeated input lines,
5258 but discard lines that are not repeated.
5259 This option is useful mainly in conjunction with other options e.g.,
5260 to ignore case or to compare only selected fields.
5261 The optional @var{delimit-method}, supported with the long form option,
5262 specifies how to delimit groups of repeated lines, and must be one of the
5268 Do not delimit groups of repeated lines.
5269 This is equivalent to @option{--all-repeated} (@option{-D}).
5272 Output a newline before each group of repeated lines.
5273 @macro nulOutputNote
5274 With @option{--zero-terminated} (@option{-z}), use a zero
5275 byte (ASCII NUL) instead of a newline as the delimiter.
5280 Separate groups of repeated lines with a single newline.
5281 This is the same as using @samp{prepend}, except that
5282 no delimiter is inserted before the first group, and hence
5283 may be better suited for output direct to users.
5287 @macro ambiguousGroupNote
5288 Note that when groups are delimited and the input stream contains
5289 blank lines, then the output is ambiguous.
5290 To avoid that, filter the input through @samp{tr -s '\\n'} to
5295 This is a GNU extension.
5296 @c FIXME: give an example showing *how* it's useful
5298 @item --group[=@var{delimit-method}]
5300 @cindex all lines, grouping
5301 Output all lines, and delimit each unique group.
5303 The optional @var{delimit-method} specifies how to delimit
5304 groups, and must be one of the following:
5309 Separate unique groups with a single delimiter.
5310 This is the default delimiting method if none is specified,
5311 and better suited for output direct to users.
5314 Output a delimiter before each group of unique items.
5317 Output a delimiter after each group of unique items.
5320 Output a delimiter around each group of unique items.
5325 This is a GNU extension.
5331 @cindex unique lines, outputting
5332 Discard the last line that would be output for a repeated input group.
5333 When used by itself, this option causes @command{uniq} to print unique
5334 lines, and nothing else.
5337 @itemx --check-chars=@var{n}
5339 @opindex --check-chars
5340 Compare at most @var{n} characters on each line (after skipping any specified
5341 fields and characters). By default the entire rest of the lines are
5345 @newlineFieldSeparator
5352 @node comm invocation
5353 @section @command{comm}: Compare two sorted files line by line
5356 @cindex line-by-line comparison
5357 @cindex comparing sorted files
5359 @command{comm} writes to standard output lines that are common, and lines
5360 that are unique, to two input files; a file name of @samp{-} means
5361 standard input. Synopsis:
5364 comm [@var{option}]@dots{} @var{file1} @var{file2}
5368 Before @command{comm} can be used, the input files must be sorted using the
5369 collating sequence specified by the @env{LC_COLLATE} locale.
5370 If an input file ends in a non-newline
5371 character, a newline is silently appended. The @command{sort} command with
5372 no options always outputs a file that is suitable input to @command{comm}.
5374 @cindex differing lines
5375 @cindex common lines
5376 With no options, @command{comm} produces three-column output. Column one
5377 contains lines unique to @var{file1}, column two contains lines unique
5378 to @var{file2}, and column three contains lines common to both files.
5379 Columns are separated by a single TAB character.
5380 @c FIXME: when there's an option to supply an alternative separator
5381 @c string, append "by default" to the above sentence.
5386 The options @option{-1}, @option{-2}, and @option{-3} suppress printing of
5387 the corresponding columns (and separators). Also see @ref{Common options}.
5389 Unlike some other comparison utilities, @command{comm} has an exit
5390 status that does not depend on the result of the comparison.
5391 Upon normal completion @command{comm} produces an exit code of zero.
5392 If there is an error it exits with nonzero status.
5394 @macro checkOrderOption{cmd}
5395 If the @option{--check-order} option is given, unsorted inputs will
5396 cause a fatal error message. If the option @option{--nocheck-order}
5397 is given, unsorted inputs will never cause an error message. If neither
5398 of these options is given, wrongly sorted inputs are diagnosed
5399 only if an input file is found to contain unpairable
5401 lines, and when both input files are non empty.
5403 @ifclear JOIN_COMMAND
5406 If an input file is diagnosed as being unsorted, the @command{\cmd\}
5407 command will exit with a nonzero status (and the output should not be used).
5409 Forcing @command{\cmd\} to process wrongly sorted input files
5410 containing unpairable lines by specifying @option{--nocheck-order} is
5411 not guaranteed to produce any particular output. The output will
5412 probably not correspond with whatever you hoped it would be.
5414 @checkOrderOption{comm}
5419 Fail with an error message if either input file is wrongly ordered.
5421 @item --nocheck-order
5422 Do not check that both input files are in sorted order.
5426 @item --output-delimiter=@var{str}
5427 Print @var{str} between adjacent output columns,
5428 rather than the default of a single TAB character.
5430 The delimiter @var{str} may not be empty.
5433 Output a summary at the end.
5435 Similar to the regular output,
5436 column one contains the total number of lines unique to @var{file1},
5437 column two contains the total number of lines unique to @var{file2}, and
5438 column three contains the total number of lines common to both files,
5439 followed by the word @samp{total} in the additional column four.
5441 In the following example, @command{comm} omits the regular output
5442 (@option{-123}), thus just printing the summary:
5445 $ printf '%s\n' a b c d e > file1
5446 $ printf '%s\n' b c d e f g > file2
5447 $ comm --total -123 file1 file2
5451 This option is a GNU extension. Portable scripts should use @command{wc} to
5452 get the totals, e.g. for the above example files:
5455 $ comm -23 file1 file2 | wc -l # number of lines only in file1
5457 $ comm -13 file1 file2 | wc -l # number of lines only in file2
5459 $ comm -12 file1 file2 | wc -l # number of lines common to both files
5467 @node ptx invocation
5468 @section @command{ptx}: Produce permuted indexes
5472 @command{ptx} reads a text file and essentially produces a permuted index, with
5473 each keyword in its context. The calling sketch is either one of:
5476 ptx [@var{option} @dots{}] [@var{file} @dots{}]
5477 ptx -G [@var{option} @dots{}] [@var{input} [@var{output}]]
5480 The @option{-G} (or its equivalent: @option{--traditional}) option disables
5481 all GNU extensions and reverts to traditional mode, thus introducing some
5482 limitations and changing several of the program's default option values.
5483 When @option{-G} is not specified, GNU extensions are always enabled.
5484 GNU extensions to @command{ptx} are documented wherever appropriate in this
5485 document. @xref{Compatibility in ptx}, for the full list.
5487 Individual options are explained in the following sections.
5489 When GNU extensions are enabled, there may be zero, one or several
5490 @var{file}s after the options. If there is no @var{file}, the program
5491 reads the standard input. If there is one or several @var{file}s, they
5492 give the name of input files which are all read in turn, as if all the
5493 input files were concatenated. However, there is a full contextual
5494 break between each file and, when automatic referencing is requested,
5495 file names and line numbers refer to individual text input files. In
5496 all cases, the program outputs the permuted index to the standard
5499 When GNU extensions are @emph{not} enabled, that is, when the program
5500 operates in traditional mode, there may be zero, one or two parameters
5501 besides the options. If there are no parameters, the program reads the
5502 standard input and outputs the permuted index to the standard output.
5503 If there is only one parameter, it names the text @var{input} to be read
5504 instead of the standard input. If two parameters are given, they give
5505 respectively the name of the @var{input} file to read and the name of
5506 the @var{output} file to produce. @emph{Be very careful} to note that,
5507 in this case, the contents of file given by the second parameter is
5508 destroyed. This behavior is dictated by System V @command{ptx}
5509 compatibility; GNU Standards normally discourage output parameters not
5510 introduced by an option.
5512 Note that for @emph{any} file named as the value of an option or as an
5513 input text file, a single dash @samp{-} may be used, in which case
5514 standard input is assumed. However, it would not make sense to use this
5515 convention more than once per program invocation.
5518 * General options in ptx:: Options which affect general program behavior.
5519 * Charset selection in ptx:: Underlying character set considerations.
5520 * Input processing in ptx:: Input fields, contexts, and keyword selection.
5521 * Output formatting in ptx:: Types of output format, and sizing the fields.
5522 * Compatibility in ptx::
5526 @node General options in ptx
5527 @subsection General options
5532 @itemx --traditional
5533 As already explained, this option disables all GNU extensions to
5534 @command{ptx} and switches to traditional mode.
5537 Print a short help on standard output, then exit without further
5541 Print the program version on standard output, then exit without further
5549 @node Charset selection in ptx
5550 @subsection Charset selection
5552 As it is set up now, @command{ptx} assumes that the input file is coded
5553 using 8-bit characters, and it may not work well in multibyte locales.
5554 In a single-byte locale, the default regular expression
5555 for a keyword allows foreign or diacriticized letters. Keyword sorting,
5556 however, is still crude; it obeys the underlying character set ordering
5559 The output of @command{ptx} assumes the locale's character encoding.
5560 For example, with @command{ptx}'s @option{-T} option, if the locale
5561 uses the Latin-1 encoding you may need a LaTeX directive like
5562 @samp{\usepackage[latin1]@{inputenc@}} to render non-ASCII characters
5568 @itemx --ignore-case
5570 @opindex --ignore-case
5571 Fold lower case letters to upper case for sorting.
5576 @node Input processing in ptx
5577 @subsection Word selection and input processing
5582 @itemx --break-file=@var{file}
5584 @opindex --break-file
5586 This option provides an alternative (to @option{-W}) method of describing
5587 which characters make up words. It introduces the name of a
5588 file which contains a list of characters which can@emph{not} be part of
5589 one word; this file is called the @dfn{Break file}. Any character which
5590 is not part of the Break file is a word constituent. If both options
5591 @option{-b} and @option{-W} are specified, then @option{-W} has precedence and
5592 @option{-b} is ignored.
5594 When GNU extensions are enabled, the only way to avoid newline as a
5595 break character is to write all the break characters in the file with no
5596 newline at all, not even at the end of the file. When GNU extensions
5597 are disabled, spaces, tabs and newlines are always considered as break
5598 characters even if not included in the Break file.
5601 @itemx --ignore-file=@var{file}
5603 @opindex --ignore-file
5605 The file associated with this option contains a list of words which will
5606 never be taken as keywords in concordance output. It is called the
5607 @dfn{Ignore file}. The file contains exactly one word in each line; the
5608 end of line separation of words is not subject to the value of the
5612 @itemx --only-file=@var{file}
5614 @opindex --only-file
5616 The file associated with this option contains a list of words which will
5617 be retained in concordance output; any word not mentioned in this file
5618 is ignored. The file is called the @dfn{Only file}. The file contains
5619 exactly one word in each line; the end of line separation of words is
5620 not subject to the value of the @option{-S} option.
5622 There is no default for the Only file. When both an Only file and an
5623 Ignore file are specified, a word is considered a keyword only
5624 if it is listed in the Only file and not in the Ignore file.
5629 @opindex --references
5631 On each input line, the leading sequence of non-white space characters will be
5632 taken to be a reference that has the purpose of identifying this input
5633 line in the resulting permuted index.
5634 @xref{Output formatting in ptx},
5635 for more information about reference production.
5636 Using this option changes the default value for option @option{-S}.
5638 Using this option, the program does not try very hard to remove
5639 references from contexts in output, but it succeeds in doing so
5640 @emph{when} the context ends exactly at the newline. If option
5641 @option{-r} is used with @option{-S} default value, or when GNU extensions
5642 are disabled, this condition is always met and references are completely
5643 excluded from the output contexts.
5645 @item -S @var{regexp}
5646 @itemx --sentence-regexp=@var{regexp}
5648 @opindex --sentence-regexp
5650 This option selects which regular expression will describe the end of a
5651 line or the end of a sentence. In fact, this regular expression is not
5652 the only distinction between end of lines or end of sentences, and input
5653 line boundaries have no special significance outside this option. By
5654 default, when GNU extensions are enabled and if @option{-r} option is not
5655 used, end of sentences are used. In this case, this @var{regex} is
5656 imported from GNU Emacs:
5659 [.?!][]\"')@}]*\\($\\|\t\\| \\)[ \t\n]*
5662 Whenever GNU extensions are disabled or if @option{-r} option is used, end
5663 of lines are used; in this case, the default @var{regexp} is just:
5669 Using an empty @var{regexp} is equivalent to completely disabling end of
5670 line or end of sentence recognition. In this case, the whole file is
5671 considered to be a single big line or sentence. The user might want to
5672 disallow all truncation flag generation as well, through option @option{-F
5673 ""}. @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
5676 When the keywords happen to be near the beginning of the input line or
5677 sentence, this often creates an unused area at the beginning of the
5678 output context line; when the keywords happen to be near the end of the
5679 input line or sentence, this often creates an unused area at the end of
5680 the output context line. The program tries to fill those unused areas
5681 by wrapping around context in them; the tail of the input line or
5682 sentence is used to fill the unused area on the left of the output line;
5683 the head of the input line or sentence is used to fill the unused area
5684 on the right of the output line.
5686 As a matter of convenience to the user, many usual backslashed escape
5687 sequences from the C language are recognized and converted to the
5688 corresponding characters by @command{ptx} itself.
5690 @item -W @var{regexp}
5691 @itemx --word-regexp=@var{regexp}
5693 @opindex --word-regexp
5695 This option selects which regular expression will describe each keyword.
5696 By default, if GNU extensions are enabled, a word is a sequence of
5697 letters; the @var{regexp} used is @samp{\w+}. When GNU extensions are
5698 disabled, a word is by default anything which ends with a space, a tab
5699 or a newline; the @var{regexp} used is @samp{[^ \t\n]+}.
5701 An empty @var{regexp} is equivalent to not using this option.
5702 @xref{Regexps, , Syntax of Regular Expressions, emacs, The GNU Emacs
5705 As a matter of convenience to the user, many usual backslashed escape
5706 sequences, as found in the C language, are recognized and converted to
5707 the corresponding characters by @command{ptx} itself.
5712 @node Output formatting in ptx
5713 @subsection Output formatting
5715 Output format is mainly controlled by the @option{-O} and @option{-T} options
5716 described in the table below. When neither @option{-O} nor @option{-T} are
5717 selected, and if GNU extensions are enabled, the program chooses an
5718 output format suitable for a dumb terminal. Each keyword occurrence is
5719 output to the center of one line, surrounded by its left and right
5720 contexts. Each field is properly justified, so the concordance output
5721 can be readily observed. As a special feature, if automatic
5722 references are selected by option @option{-A} and are output before the
5723 left context, that is, if option @option{-R} is @emph{not} selected, then
5724 a colon is added after the reference; this nicely interfaces with GNU
5725 Emacs @code{next-error} processing. In this default output format, each
5726 white space character, like newline and tab, is merely changed to
5727 exactly one space, with no special attempt to compress consecutive
5728 spaces. This might change in the future. Except for those white space
5729 characters, every other character of the underlying set of 256
5730 characters is transmitted verbatim.
5732 Output format is further controlled by the following options.
5736 @item -g @var{number}
5737 @itemx --gap-size=@var{number}
5741 Select the size of the minimum white space gap between the fields on the
5744 @item -w @var{number}
5745 @itemx --width=@var{number}
5749 Select the maximum output width of each final line. If references are
5750 used, they are included or excluded from the maximum output width
5751 depending on the value of option @option{-R}@. If this option is not
5752 selected, that is, when references are output before the left context,
5753 the maximum output width takes into account the maximum length of all
5754 references. If this option is selected, that is, when references are
5755 output after the right context, the maximum output width does not take
5756 into account the space taken by references, nor the gap that precedes
5760 @itemx --auto-reference
5762 @opindex --auto-reference
5764 Select automatic references. Each input line will have an automatic
5765 reference made up of the file name and the line ordinal, with a single
5766 colon between them. However, the file name will be empty when standard
5767 input is being read. If both @option{-A} and @option{-r} are selected, then
5768 the input reference is still read and skipped, but the automatic
5769 reference is used at output time, overriding the input reference.
5772 @itemx --right-side-refs
5774 @opindex --right-side-refs
5776 In the default output format, when option @option{-R} is not used, any
5777 references produced by the effect of options @option{-r} or @option{-A} are
5778 placed to the far right of output lines, after the right context. With
5779 default output format, when the @option{-R} option is specified, references
5780 are rather placed at the beginning of each output line, before the left
5781 context. For any other output format, option @option{-R} is
5782 ignored, with one exception: with @option{-R} the width of references
5783 is @emph{not} taken into account in total output width given by @option{-w}.
5785 This option is automatically selected whenever GNU extensions are
5788 @item -F @var{string}
5789 @itemx --flag-truncation=@var{string}
5791 @opindex --flag-truncation
5793 This option will request that any truncation in the output be reported
5794 using the string @var{string}. Most output fields theoretically extend
5795 towards the beginning or the end of the current line, or current
5796 sentence, as selected with option @option{-S}@. But there is a maximum
5797 allowed output line width, changeable through option @option{-w}, which is
5798 further divided into space for various output fields. When a field has
5799 to be truncated because it cannot extend beyond the beginning or the end of
5800 the current line to fit in, then a truncation occurs. By default,
5801 the string used is a single slash, as in @option{-F /}.
5803 @var{string} may have more than one character, as in @option{-F @dots{}}.
5804 Also, in the particular case when @var{string} is empty (@option{-F ""}),
5805 truncation flagging is disabled, and no truncation marks are appended in
5808 As a matter of convenience to the user, many usual backslashed escape
5809 sequences, as found in the C language, are recognized and converted to
5810 the corresponding characters by @command{ptx} itself.
5812 @item -M @var{string}
5813 @itemx --macro-name=@var{string}
5815 @opindex --macro-name
5817 Select another @var{string} to be used instead of @samp{xx}, while
5818 generating output suitable for @command{nroff}, @command{troff} or @TeX{}.
5821 @itemx --format=roff
5823 @opindex --format=roff
5825 Choose an output format suitable for @command{nroff} or @command{troff}
5826 processing. Each output line will look like:
5829 .xx "@var{tail}" "@var{before}" "@var{keyword_and_after}"@c
5830 "@var{head}" "@var{ref}"
5833 so it will be possible to write a @samp{.xx} roff macro to take care of
5834 the output typesetting. This is the default output format when GNU
5835 extensions are disabled. Option @option{-M} can be used to change
5836 @samp{xx} to another macro name.
5838 In this output format, each non-graphical character, like newline and
5839 tab, is merely changed to exactly one space, with no special attempt to
5840 compress consecutive spaces. Each quote character @samp{"} is doubled
5841 so it will be correctly processed by @command{nroff} or @command{troff}.
5846 @opindex --format=tex
5848 Choose an output format suitable for @TeX{} processing. Each output
5849 line will look like:
5852 \xx @{@var{tail}@}@{@var{before}@}@{@var{keyword}@}@c
5853 @{@var{after}@}@{@var{head}@}@{@var{ref}@}
5857 so it will be possible to write a @code{\xx} definition to take care of
5858 the output typesetting. Note that when references are not being
5859 produced, that is, neither option @option{-A} nor option @option{-r} is
5860 selected, the last parameter of each @code{\xx} call is inhibited.
5861 Option @option{-M} can be used to change @samp{xx} to another macro
5864 In this output format, some special characters, like @samp{$}, @samp{%},
5865 @samp{&}, @samp{#} and @samp{_} are automatically protected with a
5866 backslash. Curly brackets @samp{@{}, @samp{@}} are protected with a
5867 backslash and a pair of dollar signs (to force mathematical mode). The
5868 backslash itself produces the sequence @code{\backslash@{@}}.
5869 Circumflex and tilde diacritical marks produce the sequence @code{^\@{ @}} and
5870 @code{~\@{ @}} respectively. Other diacriticized characters of the
5871 underlying character set produce an appropriate @TeX{} sequence as far
5872 as possible. The other non-graphical characters, like newline and tab,
5873 and all other characters which are not part of ASCII, are merely
5874 changed to exactly one space, with no special attempt to compress
5875 consecutive spaces. Let me know how to improve this special character
5876 processing for @TeX{}.
5881 @node Compatibility in ptx
5882 @subsection The GNU extensions to @command{ptx}
5884 This version of @command{ptx} contains a few features which do not exist in
5885 System V @command{ptx}. These extra features are suppressed by using the
5886 @option{-G} command line option, unless overridden by other command line
5887 options. Some GNU extensions cannot be recovered by overriding, so the
5888 simple rule is to avoid @option{-G} if you care about GNU extensions.
5889 Here are the differences between this program and System V @command{ptx}.
5894 This program can read many input files at once, it always writes the
5895 resulting concordance on standard output. On the other hand, System V
5896 @command{ptx} reads only one file and sends the result to standard output
5897 or, if a second @var{file} parameter is given on the command, to that
5900 Having output parameters not introduced by options is a dangerous
5901 practice which GNU avoids as far as possible. So, for using @command{ptx}
5902 portably between GNU and System V, you should always use it with a
5903 single input file, and always expect the result on standard output. You
5904 might also want to automatically configure in a @option{-G} option to
5905 @command{ptx} calls in products using @command{ptx}, if the configurator finds
5906 that the installed @command{ptx} accepts @option{-G}.
5909 The only options available in System V @command{ptx} are options @option{-b},
5910 @option{-f}, @option{-g}, @option{-i}, @option{-o}, @option{-r}, @option{-t} and
5911 @option{-w}. All other options are GNU extensions and are not repeated in
5912 this enumeration. Moreover, some options have a slightly different
5913 meaning when GNU extensions are enabled, as explained below.
5916 By default, concordance output is not formatted for @command{troff} or
5917 @command{nroff}. It is rather formatted for a dumb terminal. @command{troff}
5918 or @command{nroff} output may still be selected through option @option{-O}.
5921 Unless @option{-R} option is used, the maximum reference width is
5922 subtracted from the total output line width. With GNU extensions
5923 disabled, width of references is not taken into account in the output
5924 line width computations.
5927 All 256 bytes, even ASCII NUL bytes, are always read and
5928 processed from input file with no adverse effect, even if GNU extensions
5929 are disabled. However, System V @command{ptx} does not accept 8-bit
5930 characters, a few control characters are rejected, and the tilde
5931 @samp{~} is also rejected.
5934 Input line length is only limited by available memory, even if GNU
5935 extensions are disabled. However, System V @command{ptx} processes only
5936 the first 200 characters in each line.
5939 The break (non-word) characters default to be every character except all
5940 letters of the underlying character set, diacriticized or not. When GNU
5941 extensions are disabled, the break characters default to space, tab and
5945 The program makes better use of output line width. If GNU extensions
5946 are disabled, the program rather tries to imitate System V @command{ptx},
5947 but still, there are some slight disposition glitches this program does
5948 not completely reproduce.
5951 The user can specify both an Ignore file and an Only file. This is not
5952 allowed with System V @command{ptx}.
5957 @node tsort invocation
5958 @section @command{tsort}: Topological sort
5961 @cindex topological sort
5963 @command{tsort} performs a topological sort on the given @var{file}, or
5964 standard input if no input file is given or for a @var{file} of
5965 @samp{-}. For more details and some history, see @ref{tsort background}.
5969 tsort [@var{option}] [@var{file}]
5972 @command{tsort} reads its input as pairs of strings, separated by blanks,
5973 indicating a partial ordering. The output is a total ordering that
5974 corresponds to the given partial ordering.
5988 will produce the output
5999 Consider a more realistic example.
6000 You have a large set of functions all in one file, and they may all be
6001 declared static except one. Currently that one (say @code{main}) is the
6002 first function defined in the file, and the ones it calls directly follow
6003 it, followed by those they call, etc. Let's say that you are determined
6004 to take advantage of prototypes, so you have to choose between declaring
6005 all of those functions (which means duplicating a lot of information from
6006 the definitions) and rearranging the functions so that as many as possible
6007 are defined before they are used. One way to automate the latter process
6008 is to get a list for each function of the functions it calls directly.
6009 Many programs can generate such lists. They describe a call graph.
6010 Consider the following list, in which a given line indicates that the
6011 function on the left calls the one on the right directly.
6017 tail_file pretty_name
6018 tail_file write_header
6020 tail_forever recheck
6021 tail_forever pretty_name
6022 tail_forever write_header
6023 tail_forever dump_remainder
6026 tail_lines start_lines
6027 tail_lines dump_remainder
6028 tail_lines file_lines
6029 tail_lines pipe_lines
6031 tail_bytes start_bytes
6032 tail_bytes dump_remainder
6033 tail_bytes pipe_bytes
6034 file_lines dump_remainder
6038 then you can use @command{tsort} to produce an ordering of those
6039 functions that satisfies your requirement.
6042 example$ tsort call-graph | tac
6062 @command{tsort} detects any cycles in the input and writes the first cycle
6063 encountered to standard error.
6065 Note that for a given partial ordering, generally there is no unique
6066 total ordering. In the context of the call graph above, the function
6067 @code{parse_options} may be placed anywhere in the list as long as it
6068 precedes @code{main}.
6070 The only options are @option{--help} and @option{--version}. @xref{Common
6076 * tsort background:: Where tsort came from.
6079 @node tsort background
6080 @subsection @command{tsort}: Background
6082 @command{tsort} exists because very early versions of the Unix linker processed
6083 an archive file exactly once, and in order. As @command{ld} read each object
6084 in the archive, it decided whether it was needed in the program based on
6085 whether it defined any symbols which were undefined at that point in
6088 This meant that dependencies within the archive had to be handled
6089 specially. For example, @code{scanf} probably calls @code{read}. That means
6090 that in a single pass through an archive, it was important for @code{scanf.o}
6091 to appear before read.o, because otherwise a program which calls
6092 @code{scanf} but not @code{read} might end up with an unexpected unresolved
6093 reference to @code{read}.
6095 The way to address this problem was to first generate a set of
6096 dependencies of one object file on another. This was done by a shell
6097 script called @command{lorder}. The GNU tools don't provide a version of
6098 lorder, as far as I know, but you can still find it in BSD
6101 Then you ran @command{tsort} over the @command{lorder} output, and you used the
6102 resulting sort to define the order in which you added objects to the archive.
6104 This whole procedure has been obsolete since about 1980, because
6105 Unix archives now contain a symbol table (traditionally built by
6106 @command{ranlib}, now generally built by @command{ar} itself), and the Unix
6107 linker uses the symbol table to effectively make multiple passes over
6110 Anyhow, that's where tsort came from. To solve an old problem with
6111 the way the linker handled archive files, which has since been solved
6115 @node Operating on fields
6116 @chapter Operating on fields
6119 * cut invocation:: Print selected parts of lines.
6120 * paste invocation:: Merge lines of files.
6121 * join invocation:: Join lines on a common field.
6125 @node cut invocation
6126 @section @command{cut}: Print selected parts of lines
6129 @command{cut} writes to standard output selected parts of each line of each
6130 input file, or standard input if no files are given or for a file name of
6134 cut @var{option}@dots{} [@var{file}]@dots{}
6137 In the table which follows, the @var{byte-list}, @var{character-list},
6138 and @var{field-list} are one or more numbers or ranges (two numbers
6139 separated by a dash) separated by commas. Bytes, characters, and
6140 fields are numbered starting at 1. Incomplete ranges may be
6141 given: @option{-@var{m}} means @samp{1-@var{m}}; @samp{@var{n}-} means
6142 @samp{@var{n}} through end of line or last field. The list elements
6143 can be repeated, can overlap, and can be specified in any order; but
6144 the selected input is written in the same order that it is read, and
6145 is written exactly once.
6147 The program accepts the following options. Also see @ref{Common
6152 @item -b @var{byte-list}
6153 @itemx --bytes=@var{byte-list}
6156 Select for printing only the bytes in positions listed in
6157 @var{byte-list}. Tabs and backspaces are treated like any other
6158 character; they take up 1 byte. If an output delimiter is specified,
6159 (see the description of @option{--output-delimiter}), then output that
6160 string between ranges of selected bytes.
6162 @item -c @var{character-list}
6163 @itemx --characters=@var{character-list}
6165 @opindex --characters
6166 Select for printing only the characters in positions listed in
6167 @var{character-list}. The same as @option{-b} for now, but
6168 internationalization will change that. Tabs and backspaces are
6169 treated like any other character; they take up 1 character. If an
6170 output delimiter is specified, (see the description of
6171 @option{--output-delimiter}), then output that string between ranges
6174 @item -f @var{field-list}
6175 @itemx --fields=@var{field-list}
6178 Select for printing only the fields listed in @var{field-list}.
6179 Fields are separated by a TAB character by default. Also print any
6180 line that contains no delimiter character, unless the
6181 @option{--only-delimited} (@option{-s}) option is specified.
6183 Note @command{awk} supports more sophisticated field processing,
6184 like reordering fields, and handling fields aligned with blank characters.
6185 By default @command{awk} uses (and discards) runs of blank characters
6186 to separate fields, and ignores leading and trailing blanks.
6189 awk '{print $2}' # print the second field
6190 awk '{print $(NF-1)}' # print the penultimate field
6191 awk '{print $2,$1}' # reorder the first two fields
6194 Note while @command{cut} accepts field specifications in
6195 arbitrary order, output is always in the order encountered in the file.
6197 In the unlikely event that @command{awk} is unavailable,
6198 one can use the @command{join} command, to process blank
6199 characters as @command{awk} does above.
6202 join -a1 -o 1.2 - /dev/null # print the second field
6203 join -a1 -o 1.2,1.1 - /dev/null # reorder the first two fields
6207 @item -d @var{input_delim_byte}
6208 @itemx --delimiter=@var{input_delim_byte}
6210 @opindex --delimiter
6211 With @option{-f}, use the first byte of @var{input_delim_byte} as
6212 the input fields separator (default is TAB).
6216 Do not split multi-byte characters (no-op for now).
6219 @itemx --only-delimited
6221 @opindex --only-delimited
6222 For @option{-f}, do not print lines that do not contain the field separator
6223 character. Normally, any line without a field separator is printed verbatim.
6225 @item --output-delimiter=@var{output_delim_string}
6226 @opindex --output-delimiter
6227 With @option{-f}, output fields are separated by @var{output_delim_string}.
6228 The default with @option{-f} is to use the input delimiter.
6229 When using @option{-b} or @option{-c} to select ranges of byte or
6230 character offsets (as opposed to ranges of fields),
6231 output @var{output_delim_string} between non-overlapping
6232 ranges of selected bytes.
6235 @opindex --complement
6236 This option is a GNU extension.
6237 Select for printing the complement of the bytes, characters or fields
6238 selected with the @option{-b}, @option{-c} or @option{-f} options.
6239 In other words, do @emph{not} print the bytes, characters or fields
6240 specified via those options. This option is useful when you have
6241 many fields and want to print all but a few of them.
6250 @node paste invocation
6251 @section @command{paste}: Merge lines of files
6254 @cindex merging files
6256 @command{paste} writes to standard output lines consisting of sequentially
6257 corresponding lines of each given file, separated by a TAB character.
6258 Standard input is used for a file name of @samp{-} or if no input files
6264 paste [@var{option}]@dots{} [@var{file}]@dots{}
6278 Take lines sequentially from each file:
6286 Duplicate lines from a file:
6288 $ paste num2 let3 num2
6294 Intermix lines from standard input:
6296 $ paste - let3 - < num2
6302 Join consecutive lines with a space:
6304 $ seq 4 | paste -d ' ' - -
6309 The program accepts the following options. Also see @ref{Common options}.
6317 Paste the lines of one file at a time rather than one line from each
6318 file. Using the above example data:
6321 $ paste -s num2 let3
6326 @item -d @var{delim-list}
6327 @itemx --delimiters=@var{delim-list}
6329 @opindex --delimiters
6330 Consecutively use the characters in @var{delim-list} instead of
6331 TAB to separate merged lines. When @var{delim-list} is
6332 exhausted, start again at its beginning. Using the above example data:
6335 $ paste -d '%_' num2 let3 num2
6348 @node join invocation
6349 @section @command{join}: Join lines on a common field
6352 @cindex common field, joining on
6354 @command{join} writes to standard output a line for each pair of input
6355 lines that have identical join fields. Synopsis:
6358 join [@var{option}]@dots{} @var{file1} @var{file2}
6361 Either @var{file1} or @var{file2} (but not both) can be @samp{-},
6362 meaning standard input. @var{file1} and @var{file2} should be
6363 sorted on the join fields.
6385 @command{join}'s default behavior (when no options are given):
6387 @item the join field is the first field in each line;
6388 @item fields in the input are separated by one or more blanks, with leading
6389 blanks on the line ignored;
6390 @item fields in the output are separated by a space;
6391 @item each output line consists of the join field, the remaining
6392 fields from @var{file1}, then the remaining fields from @var{file2}.
6397 * General options in join:: Options which affect general program behavior.
6398 * Sorting files for join:: Using @command{sort} before @command{join}.
6399 * Working with fields:: Joining on different fields.
6400 * Paired and unpaired lines:: Controlling @command{join}'s field matching.
6401 * Header lines:: Working with header lines in files.
6402 * Set operations:: Union, Intersection and Difference of files.
6405 @node General options in join
6406 @subsection General options
6407 The program accepts the following options. Also see @ref{Common options}.
6411 @item -a @var{file-number}
6413 Print a line for each unpairable line in file @var{file-number} (either
6414 @samp{1} or @samp{2}), in addition to the normal output.
6417 Fail with an error message if either input file is wrongly ordered.
6419 @item --nocheck-order
6420 Do not check that both input files are in sorted order. This is the default.
6422 @item -e @var{string}
6424 Replace those output fields that are missing in the input with @var{string}.
6425 I.e., missing fields specified with the @option{-12jo} options.
6429 Treat the first line of each input file as a header line. The header lines
6430 will be joined and printed as the first output line. If @option{-o} is used to
6431 specify output format, the header line will be printed according to the
6432 specified format. The header lines will not be checked for ordering even if
6433 @option{--check-order} is specified. Also if the header lines from each file
6434 do not match, the heading fields from the first file will be used.
6437 @itemx --ignore-case
6439 @opindex --ignore-case
6440 Ignore differences in case when comparing keys.
6441 With this option, the lines of the input files must be ordered in the same way.
6442 Use @samp{sort -f} to produce this ordering.
6444 @item -1 @var{field}
6446 Join on field @var{field} (a positive integer) of file 1.
6448 @item -2 @var{field}
6450 Join on field @var{field} (a positive integer) of file 2.
6452 @item -j @var{field}
6453 Equivalent to @option{-1 @var{field} -2 @var{field}}.
6455 @item -o @var{field-list}
6457 If the keyword @samp{auto} is specified, infer the output format from
6458 the first line in each file. This is the same as the default output format
6459 but also ensures the same number of fields are output for each line.
6460 Missing fields are replaced with the @option{-e} option and extra fields
6463 Otherwise, construct each output line according to the format in
6464 @var{field-list}. Each element in @var{field-list} is either the single
6465 character @samp{0} or has the form @var{m.n} where the file number, @var{m},
6466 is @samp{1} or @samp{2} and @var{n} is a positive field number.
6468 A field specification of @samp{0} denotes the join field.
6469 In most cases, the functionality of the @samp{0} field spec
6470 may be reproduced using the explicit @var{m.n} that corresponds
6471 to the join field. However, when printing unpairable lines
6472 (using either of the @option{-a} or @option{-v} options), there is no way
6473 to specify the join field using @var{m.n} in @var{field-list}
6474 if there are unpairable lines in both files.
6475 To give @command{join} that functionality, POSIX invented the @samp{0}
6476 field specification notation.
6478 The elements in @var{field-list}
6479 are separated by commas or blanks.
6480 Blank separators typically need to be quoted for the shell. For
6481 example, the commands @samp{join -o 1.2,2.2} and @samp{join -o '1.2
6482 2.2'} are equivalent.
6484 All output lines---including those printed because of any -a or -v
6485 option---are subject to the specified @var{field-list}.
6488 Use character @var{char} as the input and output field separator.
6489 Treat as significant each occurrence of @var{char} in the input file.
6490 Use @samp{sort -t @var{char}}, without the @option{-b} option of
6491 @samp{sort}, to produce this ordering. If @samp{join -t ''} is specified,
6492 the whole line is considered, matching the default operation of sort.
6493 If @samp{-t '\0'} is specified then the ASCII NUL
6494 character is used to delimit the fields.
6496 @item -v @var{file-number}
6497 Print a line for each unpairable line in file @var{file-number}
6498 (either @samp{1} or @samp{2}), instead of the normal output.
6501 @newlineFieldSeparator
6508 @checkOrderOption{join}
6513 @node Sorting files for join
6514 @subsection Pre-sorting
6516 @command{join} requires sorted input files. Each input file should be
6517 sorted according to the key (=field/column number) used in
6518 @command{join}. The recommended sorting option is @samp{sort -k 1b,1}
6519 (assuming the desired key is in the first column).
6521 @noindent Typical usage:
6524 $ sort -k 1b,1 file1 > file1.sorted
6525 $ sort -k 1b,1 file2 > file2.sorted
6526 $ join file1.sorted file2.sorted > file3
6531 Normally, the sort order is that of the
6532 collating sequence specified by the @env{LC_COLLATE} locale. Unless
6533 the @option{-t} option is given, the sort comparison ignores blanks at
6534 the start of the join field, as in @code{sort -b}. If the
6535 @option{--ignore-case} option is given, the sort comparison ignores
6536 the case of characters in the join field, as in @code{sort -f}:
6540 $ sort -k 1bf,1 file1 > file1.sorted
6541 $ sort -k 1bf,1 file2 > file2.sorted
6542 $ join --ignore-case file1.sorted file2.sorted > file3
6546 The @command{sort} and @command{join} commands should use consistent
6547 locales and options if the output of @command{sort} is fed to
6548 @command{join}. You can use a command like @samp{sort -k 1b,1} to
6549 sort a file on its default join field, but if you select a non-default
6550 locale, join field, separator, or comparison options, then you should
6551 do so consistently between @command{join} and @command{sort}.
6553 @noindent To avoid any locale-related issues, it is recommended to use the
6554 @samp{C} locale for both commands:
6558 $ LC_ALL=C sort -k 1b,1 file1 > file1.sorted
6559 $ LC_ALL=C sort -k 1b,1 file2 > file2.sorted
6560 $ LC_ALL=C join file1.sorted file2.sorted > file3
6565 @node Working with fields
6566 @subsection Working with fields
6568 Use @option{-1},@option{-2} to set the key fields for each of the input files.
6569 Ensure the preceding @command{sort} commands operated on the same fields.
6572 The following example joins two files, using the values from seventh field
6573 of the first file and the third field of the second file:
6577 $ sort -k 7b,7 file1 > file1.sorted
6578 $ sort -k 3b,3 file2 > file2.sorted
6579 $ join -1 7 -2 3 file1.sorted file2.sorted > file3
6584 If the field number is the same for both files, use @option{-j}:
6588 $ sort -k4b,4 file1 > file1.sorted
6589 $ sort -k4b,4 file2 > file2.sorted
6590 $ join -j4 file1.sorted file2.sorted > file3
6595 Both @command{sort} and @command{join} operate of whitespace-delimited
6596 fields. To specify a different delimiter, use @option{-t} in @emph{both}:
6600 $ sort -t, -k3b,3 file1 > file1.sorted
6601 $ sort -t, -k3b,3 file2 > file2.sorted
6602 $ join -t, -j3 file1.sorted file2.sorted > file3
6607 To specify a tab (@sc{ascii} 0x09) character instead of whitespace,
6608 use:@footnote{the @code{$'\t'} is supported in most modern shells.
6609 For older shells, use a literal tab.}
6613 $ sort -t$'\t' -k3b,3 file1 > file1.sorted
6614 $ sort -t$'\t' -k3b,3 file2 > file2.sorted
6615 $ join -t$'\t' -j3 file1.sorted file2.sorted > file3
6621 If @samp{join -t ''} is specified then the whole line is considered which
6622 matches the default operation of sort:
6626 $ sort file1 > file1.sorted
6627 $ sort file2 > file2.sorted
6628 $ join -t '' file1.sorted file2.sorted > file3
6633 @node Paired and unpaired lines
6634 @subsection Controlling @command{join}'s field matching
6636 In this section the @command{sort} commands are omitted for brevity.
6637 Sorting the files before joining is still required.
6639 @command{join}'s default behavior is to print only lines common to
6640 both input files. Use @option{-a} and @option{-v} to print unpairable lines
6641 from one or both files.
6644 All examples below use the following two (pre-sorted) input files:
6646 @multitable @columnfractions .5 .5
6663 @c TODO: Find better column widths that work for both HTML and PDF
6664 @c and disable indentation of @example.
6665 @multitable @columnfractions 0.5 0.5
6667 @headitem Command @tab Outcome
6677 (@emph{intersection})
6683 $ join -a 1 file1 file2
6688 common lines @emph{and} unpaired
6689 lines from the first file
6694 $ join -a 2 file1 file2
6699 common lines @emph{and} unpaired lines from the second file
6704 $ join -a 1 -a 2 file1 file2
6710 all lines (paired and unpaired) from both files
6713 see note below regarding @code{-o auto}.
6718 $ join -v 1 file1 file2
6722 unpaired lines from the first file
6728 $ join -v 2 file1 file2
6732 unpaired lines from the second file
6738 $ join -v 1 -v 2 file1 file2
6743 unpaired lines from both files, omitting common lines
6744 (@emph{symmetric difference}).
6750 The @option{-o auto -e X} options are useful when dealing with unpaired lines.
6751 The following example prints all lines (common and unpaired) from both files.
6752 Without @option{-o auto} it is not easy to discern which fields originate from
6756 $ join -a 1 -a 2 file1 file2
6761 $ join -o auto -e X -a 1 -a 2 file1 file2
6768 If the input has no unpairable lines, a GNU extension is
6769 available; the sort order can be any order that considers two fields
6770 to be equal if and only if the sort comparison described above
6771 considers them to be equal. For example:
6794 @subsection Header lines
6796 The @option{--header} option can be used when the files to join
6797 have a header line which is not sorted:
6811 $ join --header -o auto -e NA -a1 -a2 file1 file2
6820 To sort a file with a header line, use GNU @command{sed -u}.
6821 The following example sort the files but keeps the first line of each
6826 $ ( sed -u 1q ; sort -k2b,2 ) < file1 > file1.sorted
6827 $ ( sed -u 1q ; sort -k2b,2 ) < file2 > file2.sorted
6828 $ join --header -o auto -e NA -a1 -a2 file1.sorted file2.sorted > file3
6832 @node Set operations
6833 @subsection Union, Intersection and Difference of files
6835 Combine @command{sort}, @command{uniq} and @command{join} to
6836 perform the equivalent of set operations on files:
6838 @c From https://www.pixelbeat.org/cmdline.html#sets
6839 @multitable @columnfractions 0.5 0.5
6840 @headitem Command @tab outcome
6841 @item @code{sort -u file1 file2}
6842 @tab Union of unsorted files
6844 @item @code{sort file1 file2 | uniq -d}
6845 @tab Intersection of unsorted files
6847 @item @code{sort file1 file1 file2 | uniq -u}
6848 @tab Difference of unsorted files
6850 @item @code{sort file1 file2 | uniq -u}
6851 @tab Symmetric Difference of unsorted files
6853 @item @code{join -t '' -a1 -a2 file1 file2}
6854 @tab Union of sorted files
6856 @item @code{join -t '' file1 file2}
6857 @tab Intersection of sorted files
6859 @item @code{join -t '' -v2 file1 file2}
6860 @tab Difference of sorted files
6862 @item @code{join -t '' -v1 -v2 file1 file2}
6863 @tab Symmetric Difference of sorted files
6867 All examples above operate on entire lines and not on specific fields:
6868 @command{sort} without @option{-k} and @command{join -t ''} both consider
6869 entire lines as the key.
6872 @node Operating on characters
6873 @chapter Operating on characters
6875 @cindex operating on characters
6877 These commands operate on individual characters.
6880 * tr invocation:: Translate, squeeze, and/or delete characters.
6881 * expand invocation:: Convert tabs to spaces.
6882 * unexpand invocation:: Convert spaces to tabs.
6887 @section @command{tr}: Translate, squeeze, and/or delete characters
6894 tr [@var{option}]@dots{} @var{string1} [@var{string2}]
6897 @command{tr} copies standard input to standard output, performing
6898 one of the following operations:
6902 translate, and optionally squeeze repeated characters in the result,
6904 squeeze repeated characters,
6908 delete characters, then squeeze repeated characters from the result.
6911 The @var{string1} and @var{string2} operands define arrays of
6912 characters @var{array1} and @var{array2}. By default @var{array1}
6913 lists input characters that @command{tr} operates on, and @var{array2}
6914 lists corresponding translations. In some cases the second operand is
6917 The program accepts the following options. Also see @ref{Common options}.
6918 Options must precede operands.
6927 @opindex --complement
6928 Instead of @var{array1}, use its complement (all characters not
6929 specified by @var{string1}), in ascending order. Use this option with
6930 caution in multibyte locales where its meaning is not always clear
6931 or portable; see @ref{Character arrays}.
6937 Delete characters in @var{array1}; do not translate.
6940 @itemx --squeeze-repeats
6942 @opindex --squeeze-repeats
6943 Replace each sequence of a repeated character that is listed in
6944 the last specified @var{array}, with a single occurrence of that character.
6947 @itemx --truncate-set1
6949 @opindex --truncate-set1
6950 Truncate @var{array1} to the length of @var{array2}.
6958 * Character arrays:: Specifying arrays of characters.
6959 * Translating:: Changing characters to other characters.
6960 * Squeezing and deleting:: Removing characters.
6964 @node Character arrays
6965 @subsection Specifying arrays of characters
6967 @cindex arrays of characters in @command{tr}
6969 The @var{string1} and @var{string2} operands are not regular
6970 expressions, even though they may look similar. Instead, they
6971 merely represent arrays of characters. As a GNU extension to POSIX,
6972 an empty string operand represents an empty array of characters.
6974 The interpretation of @var{string1} and @var{string2} depends on locale.
6975 GNU @command{tr} fully supports only safe single-byte locales,
6976 where each possible input byte represents a single character.
6977 Unfortunately, this means GNU @command{tr} will not handle commands
6978 like @samp{tr @"o @L{}} the way you might expect,
6979 since (assuming a UTF-8 encoding) this is equivalent to
6980 @samp{tr '\303\266' '\305\201'} and GNU @command{tr} will
6981 simply transliterate all @samp{\303} bytes to @samp{\305} bytes, etc.
6982 POSIX does not clearly specify the behavior of @command{tr} in locales
6983 where characters are represented by byte sequences instead of by
6984 individual bytes, or where data might contain invalid bytes that are
6985 encoding errors. To avoid problems in this area, you can run
6986 @command{tr} in a safe single-byte locale by using a shell command
6987 like @samp{LC_ALL=C tr} instead of plain @command{tr}.
6989 Although most characters simply represent themselves in @var{string1}
6990 and @var{string2}, the strings can contain shorthands listed below,
6991 for convenience. Some shorthands can be used only in @var{string1} or
6992 @var{string2}, as noted below.
6996 @item Backslash escapes
6997 @cindex backslash escapes
6999 The following backslash escape sequences are recognized:
7003 Bell (BEL, Control-G).
7005 Backspace (BS, Control-H).
7007 Form feed (FF, Control-L).
7009 Newline (LF, Control-J).
7011 Carriage return (CR, Control-M).
7013 Tab (HT, Control-I).
7015 Vertical tab (VT, Control-K).
7017 The eight-bit byte with the value given by @var{ooo}, which is the longest
7018 sequence of one to three octal digits following the backslash.
7019 For portability, @var{ooo} should represent a value that fits in eight bits.
7020 As a GNU extension to POSIX, if the value would not fit, then only the
7021 first two digits of @var{ooo} are used, e.g., @samp{\400}
7022 is equivalent to @samp{\0400} and represents a two-byte sequence.
7027 It is an error if no character follows an unescaped backslash.
7028 As a GNU extension, a backslash followed by a character not listed
7029 above is interpreted as that character, removing any special
7030 significance; this can be used to escape the characters
7031 @samp{[} and @samp{-} when they would otherwise be special.
7036 The notation @samp{@var{m}-@var{n}} expands to the characters
7037 from @var{m} through @var{n}, in ascending order. @var{m} should
7038 not collate after @var{n}; if it does, an error results. As an example,
7039 @samp{0-9} is the same as @samp{0123456789}.
7041 GNU @command{tr} does not support the System V syntax that uses square
7042 brackets to enclose ranges. Translations specified in that format
7043 sometimes work as expected, since the brackets are often transliterated
7044 to themselves. However, they should be avoided because they sometimes
7045 behave unexpectedly. For example, @samp{tr -d '[0-9]'} deletes brackets
7048 Many historically common and even accepted uses of ranges are not fully
7049 portable. For example, on EBCDIC hosts using the @samp{A-Z}
7050 range will not do what most would expect because @samp{A} through @samp{Z}
7051 are not contiguous as they are in ASCII@.
7052 One way to work around this is to use character classes (see below).
7053 Otherwise, it is most portable (and most ugly) to enumerate the members
7056 @item Repeated characters
7057 @cindex repeated characters
7059 The notation @samp{[@var{c}*@var{n}]} in @var{string2} expands to @var{n}
7060 copies of character @var{c}. Thus, @samp{[y*6]} is the same as
7061 @samp{yyyyyy}. The notation @samp{[@var{c}*]} in @var{string2} expands
7062 to as many copies of @var{c} as are needed to make @var{array2} as long as
7063 @var{array1}. If @var{n} begins with @samp{0}, it is interpreted in
7064 octal, otherwise in decimal. A zero-valued @var{n} is treated as if
7067 @item Character classes
7068 @cindex character classes
7070 The notation @samp{[:@var{class}:]} expands to all characters in
7071 the (predefined) class @var{class}. When the @option{--delete} (@option{-d})
7072 and @option{--squeeze-repeats} (@option{-s}) options are both given, any
7073 character class can be used in @var{string2}. Otherwise, only the
7074 character classes @code{lower} and @code{upper} are accepted in
7075 @var{string2}, and then only if the corresponding character class
7076 (@code{upper} and @code{lower}, respectively) is specified in the same
7077 relative position in @var{string1}. Doing this specifies case conversion.
7078 Except for case conversion, a class's characters appear in no particular order.
7079 The class names are given below; an error results when an invalid class
7091 Horizontal whitespace.
7100 Printable characters, not including space.
7106 Printable characters, including space.
7109 Punctuation characters.
7112 Horizontal or vertical whitespace.
7121 @item Equivalence classes
7122 @cindex equivalence classes
7124 The syntax @samp{[=@var{c}=]} expands to all characters equivalent to
7125 @var{c}, in no particular order. These equivalence classes are
7126 allowed in @var{string2} only when @option{--delete} (@option{-d}) and
7127 @option{--squeeze-repeats} @option{-s} are both given.
7129 Although equivalence classes are intended to support non-English alphabets,
7130 there seems to be no standard way to define them or determine their
7131 contents. Therefore, they are not fully implemented in GNU @command{tr};
7132 each character's equivalence class consists only of that character,
7133 which is of no particular use.
7139 @subsection Translating
7141 @cindex translating characters
7143 @command{tr} performs translation when @var{string1} and @var{string2} are
7144 both given and the @option{--delete} (@option{-d}) option is not given.
7145 @command{tr} translates each character of its input that is in @var{array1}
7146 to the corresponding character in @var{array2}. Characters not in
7147 @var{array1} are passed through unchanged.
7149 As a GNU extension to POSIX, when a character appears more than once
7150 in @var{array1}, only the final instance is used. For example, these
7151 two commands are equivalent:
7158 A common use of @command{tr} is to convert lowercase characters to
7159 uppercase. This can be done in many ways. Here are three of them:
7162 tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
7164 tr '[:lower:]' '[:upper:]'
7168 However, ranges like @code{a-z} are not portable outside the C locale.
7170 When @command{tr} is performing translation, @var{array1} and @var{array2}
7171 typically have the same length. If @var{array1} is shorter than
7172 @var{array2}, the extra characters at the end of @var{array2} are ignored.
7174 On the other hand, making @var{array1} longer than @var{array2} is not
7175 portable; POSIX says that the result is undefined. In this situation,
7176 BSD @command{tr} pads @var{array2} to the length of @var{array1} by repeating
7177 the last character of @var{array2} as many times as necessary. System V
7178 @command{tr} truncates @var{array1} to the length of @var{array2}.
7180 By default, GNU @command{tr} handles this case like BSD @command{tr}.
7181 When the @option{--truncate-set1} (@option{-t}) option is given,
7182 GNU @command{tr} handles this case like the System V @command{tr}
7183 instead. This option is ignored for operations other than translation.
7185 Acting like System V @command{tr} in this case breaks the relatively common
7189 tr -cs A-Za-z0-9 '\012'
7193 because it converts only zero bytes (the first element in the
7194 complement of @var{array1}), rather than all non-alphanumerics, to
7198 By the way, the above idiom is not portable because it uses ranges, and
7199 it assumes that the octal code for newline is 012. Here is a better
7203 tr -cs '[:alnum:]' '[\n*]'
7207 @node Squeezing and deleting
7208 @subsection Squeezing repeats and deleting
7210 @cindex squeezing repeat characters
7211 @cindex deleting characters
7212 @cindex removing characters
7214 When given just the @option{--delete} (@option{-d}) option, @command{tr}
7215 removes any input characters that are in @var{array1}.
7217 When given just the @option{--squeeze-repeats} (@option{-s}) option
7218 and not translating, @command{tr} replaces each input sequence of a
7219 repeated character that is in @var{array1} with a single occurrence of
7222 When given both @option{--delete} and @option{--squeeze-repeats}, @command{tr}
7223 first performs any deletions using @var{array1}, then squeezes repeats
7224 from any remaining characters using @var{array2}.
7226 The @option{--squeeze-repeats} option may also be used when translating,
7227 in which case @command{tr} first performs translation, then squeezes
7228 repeats from any remaining characters using @var{array2}.
7230 Here are some examples to illustrate various combinations of options:
7235 Remove all zero bytes:
7242 Put all words on lines by themselves. This converts all
7243 non-alphanumeric characters to newlines, then squeezes each string
7244 of repeated newlines into a single newline:
7247 tr -cs '[:alnum:]' '[\n*]'
7251 Convert each sequence of repeated newlines to a single newline.
7252 I.e., delete empty lines:
7259 Find doubled occurrences of words in a document.
7260 @c Separate the following two "the"s, so typo checkers don't complain.
7261 For example, people often write ``the @w{}the'' with the repeated words
7262 separated by a newline. The Bourne shell script below works first
7263 by converting each sequence of punctuation and blank characters to a
7264 single newline. That puts each ``word'' on a line by itself.
7265 Next it maps all uppercase characters to lower case, and finally it
7266 runs @command{uniq} with the @option{-d} option to print out only the words
7272 | tr -s '[:punct:][:blank:]' '[\n*]' \
7273 | tr '[:upper:]' '[:lower:]' \
7278 Deleting a small set of characters is usually straightforward. For example,
7279 to remove all @samp{a}s, @samp{x}s, and @samp{M}s you would do this:
7285 However, when @samp{-} is one of those characters, it can be tricky because
7286 @samp{-} has special meanings. Performing the same task as above but also
7287 removing all @samp{-} characters, we might try @code{tr -d -axM}, but
7288 that would fail because @command{tr} would try to interpret @option{-a} as
7289 a command-line option. Alternatively, we could try putting the hyphen
7290 inside the string, @code{tr -d a-xM}, but that wouldn't work either because
7291 it would make @command{tr} interpret @code{a-x} as the range of characters
7292 @samp{a}@dots{}@samp{x} rather than the three.
7293 One way to solve the problem is to put the hyphen at the end of the list
7300 Or you can use @samp{--} to terminate option processing:
7309 @node expand invocation
7310 @section @command{expand}: Convert tabs to spaces
7313 @cindex tabs to spaces, converting
7314 @cindex converting tabs to spaces
7316 @command{expand} writes the contents of each given @var{file}, or standard
7317 input if none are given or for a @var{file} of @samp{-}, to standard
7318 output, with tab characters converted to the appropriate number of
7322 expand [@var{option}]@dots{} [@var{file}]@dots{}
7325 By default, @command{expand} converts all tabs to spaces. It preserves
7326 backspace characters in the output; they decrement the column count for
7327 tab calculations. The default action is equivalent to @option{-t 8} (set
7328 tabs every 8 columns).
7330 The program accepts the following options. Also see @ref{Common options}.
7334 @item -t @var{tab1}[,@var{tab2}]@dots{}
7335 @itemx --tabs=@var{tab1}[,@var{tab2}]@dots{}
7338 @cindex tab stops, setting
7339 If only one tab stop is given, set the tabs @var{tab1} spaces apart
7340 (default is 8). Otherwise, set the tabs at columns @var{tab1},
7341 @var{tab2}, @dots{} (numbered from 0), and replace any tabs beyond the
7342 last tab stop given with single spaces.
7343 @macro gnuExpandTabs
7344 Tab stops can be separated by blanks as well as by commas.
7346 As a GNU extension the last @var{tab} specified can be prefixed
7347 with a @samp{/} to indicate a tab size to use for remaining positions.
7348 For example, @option{--tabs=2,4,/8} will set tab stops at position 2 and 4,
7349 and every multiple of 8 after that.
7351 Also the last @var{tab} specified can be prefixed with a @samp{+} to indicate
7352 a tab size to use for remaining positions, offset from the final explicitly
7354 For example, to ignore the 1 character gutter present in diff output,
7355 one can specify a 1 character offset using @option{--tabs=1,+8},
7356 which will set tab stops at positions 1,9,17,@dots{}
7361 For compatibility, GNU @command{expand} also accepts the obsolete
7362 option syntax, @option{-@var{t1}[,@var{t2}]@dots{}}. New scripts
7363 should use @option{-t @var{t1}[,@var{t2}]@dots{}} instead.
7369 @cindex initial tabs, converting
7370 Only convert initial tabs (those that precede all non-space or non-tab
7371 characters) on each line to spaces.
7378 @node unexpand invocation
7379 @section @command{unexpand}: Convert spaces to tabs
7383 @command{unexpand} writes the contents of each given @var{file}, or
7384 standard input if none are given or for a @var{file} of @samp{-}, to
7385 standard output, converting blanks at the beginning of each line into
7386 as many tab characters as needed. In the default POSIX
7387 locale, a @dfn{blank} is a space or a tab; other locales may specify
7388 additional blank characters. Synopsis:
7391 unexpand [@var{option}]@dots{} [@var{file}]@dots{}
7394 By default, @command{unexpand} converts only initial blanks (those
7395 that precede all non-blank characters) on each line. It
7396 preserves backspace characters in the output; they decrement the column
7397 count for tab calculations. By default, tabs are set at every 8th
7400 The program accepts the following options. Also see @ref{Common options}.
7404 @item -t @var{tab1}[,@var{tab2}]@dots{}
7405 @itemx --tabs=@var{tab1}[,@var{tab2}]@dots{}
7408 If only one tab stop is given, set the tabs @var{tab1} columns apart
7409 instead of the default 8. Otherwise, set the tabs at columns
7410 @var{tab1}, @var{tab2}, @dots{} (numbered from 0), and leave blanks
7411 beyond the tab stops given unchanged.
7414 This option implies the @option{-a} option.
7416 For compatibility, GNU @command{unexpand} supports the obsolete option syntax,
7417 @option{-@var{tab1}[,@var{tab2}]@dots{}}, where tab stops must be
7418 separated by commas. (Unlike @option{-t}, this obsolete option does
7419 not imply @option{-a}.) New scripts should use @option{--first-only -t
7420 @var{tab1}[,@var{tab2}]@dots{}} instead.
7426 Also convert all sequences of two or more blanks just before a tab stop,
7427 even if they occur after non-blank characters in a line.
7434 @node Directory listing
7435 @chapter Directory listing
7437 This chapter describes the @command{ls} command and its variants @command{dir}
7438 and @command{vdir}, which list information about files.
7441 * ls invocation:: List directory contents.
7442 * dir invocation:: Briefly ls.
7443 * vdir invocation:: Verbosely ls.
7444 * dircolors invocation:: Color setup for ls, etc.
7449 @section @command{ls}: List directory contents
7452 @cindex directory listing
7454 The @command{ls} program lists information about files (of any type,
7455 including directories). Options and file arguments can be intermixed
7456 arbitrarily, as usual. Later options override earlier options that
7459 For non-option command-line arguments that are directories, by default
7460 @command{ls} lists the contents of directories, not recursively, and
7461 omitting files with names beginning with @samp{.}. For other non-option
7462 arguments, by default @command{ls} lists just the file name. If no
7463 non-option argument is specified, @command{ls} operates on the current
7464 directory, acting as if it had been invoked with a single argument of @samp{.}.
7467 By default, the output is sorted alphabetically, according to the locale
7468 settings in effect.@footnote{If you use a non-POSIX
7469 locale (e.g., by setting @env{LC_ALL} to @samp{en_US}), then @command{ls} may
7470 produce output that is sorted differently than you're accustomed to.
7471 In that case, set the @env{LC_ALL} environment variable to @samp{C}.}
7472 If standard output is
7473 a terminal, the output is in columns (sorted vertically) and control
7474 characters are output as question marks; otherwise, the output is listed
7475 one per line and control characters are output as-is.
7477 Because @command{ls} is such a fundamental program, it has accumulated many
7478 options over the years. They are described in the subsections below;
7479 within each section, options are listed alphabetically (ignoring case).
7480 The division of options into the subsections is not absolute, since some
7481 options affect more than one aspect of @command{ls}'s operation.
7483 @cindex exit status of @command{ls}
7488 1 minor problems (e.g., failure to access a file or directory not
7489 specified as a command line argument. This happens when listing a
7490 directory in which entries are actively being removed or renamed.)
7491 2 serious trouble (e.g., memory exhausted, invalid option, failure
7492 to access a file or directory specified as a command line argument
7493 or a directory loop)
7496 Also see @ref{Common options}.
7499 * Which files are listed::
7500 * What information is listed::
7501 * Sorting the output::
7502 * General output formatting::
7503 * Formatting file timestamps::
7504 * Formatting the file names::
7508 @node Which files are listed
7509 @subsection Which files are listed
7511 These options determine which files @command{ls} lists information for.
7512 By default, @command{ls} lists files and the contents of any
7513 directories on the command line, except that in directories it ignores
7514 files whose names start with @samp{.}.
7522 In directories, do not ignore file names that start with @samp{.}.
7527 @opindex --almost-all
7528 In directories, do not ignore all file names that start with @samp{.};
7529 ignore only @file{.} and @file{..}. The @option{--all} (@option{-a})
7530 option overrides this option.
7533 @itemx --ignore-backups
7535 @opindex --ignore-backups
7536 @cindex backup files, ignoring
7537 In directories, ignore files that end with @samp{~}. This option is
7538 equivalent to @samp{--ignore='*~' --ignore='.*~'}.
7543 @opindex --directory
7544 List just the names of directories, as with other types of files, rather
7545 than listing their contents.
7546 @c The following sentence is the same as the one for -F.
7547 Do not follow symbolic links listed on the
7548 command line unless the @option{--dereference-command-line} (@option{-H}),
7549 @option{--dereference} (@option{-L}), or
7550 @option{--dereference-command-line-symlink-to-dir} options are specified.
7553 @itemx --dereference-command-line
7555 @opindex --dereference-command-line
7556 @cindex symbolic links, dereferencing
7557 If a command line argument specifies a symbolic link, show information
7558 for the file the link references rather than for the link itself.
7560 @item --dereference-command-line-symlink-to-dir
7561 @opindex --dereference-command-line-symlink-to-dir
7562 @cindex symbolic links, dereferencing
7563 Do not dereference symbolic links, with one exception:
7564 if a command line argument specifies a symbolic link that refers to
7565 a directory, show information for that directory rather than for the
7567 This is the default behavior unless long format is being used
7568 or any of the following options is in effect:
7569 @option{--classify} (@option{-F}),
7570 @option{--directory} (@option{-d}),
7571 @option{--dereference} (@option{-L}), or
7572 @option{--dereference-command-line} (@option{-H})).
7574 @item --group-directories-first
7575 @opindex --group-directories-first
7576 Group all the directories before the files and then sort the
7577 directories and the files separately using the selected sort key
7578 (see --sort option).
7579 That is, this option specifies a primary sort key,
7580 and the --sort option specifies a secondary key.
7581 However, any use of @option{--sort=none}
7582 (@option{-U}) disables this option altogether.
7584 @item --hide=PATTERN
7585 @opindex --hide=@var{pattern}
7586 In directories, ignore files whose names match the shell pattern
7587 @var{pattern}, unless the @option{--all} (@option{-a}) or
7588 @option{--almost-all} (@option{-A}) is also given. This
7589 option acts like @option{--ignore=@var{pattern}} except that it has no
7590 effect if @option{--all} (@option{-a}) or @option{--almost-all}
7591 (@option{-A}) is also given.
7593 This option can be useful in shell aliases. For example, if
7594 @command{lx} is an alias for @samp{ls --hide='*~'} and @command{ly} is
7595 an alias for @samp{ls --ignore='*~'}, then the command @samp{lx -A}
7596 lists the file @file{README~} even though @samp{ly -A} would not.
7598 @item -I @var{pattern}
7599 @itemx --ignore=@var{pattern}
7601 @opindex --ignore=@var{pattern}
7602 In directories, ignore files whose names match the shell pattern
7603 (not regular expression) @var{pattern}. As
7604 in the shell, an initial @samp{.} in a file name does not match a
7605 wildcard at the start of @var{pattern}. Sometimes it is useful
7606 to give this option several times. For example,
7609 $ ls --ignore='.??*' --ignore='.[^.]' --ignore='#*'
7612 The first option ignores names of length 3 or more that start with @samp{.},
7613 the second ignores all two-character names that start with @samp{.}
7614 except @samp{..}, and the third ignores names that start with @samp{#}.
7617 @itemx --dereference
7619 @opindex --dereference
7620 @cindex symbolic links, dereferencing
7621 When showing file information for a symbolic link, show information
7622 for the file the link references rather than the link itself.
7623 However, even with this option, @command{ls} still prints the name
7624 of the link itself, not the name of the file that the link points to.
7629 @opindex --recursive
7630 @cindex recursive directory listing
7631 @cindex directory listing, recursive
7632 List the contents of all directories recursively.
7637 @node What information is listed
7638 @subsection What information is listed
7640 These options affect the information that @command{ls} displays. By
7641 default, only file names are shown.
7647 @cindex hurd, author, printing
7648 In long format, list each file's author.
7649 In GNU/Hurd, file authors can differ from their owners, but in other
7650 operating systems the two are the same.
7656 @cindex dired Emacs mode support
7657 Print an additional line after the main output:
7660 //DIRED// @var{beg1} @var{end1} @var{beg2} @var{end2} @dots{}
7664 The @var{begn} and @var{endn} are unsigned integers that record the
7665 byte position of the beginning and end of each file name in the output.
7666 This makes it easy for Emacs to find the names, even when they contain
7667 unusual characters such as space or newline, without fancy searching.
7669 If directories are being listed recursively via
7670 @option{--recursive} (@option{-R}), output a similar
7671 line with offsets for each subdirectory name:
7674 //SUBDIRED// @var{beg1} @var{end1} @dots{}
7677 Finally, output a line of the form:
7680 //DIRED-OPTIONS// --quoting-style=@var{word}
7684 where @var{word} is the quoting style (@pxref{Formatting the file names}).
7686 Here is an actual example:
7689 $ mkdir -p a/sub/deeper a/sub2
7691 $ touch a/sub/deeper/file
7692 $ ls -gloRF --dired a
7695 -rw-r--r-- 1 0 Jun 10 12:27 f1
7696 -rw-r--r-- 1 0 Jun 10 12:27 f2
7697 drwxr-xr-x 3 4096 Jun 10 12:27 sub/
7698 drwxr-xr-x 2 4096 Jun 10 12:27 sub2/
7702 drwxr-xr-x 2 4096 Jun 10 12:27 deeper/
7706 -rw-r--r-- 1 0 Jun 10 12:27 file
7710 //DIRED// 48 50 84 86 120 123 158 162 217 223 282 286
7711 //SUBDIRED// 2 3 167 172 228 240 290 296
7712 //DIRED-OPTIONS// --quoting-style=literal
7715 The pairs of offsets on the @samp{//DIRED//} line above delimit
7716 these names: @file{f1}, @file{f2}, @file{sub}, @file{sub2}, @file{deeper},
7718 The offsets on the @samp{//SUBDIRED//} line delimit the following
7719 directory names: @file{a}, @file{a/sub}, @file{a/sub/deeper}, @file{a/sub2}.
7721 Here is an example of how to extract the fifth entry name, @samp{deeper},
7722 corresponding to the pair of offsets, 222 and 228:
7725 $ ls -gloRF --dired a > out
7726 $ dd bs=1 skip=222 count=6 < out 2>/dev/null; echo
7730 Although the listing above includes a trailing slash
7731 for the @samp{deeper} entry, the offsets select the name without
7732 the trailing slash. However, if you invoke @command{ls} with @option{--dired}
7733 (@option{-D}) along with an option like
7734 @option{--escape} (@option{-b}) and operate
7735 on a file whose name contains special characters, the backslash
7740 $ ls -blog --dired 'a b'
7741 -rw-r--r-- 1 0 Jun 10 12:28 a\ b
7743 //DIRED-OPTIONS// --quoting-style=escape
7746 If you use a quoting style like @option{--quoting-style=c} (@option{-Q})
7747 that adds quote marks, then the offsets include the quote marks.
7748 So beware that the user may select the quoting style via the environment
7749 variable @env{QUOTING_STYLE}@. Hence, applications using @option{--dired}
7750 should either specify an explicit @option{--quoting-style=literal}
7751 (@option{-N}) option on the command line, or else be
7752 prepared to parse the escaped names.
7754 The @option{--dired} (@option{-D}) option has well-defined behavior
7755 only when long format is in effect and hyperlinks are disabled (e.g.,
7756 @option{--hyperlink=none}).
7759 @opindex --full-time
7760 Produce long format, and list times in full. It is
7761 equivalent to using @option{--format=long} (@option{-l}) with
7762 @option{--time-style=full-iso} (@pxref{Formatting file timestamps}).
7766 Produce long format, but omit owner information.
7772 Inhibit display of group information in long format.
7773 (This is the default in some non-GNU versions of @command{ls}, so we
7774 provide this option for compatibility.)
7782 @cindex inode number, printing
7783 Print the inode number (also called the file serial number and index
7784 number) of each file to the left of the file name. (This number
7785 uniquely identifies each file within a particular file system.)
7788 @itemx --format=long
7789 @itemx --format=verbose
7792 @opindex long ls @r{format}
7793 @opindex verbose ls @r{format}
7794 Produce long format.
7795 In addition to the name of each file, print the file type, file mode bits,
7796 number of hard links, owner name, group name, size, and
7797 timestamp (@pxref{Formatting file timestamps}), normally
7798 the modification timestamp (the mtime, @pxref{File timestamps}).
7799 If the owner or group name cannot be determined, print
7800 the owner or group ID instead, right-justified as a cue
7801 that it is a number rather than a textual name.
7802 Print question marks for other information that
7803 cannot be determined.
7805 Normally the size is printed as a byte count without punctuation, but
7806 this can be overridden (@pxref{Block size}).
7807 For example, @option{--human-readable} (@option{-h})
7808 prints an abbreviated, human-readable count, and
7809 @samp{--block-size="'1"} prints a byte count with the thousands
7810 separator of the current locale.
7812 For each directory that is listed, preface the files with a line
7813 @samp{total @var{blocks}}, where @var{blocks} is the file system allocation
7814 for all files in that directory. The block size currently defaults to 1024
7815 bytes, but this can be overridden (@pxref{Block size}).
7816 The @var{blocks} computed counts each hard link separately;
7817 this is arguably a deficiency.
7819 The file type is one of the following characters:
7821 @c The commented-out entries are ones we're not sure about.
7829 character special file
7831 high performance (``contiguous data'') file
7837 @c semaphore, if this is a distinct file type
7841 @c multiplexed file (7th edition Unix; obsolete)
7843 off-line (``migrated'') file (Cray DMF)
7845 network special file (HP-UX)
7851 @c message queue, if this is a distinct file type
7855 @c shared memory object, if this is a distinct file type
7857 @c typed memory object, if this is a distinct file type
7859 @c whiteout (4.4BSD; not implemented)
7861 some other file type
7864 @cindex permissions, output by @command{ls}
7865 The file mode bits listed are similar to symbolic mode specifications
7866 (@pxref{Symbolic Modes}). But @command{ls} combines multiple bits into the
7867 third character of each set of permissions as follows:
7871 If the set-user-ID or set-group-ID bit and the corresponding executable bit
7875 If the set-user-ID or set-group-ID bit is set but the corresponding
7876 executable bit is not set.
7879 If the restricted deletion flag or sticky bit, and the
7880 other-executable bit, are both set. The restricted deletion flag is
7881 another name for the sticky bit. @xref{Mode Structure}.
7884 If the restricted deletion flag or sticky bit is set but the
7885 other-executable bit is not set.
7888 If the executable bit is set and none of the above apply.
7894 Following the file mode bits is a single character that specifies
7895 whether an alternate access method such as an access control list
7896 applies to the file. When the character following the file mode bits is a
7897 space, there is no alternate access method. When it is a printing
7898 character, then there is such a method.
7900 GNU @command{ls} uses a @samp{.} character to indicate a file
7901 with a security context, but no other alternate access method.
7903 A file with any other combination of alternate access methods
7904 is marked with a @samp{+} character.
7907 @itemx --numeric-uid-gid
7909 @opindex --numeric-uid-gid
7910 @cindex numeric uid and gid
7911 @cindex numeric user and group IDs
7912 Produce long format, but
7913 display right-justified numeric user and group IDs
7914 instead of left-justified owner and group names.
7918 Produce long format, but omit group information.
7919 It is equivalent to using @option{--format=long} (@option{-l})
7920 with @option{--no-group} (@option{-G}).
7926 @cindex file system allocation
7927 @cindex size of files, reporting
7928 Print the file system allocation of each file to the left of the file name.
7929 This is the amount of file system space used by the file, which is usually a
7930 bit more than the file's size, but it can be less if the file has holes.
7932 Normally the allocation is printed in units of
7933 1024 bytes, but this can be overridden (@pxref{Block size}).
7935 @cindex NFS mounts from BSD to HP-UX
7936 For files that are NFS-mounted from an HP-UX system to a BSD system,
7937 this option reports sizes that are half the correct values. On HP-UX
7938 systems, it reports sizes that are twice the correct values for files
7939 that are NFS-mounted from BSD systems. This is due to a flaw in HP-UX;
7940 it also affects the HP-UX @command{ls} program.
7949 @cindex security context
7950 Display the SELinux security context or @samp{?} if none is found.
7951 In long format, print the security context to the left of the size column.
7956 @node Sorting the output
7957 @subsection Sorting the output
7959 @cindex sorting @command{ls} output
7960 These options change the order in which @command{ls} sorts the information
7961 it outputs. By default, sorting is done by character code
7962 (e.g., ASCII order).
7968 @itemx --time=status
7971 @opindex ctime@r{, printing or sorting by}
7972 @opindex status time@r{, printing or sorting by}
7973 @opindex use time@r{, printing or sorting files by}
7975 print the status change timestamp (the ctime) instead of the mtime.
7976 When sorting by time or when not using long format,
7977 sort according to the ctime. @xref{File timestamps}.
7981 @cindex unsorted directory listing
7982 @cindex directory order, listing by
7983 Produce an unsorted directory listing.
7984 This is equivalent to the combination of @option{--all} (@option{-a}),
7985 @option{--sort=none} (@option{-U}), @option{-1},
7986 @option{--color=none}, and @option{--hyperlink=none},
7987 while also disabling any previous use of @option{--size} (@option{-s}).
7993 @cindex reverse sorting
7994 Reverse whatever the sorting method is---e.g., list files in reverse
7995 alphabetical order, youngest first, smallest first, or whatever.
7996 This option has no effect when @option{--sort=none} (@option{-U})
8003 @opindex size of files@r{, sorting files by}
8004 Sort by file size, largest first.
8010 @opindex modification timestamp@r{, sorting files by}
8011 Sort by modification timestamp (mtime) by default, newest first.
8012 The timestamp to order by can be changed with the @option{--time} option.
8013 @xref{File timestamps}.
8017 @itemx --time=access
8021 @opindex use time@r{, printing or sorting files by}
8022 @opindex atime@r{, printing or sorting files by}
8023 @opindex access timestamp@r{, printing or sorting files by}
8024 In long format, print the last access timestamp (the atime).
8025 When sorting by time or when not using long format,
8026 sort according to the atime.
8027 @xref{File timestamps}.
8030 @itemx --time=modification
8032 @opindex data modification time@r{, printing or sorting files by}
8033 @opindex mtime@r{, printing or sorting files by}
8034 This is the default timestamp display and sorting mode.
8035 In long format, print the last data modification timestamp (the mtime).
8036 When sorting by time or when not using long format,
8037 sort according to the mtime.
8038 @xref{File timestamps}.
8041 @itemx --time=creation
8043 @opindex birth time@r{, printing or sorting files by}
8044 @opindex creation timestamp@r{, printing or sorting files by}
8045 In long format, print the file creation timestamp if available,
8046 falling back to the file modification timestamp (mtime) if not.
8047 When sorting by time or when not using long format,
8048 sort according to the birth time.
8049 @xref{File timestamps}.
8055 @opindex none@r{, sorting option for @command{ls}}
8056 Do not sort; list the files in whatever order they are
8057 stored in the directory. (Do not do any of the other unrelated things
8058 that @option{-f} does.) This can be useful when listing large
8059 directories, where sorting can take some time.
8062 @itemx --sort=version
8065 @opindex version@r{, sorting option for @command{ls}}
8066 Sort by version name and number, lowest first. It behaves like a default
8067 sort, except that each sequence of decimal digits is treated numerically
8068 as an index/version number. @xref{Version sort ordering}.
8072 @opindex width@r{, sorting option for @command{ls}}
8073 Sort by printed width of file names.
8074 This can be useful with the @option{--format=vertical} (@option{-C})
8075 output format, to most densely display the listed files.
8078 @itemx --sort=extension
8081 @opindex extension@r{, sorting files by}
8082 Sort directory contents alphabetically by file extension (characters
8083 after the last @samp{.}); files with no extension are sorted first.
8088 @node General output formatting
8089 @subsection General output formatting
8091 These options affect the appearance of the overall output.
8095 @item --format=single-column
8097 @opindex single-column @r{output of files}
8098 List one file name per line, with no other information.
8099 This is the default for @command{ls} when standard
8100 output is not a terminal. See also the @option{--escape} (@option{-b}),
8101 @option{--hide-control-chars} (@option{-q}), and @option{--zero} options
8102 to disambiguate output of file names containing newline characters.
8106 List one file per line. This is like @option{--format=single-column}
8107 except that it has no effect if long format is also in effect.
8110 @itemx --format=vertical
8113 @opindex vertical @r{sorted files in columns}
8114 List files in columns, sorted vertically, with no other information.
8115 This is the default for @command{ls} if standard output is a terminal.
8116 It is always the default for the @command{dir} program.
8117 GNU @command{ls} uses variable width columns to display as many files as
8118 possible in the fewest lines.
8120 @item --color [=@var{when}]
8122 @cindex color, distinguishing file types with
8123 Specify whether to use color for distinguishing file types; @var{when}
8124 may be omitted, or one of:
8127 @vindex none @r{color option}
8128 - Do not use color at all. This is the default.
8130 @vindex auto @r{color option}
8131 @cindex terminal, using color iff
8132 - Only use color if standard output is a terminal.
8134 @vindex always @r{color option}
8137 Specifying @option{--color} and no @var{when} is equivalent to
8138 @option{--color=always}.
8139 If piping a colored listing through a pager like @command{less},
8140 use the pager's @option{-R} option to pass the color codes to the terminal.
8143 @vindex SHELL @r{environment variable, and color}
8144 Using the @option{--color} option may incur a noticeable
8145 performance penalty when run in a large directory,
8146 because the default settings require that @command{ls} @code{stat} every
8147 single file it lists.
8148 However, if you would like most of the file-type coloring
8149 but can live without the other coloring options (e.g.,
8150 executable, orphan, sticky, other-writable, capability), use
8151 @command{dircolors} to set the @env{LS_COLORS} environment variable like this,
8153 eval $(dircolors -p | perl -pe \
8154 's/^((CAP|S[ET]|O[TR]|M|E)\w+).*/$1 00/' | dircolors -)
8156 and on a @code{dirent.d_type}-capable file system, @command{ls}
8157 will perform only one @code{stat} call per command line argument.
8160 @itemx --classify [=@var{when}]
8161 @itemx --indicator-style=classify
8164 @opindex --indicator-style
8165 @cindex file type and executables, marking
8166 @cindex executables and file type, marking
8167 Append a character to each file name indicating the file type. Also,
8168 for regular files that are executable, append @samp{*}. The file type
8169 indicators are @samp{/} for directories, @samp{@@} for symbolic links,
8170 @samp{|} for FIFOs, @samp{=} for sockets, @samp{>} for doors,
8171 and nothing for regular files.
8172 @var{when} may be omitted, or one of:
8175 @vindex none @r{classify option}
8176 - Do not classify. This is the default.
8178 @vindex auto @r{classify option}
8179 @cindex terminal, using classify iff
8180 - Only classify if standard output is a terminal.
8182 @vindex always @r{classify option}
8185 Specifying @option{--classify} and no @var{when} is equivalent to
8186 @option{--classify=always}.
8187 @c The following sentence is the same as the one for -d.
8188 Do not follow symbolic links listed on the
8189 command line unless the @option{--dereference-command-line} (@option{-H}),
8190 @option{--dereference} (@option{-L}), or
8191 @option{--dereference-command-line-symlink-to-dir} options are specified.
8194 @itemx --indicator-style=file-type
8195 @opindex --file-type
8196 @opindex --indicator-style
8197 @cindex file type, marking
8198 Append a character to each file name indicating the file type. This is
8199 like @option{--classify} (@option{-F}, except that executables are not marked.
8201 @item --hyperlink [=@var{when}]
8202 @opindex --hyperlink
8203 @cindex hyperlink, linking to files
8204 Output codes recognized by some terminals to link
8205 to files using the @samp{file://} URI format.
8206 @var{when} may be omitted, or one of:
8209 @vindex none @r{hyperlink option}
8210 - Do not use hyperlinks at all. This is the default.
8212 @vindex auto @r{hyperlink option}
8213 @cindex terminal, using hyperlink iff
8214 - Only use hyperlinks if standard output is a terminal.
8216 @vindex always @r{hyperlink option}
8217 - Always use hyperlinks.
8219 Specifying @option{--hyperlink} and no @var{when} is equivalent to
8220 @option{--hyperlink=always}.
8222 @item --indicator-style=@var{word}
8223 @opindex --indicator-style
8224 Append a character indicator with style @var{word} to entry names,
8229 Do not append any character indicator; this is the default.
8231 Append @samp{/} for directories. This is the same as the @option{-p}
8234 Append @samp{/} for directories, @samp{@@} for symbolic links, @samp{|}
8235 for FIFOs, @samp{=} for sockets, and nothing for regular files. This is
8236 the same as the @option{--file-type} option.
8238 Append @samp{*} for executable regular files, otherwise behave as for
8239 @samp{file-type}. This is the same as the @option{--classify}
8240 (@option{-F}) option.
8246 @opindex --kibibytes
8247 Set the default block size to its normal value of 1024 bytes,
8248 overriding any contrary specification in environment variables
8249 (@pxref{Block size}). If @option{--block-size},
8250 @option{--human-readable} (@option{-h}), or @option{--si} options are used,
8251 they take precedence even if @option{--kibibytes} (@option{-k}) is placed after
8253 The @option{--kibibytes} (@option{-k}) option affects the
8254 per-directory block count written in long format,
8255 and the file system allocation written by the @option{--size} (@option{-s})
8256 option. It does not affect the file size in bytes that is written in
8260 @itemx --format=commas
8263 @opindex commas@r{, outputting between files}
8264 List files horizontally, with as many as will fit on each line,
8265 separated by @samp{, } (a comma and a space),
8266 and with no other information.
8269 @itemx --indicator-style=slash
8271 @opindex --indicator-style
8272 @cindex file type, marking
8273 Append a @samp{/} to directory names.
8276 @itemx --format=across
8277 @itemx --format=horizontal
8280 @opindex across@r{, listing files}
8281 @opindex horizontal@r{, listing files}
8282 List the files in columns, sorted horizontally.
8285 @itemx --tabsize=@var{cols}
8288 Assume that each tab stop is @var{cols} columns wide. The default is 8.
8289 @command{ls} uses tabs where possible in the output, for efficiency. If
8290 @var{cols} is zero, do not use tabs at all.
8292 Some terminal emulators might not properly align columns to the right of a
8293 TAB following a non-ASCII byte. You can avoid that issue by using the
8294 @option{-T0} option or put @code{TABSIZE=0} in your environment, to tell
8295 @command{ls} to align using spaces, not tabs.
8298 @itemx --width=@var{cols}
8302 Assume the screen is @var{cols} columns wide. The default is taken
8303 from the terminal settings if possible; otherwise the environment
8304 variable @env{COLUMNS} is used if it is set; otherwise the default
8305 is 80. With a @var{cols} value of @samp{0}, there is no limit on
8306 the length of the output line, and that single output line will
8307 be delimited with spaces, not tabs.
8312 This option is incompatible with the @option{--dired} (@option{-D}) option.
8313 This option also implies the options @option{--show-control-chars},
8314 @option{-1}, @option{--color=none}, and
8315 @option{--quoting-style=literal} (@option{-N}).
8320 @node Formatting file timestamps
8321 @subsection Formatting file timestamps
8323 By default, file timestamps are listed in abbreviated form, using
8324 a date like @samp{Mar 30@ @ 2020} for non-recent timestamps, and a
8325 date-without-year and time like @samp{Mar 30 23:45} for recent timestamps.
8326 This format can change depending on the current locale as detailed below.
8329 A timestamp is considered to be @dfn{recent} if it is less than six
8330 months old, and is not dated in the future. If a timestamp dated
8331 today is not listed in recent form, the timestamp is in the future,
8332 which means you probably have clock skew problems which may break
8333 programs like @command{make} that rely on file timestamps.
8334 @xref{File timestamps}.
8337 Timestamps are listed according to the time zone rules specified by
8338 the @env{TZ} environment variable, or by the system default rules if
8339 @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
8340 with @env{TZ}, libc, The GNU C Library Reference Manual}.
8342 The following option changes how file timestamps are printed.
8345 @item --time-style=@var{style}
8346 @opindex --time-style
8348 List timestamps in style @var{style}. The @var{style} should
8349 be one of the following:
8354 List timestamps using @var{format}, where @var{format} is interpreted
8355 like the format argument of @command{date} (@pxref{date invocation}).
8356 For example, @option{--time-style="+%Y-%m-%d %H:%M:%S"} causes
8357 @command{ls} to list timestamps like @samp{2020-03-30 23:45:56}. As
8358 with @command{date}, @var{format}'s interpretation is affected by the
8359 @env{LC_TIME} locale category.
8361 If @var{format} contains two format strings separated by a newline,
8362 the former is used for non-recent files and the latter for recent
8363 files; if you want output columns to line up, you may need to insert
8364 spaces in one of the two formats.
8367 List timestamps in full using ISO 8601-like date, time, and time zone
8368 components with nanosecond precision, e.g., @samp{2020-07-21
8369 23:45:56.477817180 -0400}. This style is equivalent to
8370 @samp{+%Y-%m-%d %H:%M:%S.%N %z}.
8372 This is useful because the time output includes all the information that
8373 is available from the operating system. For example, this can help
8374 explain @command{make}'s behavior, since GNU @command{make}
8375 uses the full timestamp to determine whether a file is out of date.
8378 List ISO 8601 date and time components with minute precision, e.g.,
8379 @samp{2020-03-30 23:45}. These timestamps are shorter than
8380 @samp{full-iso} timestamps, and are usually good enough for everyday
8381 work. This style is equivalent to @samp{+%Y-%m-%d %H:%M}.
8384 List ISO 8601 dates for non-recent timestamps (e.g.,
8385 @samp{2020-03-30@ }), and ISO 8601-like month, day, hour, and
8386 minute for recent timestamps (e.g., @samp{03-30 23:45}). These
8387 timestamps are uglier than @samp{long-iso} timestamps, but they carry
8388 nearly the same information in a smaller space and their brevity helps
8389 @command{ls} output fit within traditional 80-column output lines.
8390 The following two @command{ls} invocations are equivalent:
8395 ls -l --time-style="+%Y-%m-%d $newline%m-%d %H:%M"
8396 ls -l --time-style="iso"
8401 List timestamps in a locale-dependent form. For example, a French
8402 locale might list non-recent timestamps like @samp{30 mars@ @ @ 2020}
8403 and recent timestamps like @samp{30 mars@ @ 23:45}. Locale-dependent
8404 timestamps typically consume more space than @samp{iso} timestamps and
8405 are harder for programs to parse because locale conventions vary so
8406 widely, but they are easier for many people to read.
8408 The @env{LC_TIME} locale category specifies the timestamp format. The
8409 default POSIX locale uses timestamps like @samp{Mar 30@
8410 @ 2020} and @samp{Mar 30 23:45}; in this locale, the following two
8411 @command{ls} invocations are equivalent:
8416 ls -l --time-style="+%b %e %Y$newline%b %e %H:%M"
8417 ls -l --time-style="locale"
8420 Other locales behave differently. For example, in a German locale,
8421 @option{--time-style="locale"} might be equivalent to
8422 @option{--time-style="+%e. %b %Y $newline%e. %b %H:%M"}
8423 and might generate timestamps like @samp{30. M@"ar 2020@ } and
8424 @samp{30. M@"ar 23:45}.
8426 @item posix-@var{style}
8428 List POSIX-locale timestamps if the @env{LC_TIME} locale
8429 category is POSIX, @var{style} timestamps otherwise. For
8430 example, the @samp{posix-long-iso} style lists
8431 timestamps like @samp{Mar 30@ @ 2020} and @samp{Mar 30 23:45} when in
8432 the POSIX locale, and like @samp{2020-03-30 23:45} otherwise.
8437 You can specify the default value of the @option{--time-style} option
8438 with the environment variable @env{TIME_STYLE}; if @env{TIME_STYLE} is not set
8439 the default style is @samp{locale}. GNU Emacs 21.3 and
8440 later use the @option{--dired} option and therefore can parse any date
8441 format, but if you are using Emacs 21.1 or 21.2 and specify a
8442 non-POSIX locale you may need to set
8443 @samp{TIME_STYLE="posix-long-iso"}.
8445 To avoid certain denial-of-service attacks, timestamps that would be
8446 longer than 1000 bytes may be treated as errors.
8449 @node Formatting the file names
8450 @subsection Formatting the file names
8452 These options change how file names themselves are printed.
8458 @itemx --quoting-style=escape
8461 @opindex --quoting-style
8462 @cindex backslash sequences for file names
8463 Quote nongraphic characters in file names using alphabetic and octal
8464 backslash sequences like those used in C.
8468 @itemx --quoting-style=literal
8471 @opindex --quoting-style
8472 Do not quote file names. However, with @command{ls} nongraphic
8473 characters are still printed as question marks if the output is a
8474 terminal and you do not specify the @option{--show-control-chars}
8478 @itemx --hide-control-chars
8480 @opindex --hide-control-chars
8481 Print question marks instead of nongraphic characters in file names.
8482 This is the default if the output is a terminal and the program is
8487 @itemx --quoting-style=c
8489 @opindex --quote-name
8490 @opindex --quoting-style
8491 Enclose file names in double quotes and quote nongraphic characters as
8494 @item --quoting-style=@var{word}
8495 @opindex --quoting-style
8496 @cindex quoting style
8497 Use style @var{word} to quote file names and other strings that may
8498 contain arbitrary characters. The @var{word} should
8499 be one of the following:
8501 @macro quotingStyles
8504 Output strings as-is; this is the same as the @option{--literal} (@option{-N})
8507 Quote strings for the shell if they contain shell metacharacters or would
8508 cause ambiguous output.
8509 The quoting is suitable for POSIX-compatible shells like
8510 @command{bash}, but it does not always work for incompatible shells
8513 Quote strings for the shell, even if they would normally not require quoting.
8515 Like @samp{shell}, but also quoting non-printable characters using the POSIX
8516 proposed @samp{$''} syntax suitable for most shells.
8517 @item shell-escape-always
8518 Like @samp{shell-escape}, but quote strings even if they would
8519 normally not require quoting.
8521 Quote strings as for C character string literals, including the
8522 surrounding double-quote characters; this is the same as the
8523 @option{--quote-name} (@option{-Q}) option.
8525 Quote strings as for C character string literals, except omit the
8526 surrounding double-quote
8527 characters; this is the same as the @option{--escape} (@option{-b}) option.
8529 Quote strings as for C character string literals, except use
8530 surrounding quotation marks appropriate for the
8533 @c Use @t instead of @samp to avoid duplicate quoting in some output styles.
8534 Quote strings as for C character string literals, except use
8535 surrounding quotation marks appropriate for the locale, and quote
8536 @t{'like this'} instead of @t{"like
8537 this"} in the default C locale. This looks nicer on many displays.
8542 You can specify the default value of the @option{--quoting-style} option
8543 with the environment variable @env{QUOTING_STYLE}@. If that environment
8544 variable is not set, the default value is @samp{shell-escape} when the
8545 output is a terminal, and @samp{literal} otherwise.
8547 @item --show-control-chars
8548 @opindex --show-control-chars
8549 Print nongraphic characters as-is in file names.
8550 This is the default unless the output is a terminal and the program is
8556 @node dir invocation
8557 @section @command{dir}: Briefly list directory contents
8560 @cindex directory listing, brief
8562 @command{dir} is equivalent to @code{ls -C
8563 -b}; that is, by default files are listed in columns, sorted vertically,
8564 and special characters are represented by backslash escape sequences.
8566 @xref{ls invocation, @command{ls}}.
8569 @node vdir invocation
8570 @section @command{vdir}: Verbosely list directory contents
8573 @cindex directory listing, verbose
8575 @command{vdir} is equivalent to @code{ls -l
8576 -b}; that is, by default files are listed in long format and special
8577 characters are represented by backslash escape sequences.
8579 @xref{ls invocation, @command{ls}}.
8581 @node dircolors invocation
8582 @section @command{dircolors}: Color setup for @command{ls}
8586 @cindex setup for color
8588 @command{dircolors} outputs a sequence of shell commands to set up the
8589 terminal for color output from @command{ls} (and @command{dir}, etc.).
8593 eval "$(dircolors [@var{option}]@dots{} [@var{file}])"
8596 If @var{file} is specified, @command{dircolors} reads it to determine which
8597 colors to use for which file types and extensions. Otherwise, a
8598 precompiled database is used. For details on the format of these files,
8599 run @samp{dircolors --print-database}.
8601 To make @command{dircolors} read a @file{~/.dircolors} file if it
8602 exists, you can put the following lines in your @file{~/.bashrc} (or
8603 adapt them to your favorite shell):
8607 test -r $d && eval "$(dircolors $d)"
8611 @vindex SHELL @r{environment variable, and color}
8612 The output is a shell command to set the @env{LS_COLORS} environment
8613 variable. You can specify the shell syntax to use on the command line,
8614 or @command{dircolors} will guess it from the value of the @env{SHELL}
8615 environment variable.
8617 The program accepts the following options. Also see @ref{Common options}.
8622 @itemx --bourne-shell
8625 @opindex --bourne-shell
8626 @cindex Bourne shell syntax for color setup
8627 @cindex @command{sh} syntax for color setup
8628 Output Bourne shell commands. This is the default if the @env{SHELL}
8629 environment variable is set and does not end with @samp{csh} or
8638 @cindex C shell syntax for color setup
8639 @cindex @command{csh} syntax for color setup
8640 Output C shell commands. This is the default if @code{SHELL} ends with
8641 @command{csh} or @command{tcsh}.
8644 @itemx --print-database
8646 @opindex --print-database
8647 @cindex color database, printing
8648 @cindex database for color setup, printing
8649 @cindex printing color database
8650 Print the (compiled-in) default color configuration database. This
8651 output is itself a valid configuration file, and is fairly descriptive
8652 of the possibilities.
8654 @item --print-ls-colors
8655 @opindex --print-ls-colors
8656 @cindex printing ls colors
8657 Print the LS_COLORS entries on separate lines,
8658 each colored as per the color they represent.
8665 @node Basic operations
8666 @chapter Basic operations
8668 @cindex manipulating files
8670 This chapter describes the commands for basic file manipulation:
8671 copying, moving (renaming), and deleting (removing).
8674 * cp invocation:: Copy files.
8675 * dd invocation:: Convert and copy a file.
8676 * install invocation:: Copy files and set attributes.
8677 * mv invocation:: Move (rename) files.
8678 * rm invocation:: Remove files or directories.
8679 * shred invocation:: Remove files more securely.
8684 @section @command{cp}: Copy files and directories
8687 @cindex copying files and directories
8688 @cindex files, copying
8689 @cindex directories, copying
8691 @command{cp} copies files (or, optionally, directories). The copy is
8692 completely independent of the original. You can either copy one file to
8693 another, or copy arbitrarily many files to a destination directory.
8697 cp [@var{option}]@dots{} [-T] @var{source} @var{dest}
8698 cp [@var{option}]@dots{} @var{source}@dots{} @var{directory}
8699 cp [@var{option}]@dots{} -t @var{directory} @var{source}@dots{}
8704 If two file names are given, @command{cp} copies the first file to the
8708 If the @option{--target-directory} (@option{-t}) option is given, or
8709 failing that if the last file is a directory and the
8710 @option{--no-target-directory} (@option{-T}) option is not given,
8711 @command{cp} copies each @var{source} file to the specified directory,
8712 using the @var{source}s' names.
8715 Generally, files are written just as they are read. For exceptions,
8716 see the @option{--sparse} option below.
8718 By default, @command{cp} does not copy directories. However, the
8719 @option{-R}, @option{-a}, and @option{-r} options cause @command{cp} to
8720 copy recursively by descending into source directories and copying files
8721 to corresponding destination directories.
8723 When copying from a symbolic link, @command{cp} normally follows the
8724 link only when not copying recursively or when @option{--link}
8725 (@option{-l}) is used. This default can be overridden with the
8726 @option{--archive} (@option{-a}), @option{-d}, @option{--dereference}
8727 (@option{-L}), @option{--no-dereference} (@option{-P}), and
8728 @option{-H} options. If more than one of these options is specified,
8729 the last one silently overrides the others.
8731 When copying to a symbolic link, @command{cp} follows the
8732 link only when it refers to an existing regular file.
8733 However, when copying to a dangling symbolic link, @command{cp}
8734 refuses by default, and fails with a diagnostic, since the operation
8735 is inherently dangerous. This behavior is contrary to historical
8736 practice and to POSIX@.
8737 Set @env{POSIXLY_CORRECT} to make @command{cp} attempt to create
8738 the target of a dangling destination symlink, in spite of the possible risk.
8739 Also, when an option like
8740 @option{--backup} or @option{--link} acts to rename or remove the
8741 destination before copying, @command{cp} renames or removes the
8742 symbolic link rather than the file it points to.
8744 By default, @command{cp} copies the contents of special files only
8745 when not copying recursively. This default can be overridden with the
8746 @option{--copy-contents} option.
8748 @cindex self-backups
8749 @cindex backups, making only
8750 @command{cp} generally refuses to copy a file onto itself, with the
8751 following exception: if @option{--force --backup} is specified with
8752 @var{source} and @var{dest} identical, and referring to a regular file,
8753 @command{cp} will make a backup file, either regular or numbered, as
8754 specified in the usual ways (@pxref{Backup options}). This is useful when
8755 you simply want to make a backup of an existing file before changing it.
8757 The program accepts the following options. Also see @ref{Common options}.
8764 Preserve as much as possible of the structure and attributes of the
8765 original files in the copy (but do not attempt to preserve internal
8766 directory structure; i.e., @samp{ls -U} may list the entries in a copied
8767 directory in a different order).
8768 Try to preserve SELinux security context and extended attributes (xattr),
8769 but ignore any failure to do that and print no corresponding diagnostic.
8770 Equivalent to @option{-dR --preserve=all} with the reduced diagnostics.
8772 @item --attributes-only
8773 @opindex --attributes-only
8774 Copy only the specified attributes of the source file to the destination.
8775 If the destination already exists, do not alter its contents.
8776 See the @option{--preserve} option for controlling which attributes to copy.
8779 @itemx --backup[=@var{method}]
8782 @vindex VERSION_CONTROL
8783 @cindex backups, making
8784 @xref{Backup options}.
8785 Make a backup of each file that would otherwise be overwritten or removed.
8786 As a special case, @command{cp} makes a backup of @var{source} when the force
8787 and backup options are given and @var{source} and @var{dest} are the same
8788 name for an existing, regular file. One useful application of this
8789 combination of options is this tiny Bourne shell script:
8793 # Usage: backup FILE...
8794 # Create a GNU-style backup of each listed FILE.
8797 cp --backup --force --preserve=all -- "$i" "$i" || fail=1
8802 @item --copy-contents
8803 @cindex directories, copying recursively
8804 @cindex copying directories recursively
8805 @cindex recursively copying directories
8806 @cindex non-directories, copying as special files
8807 If copying recursively, copy the contents of any special files (e.g.,
8808 FIFOs and device files) as if they were regular files. This means
8809 trying to read the data in each source file and writing it to the
8810 destination. It is usually a mistake to use this option, as it
8811 normally has undesirable effects on special files like FIFOs and the
8812 ones typically found in the @file{/dev} directory. In most cases,
8813 @code{cp -R --copy-contents} will hang indefinitely trying to read
8814 from FIFOs and special files like @file{/dev/console}, and it will
8815 fill up your destination file system if you use it to copy @file{/dev/zero}.
8816 This option has no effect unless copying recursively, and it does not
8817 affect the copying of symbolic links.
8821 @cindex symbolic links, copying
8822 @cindex hard links, preserving
8823 Copy symbolic links as symbolic links rather than copying the files that
8824 they point to, and preserve hard links between source files in the copies.
8825 Equivalent to @option{--no-dereference --preserve=links}.
8831 When copying without this option and an existing destination file cannot
8832 be opened for writing, the copy fails. However, with @option{--force},
8833 when a destination file cannot be opened, @command{cp} then
8834 tries to recreate the file by first removing it. Note @option{--force}
8835 alone will not remove dangling symlinks.
8836 When this option is combined with
8837 @option{--link} (@option{-l}) or @option{--symbolic-link}
8838 (@option{-s}), the destination link is replaced, and unless
8839 @option{--backup} (@option{-b}) is also given there is no brief
8840 moment when the destination does not exist. Also see the
8841 description of @option{--remove-destination}.
8843 This option is independent of the @option{--interactive} or
8844 @option{-i} option: neither cancels the effect of the other.
8846 This option is ignored when the @option{--no-clobber} or @option{-n} option
8851 If a command line argument specifies a symbolic link, then copy the
8852 file it points to rather than the symbolic link itself. However,
8853 copy (preserving its nature) any symbolic link that is encountered
8854 via recursive traversal.
8857 @itemx --interactive
8859 @opindex --interactive
8860 When copying a file other than a directory, prompt whether to
8861 overwrite an existing destination file. The @option{-i} option overrides
8862 a previous @option{-n} option.
8868 Make hard links instead of copies of non-directories.
8871 @itemx --dereference
8873 @opindex --dereference
8874 Follow symbolic links when copying from them.
8875 With this option, @command{cp} cannot create a symbolic link.
8876 For example, a symlink (to regular file) in the source tree will be copied to
8877 a regular file in the destination tree.
8882 @opindex --no-clobber
8883 Do not overwrite an existing file; silently do nothing instead.
8884 This option overrides a previous
8885 @option{-i} option. This option is mutually exclusive with @option{-b} or
8886 @option{--backup} option.
8889 @itemx --no-dereference
8891 @opindex --no-dereference
8892 @cindex symbolic links, copying
8893 Copy symbolic links as symbolic links rather than copying the files that
8894 they point to. This option affects only symbolic links in the source;
8895 symbolic links in the destination are always followed if possible.
8898 @itemx --preserve[=@var{attribute_list}]
8901 @cindex file information, preserving, extended attributes, xattr
8902 Preserve the specified attributes of the original files.
8903 If specified, the @var{attribute_list} must be a comma-separated list
8904 of one or more of the following strings:
8908 Preserve the file mode bits and access control lists.
8910 Preserve the owner and group. On most modern systems,
8911 only users with appropriate privileges may change the owner of a file,
8913 may preserve the group ownership of a file only if they happen to be
8914 a member of the desired group.
8916 Preserve the times of last access and last modification, when possible.
8917 On older systems, it is not possible to preserve these attributes
8918 when the affected file is a symbolic link.
8919 However, many systems now provide the @code{utimensat} function,
8920 which makes it possible even for symbolic links.
8922 Preserve in the destination files
8923 any links between corresponding source files.
8924 Note that with @option{-L} or @option{-H}, this option can convert
8925 symbolic links to hard links. For example,
8927 $ mkdir c; : > a; ln -s a b; cp -aH a b c; ls -i1 c
8932 Note the inputs: @file{b} is a symlink to regular file @file{a},
8933 yet the files in destination directory, @file{c/}, are hard-linked.
8934 Since @option{-a} implies @option{--no-dereference} it would copy the symlink,
8935 but the later @option{-H} tells @command{cp} to dereference the command line
8936 arguments where it then sees two files with the same inode number.
8937 Then the @option{--preserve=links} option also implied by @option{-a}
8938 will preserve the perceived hard link.
8940 Here is a similar example that exercises @command{cp}'s @option{-L} option:
8942 $ mkdir b c; (cd b; : > a; ln -s a b); cp -aL b c; ls -i1 c/b
8948 Preserve SELinux security context of the file, or fail with full diagnostics.
8950 Preserve extended attributes of the file, or fail with full diagnostics.
8951 If @command{cp} is built without xattr support, ignore this option.
8952 If SELinux context, ACLs or Capabilities are implemented using xattrs,
8953 they are preserved implicitly by this option as well, i.e., even without
8954 specifying @option{--preserve=mode} or @option{--preserve=context}.
8956 Preserve all file attributes.
8957 Equivalent to specifying all of the above, but with the difference
8958 that failure to preserve SELinux security context or extended attributes
8959 does not change @command{cp}'s exit status. In contrast to @option{-a},
8960 all but @samp{Operation not supported} warnings are output.
8963 Using @option{--preserve} with no @var{attribute_list} is equivalent
8964 to @option{--preserve=mode,ownership,timestamps}.
8966 In the absence of this option, the permissions of existing destination
8967 files are unchanged. Each new file is created with the mode of the
8968 corresponding source file minus the set-user-ID, set-group-ID, and
8969 sticky bits as the create mode; the operating system then applies either
8970 the umask or a default ACL, possibly resulting in a more restrictive
8972 @xref{File permissions}.
8974 @item --no-preserve=@var{attribute_list}
8975 @cindex file information, preserving
8976 Do not preserve the specified attributes. The @var{attribute_list}
8977 has the same form as for @option{--preserve}.
8981 @cindex parent directories and @command{cp}
8982 Form the name of each destination file by appending to the target
8983 directory a slash and the specified name of the source file. The last
8984 argument given to @command{cp} must be the name of an existing directory.
8985 For example, the command:
8988 cp --parents a/b/c existing_dir
8992 copies the file @file{a/b/c} to @file{existing_dir/a/b/c}, creating
8993 any missing intermediate directories.
9000 @opindex --recursive
9001 @cindex directories, copying recursively
9002 @cindex copying directories recursively
9003 @cindex recursively copying directories
9004 @cindex non-directories, copying as special files
9005 Copy directories recursively. By default, do not follow symbolic
9006 links in the source unless used together with the @option{--link}
9007 (@option{-l}) option; see the @option{--archive} (@option{-a}), @option{-d},
9008 @option{--dereference} (@option{-L}), @option{--no-dereference}
9009 (@option{-P}), and @option{-H} options. Special files are copied by
9010 creating a destination file of the same type as the source; see the
9011 @option{--copy-contents} option. It is not portable to use
9012 @option{-r} to copy symbolic links or special files. On some
9013 non-GNU systems, @option{-r} implies the equivalent of
9014 @option{-L} and @option{--copy-contents} for historical reasons.
9015 Also, it is not portable to use @option{-R} to copy symbolic links
9016 unless you also specify @option{-P}, as POSIX allows
9017 implementations that dereference symbolic links by default.
9019 @item --reflink[=@var{when}]
9020 @opindex --reflink[=@var{when}]
9023 @cindex copy on write
9024 Perform a lightweight, copy-on-write (COW) copy, if supported by the
9025 file system. Once it has succeeded, beware that the source and destination
9026 files share the same data blocks as long as they remain unmodified.
9027 Thus, if an I/O error affects data blocks of one of the files,
9028 the other suffers the same fate.
9030 The @var{when} value can be one of the following:
9034 If the copy-on-write operation is not supported
9035 then report the failure for each file and exit with a failure status.
9036 Plain @option{--reflink} is equivalent to @option{--reflink=always}.
9039 If the copy-on-write operation is not supported then fall back
9040 to the standard copy behavior.
9041 This is the default if no @option{--reflink} option is given.
9044 Disable copy-on-write operation and use the standard copy behavior.
9047 This option is overridden by the @option{--link}, @option{--symbolic-link}
9048 and @option{--attributes-only} options, thus allowing it to be used
9049 to configure the default data copying behavior for @command{cp}.
9051 @item --remove-destination
9052 @opindex --remove-destination
9053 Remove each existing destination file before attempting to open it
9054 (contrast with @option{-f} above).
9056 @item --sparse=@var{when}
9057 @opindex --sparse=@var{when}
9058 @cindex sparse files, copying
9059 @cindex holes, copying files with
9060 @findex read @r{system call, and holes}
9061 A @dfn{sparse file} contains @dfn{holes}---a sequence of zero bytes that
9062 does not occupy any file system blocks; the @samp{read} system call
9063 reads these as zeros. This can both save considerable space and
9064 increase speed, since many binary files contain lots of consecutive zero
9065 bytes. By default, @command{cp} detects holes in input source files via a crude
9066 heuristic and makes the corresponding output file sparse as well.
9067 Only regular files may be sparse.
9069 The @var{when} value can be one of the following:
9073 The default behavior: if the input file is sparse, attempt to make
9074 the output file sparse, too. However, if an output file exists but
9075 refers to a non-regular file, then do not attempt to make it sparse.
9078 For each sufficiently long sequence of zero bytes in the input file,
9079 attempt to create a corresponding hole in the output file, even if the
9080 input file does not appear to be sparse.
9081 This is useful when the input file resides on a file system
9082 that does not support sparse files
9083 (for example, @samp{efs} file systems in SGI IRIX 5.3 and earlier),
9084 but the output file is on a type of file system that does support them.
9085 Holes may be created only in regular files, so if the destination file
9086 is of some other type, @command{cp} does not even try to make it sparse.
9089 Never make the output file sparse.
9090 This is useful in creating a file for use with the @command{mkswap} command,
9091 since such a file must not have any holes.
9094 For example, with the following alias, @command{cp} will use the
9095 minimum amount of space supported by the file system.
9096 (Older versions of @command{cp} can also benefit from
9097 @option{--reflink=auto} here.)
9100 alias cp='cp --sparse=always'
9103 @optStripTrailingSlashes
9106 @itemx --symbolic-link
9108 @opindex --symbolic-link
9109 @cindex symbolic links, copying with
9110 Make symbolic links instead of copies of non-directories. All source
9111 file names must be absolute (starting with @samp{/}) unless the
9112 destination files are in the current directory. This option merely
9113 results in an error message on systems that do not support symbolic links.
9119 @optNoTargetDirectory
9125 @cindex newer files, copying only
9126 Do not copy a non-directory that has an existing destination with the
9127 same or newer modification timestamp. If timestamps are being preserved,
9128 the comparison is to the source timestamp truncated to the
9129 resolutions of the destination file system and of the system calls
9130 used to update timestamps; this avoids duplicate work if several
9131 @samp{cp -pu} commands are executed with the same source and destination.
9132 This option is ignored if the @option{-n} or @option{--no-clobber}
9133 option is also specified.
9134 Also, if @option{--preserve=links} is also specified (like with @samp{cp -au}
9135 for example), that will take precedence; consequently, depending on the
9136 order that files are processed from the source, newer files in the destination
9137 may be replaced, to mirror hard links in the source.
9143 Print the name of each file before copying it.
9146 @itemx --one-file-system
9148 @opindex --one-file-system
9149 @cindex file systems, omitting copying to different
9150 Skip subdirectories that are on different file systems from the one that
9151 the copy started on.
9152 However, mount point directories @emph{are} copied.
9156 @itemx --context[=@var{context}]
9159 @cindex SELinux, setting/restoring security context
9160 @cindex security context
9161 Without a specified @var{context}, adjust the SELinux security context according
9162 to the system default type for destination files, similarly to the
9163 @command{restorecon} command.
9164 The long form of this option with a specific context specified,
9165 will set the context for newly created files only.
9166 With a specified context, if both SELinux and SMACK are disabled, a warning is
9170 This option is mutually exclusive with the @option{--preserve=context}
9171 option, and overrides the @option{--preserve=all} and @option{-a} options.
9179 @section @command{dd}: Convert and copy a file
9182 @cindex converting while copying a file
9184 @command{dd} copies input to output with a changeable I/O block size,
9185 while optionally performing conversions on the data. Synopses:
9188 dd [@var{operand}]@dots{}
9192 The only options are @option{--help} and @option{--version}.
9193 @xref{Common options}.
9195 By default, @command{dd} copies standard input to standard output.
9196 To copy, @command{dd} repeatedly does the following steps in order:
9200 Read an input block.
9203 If converting via @samp{sync}, pad as needed to meet the input block size.
9204 Pad with spaces if converting via @samp{block} or @samp{unblock}, NUL
9208 If @samp{bs=} is given and no conversion mentioned in steps (4) or (5)
9209 is given, output the data as a single block and skip all remaining steps.
9212 If the @samp{swab} conversion is given, swap each pair of input bytes.
9213 If the input data length is odd, preserve the last input byte
9214 (since there is nothing to swap it with).
9217 If any of the conversions @samp{swab}, @samp{block}, @samp{unblock},
9218 @samp{lcase}, @samp{ucase}, @samp{ascii}, @samp{ebcdic} and @samp{ibm}
9219 are given, do these conversions. These conversions operate
9220 independently of input blocking, and might deal with records that span
9224 Aggregate the resulting data into output blocks of the specified size,
9225 and output each output block in turn. Do not pad the last output block;
9226 it can be shorter than usual.
9229 @command{dd} accepts the following operands,
9230 whose syntax was inspired by the DD (data definition) statement of
9237 Read from @var{file} instead of standard input.
9241 Write to @var{file} instead of standard output. Unless
9242 @samp{conv=notrunc} is given, truncate @var{file} before writing it.
9244 @item ibs=@var{bytes}
9246 @cindex block size of input
9247 @cindex input block size
9248 Set the input block size to @var{bytes}.
9249 This makes @command{dd} read @var{bytes} per block.
9250 The default is 512 bytes.
9252 @item obs=@var{bytes}
9254 @cindex block size of output
9255 @cindex output block size
9256 Set the output block size to @var{bytes}.
9257 This makes @command{dd} write @var{bytes} per block.
9258 The default is 512 bytes.
9260 @item bs=@var{bytes}
9263 Set both input and output block sizes to @var{bytes}.
9264 This makes @command{dd} read and write @var{bytes} per block,
9265 overriding any @samp{ibs} and @samp{obs} settings.
9266 In addition, if no data-transforming @option{conv} operand is specified,
9267 input is copied to the output as soon as it's read,
9268 even if it is smaller than the block size.
9270 @item cbs=@var{bytes}
9272 @cindex block size of conversion
9273 @cindex conversion block size
9274 @cindex fixed-length records, converting to variable-length
9275 @cindex variable-length records, converting to fixed-length
9276 Set the conversion block size to @var{bytes}.
9277 When converting variable-length records to fixed-length ones
9278 (@option{conv=block}) or the reverse (@option{conv=unblock}),
9279 use @var{bytes} as the fixed record length.
9282 @itemx iseek=@var{n}
9285 Skip @var{n} @samp{ibs}-byte blocks in the input file before copying.
9286 If @var{n} ends in the letter @samp{B}, interpret @var{n}
9287 as a byte count rather than a block count.
9288 (@samp{B} and the @samp{iseek=} spelling are GNU extensions to POSIX.)
9291 @itemx oseek=@var{n}
9294 Skip @var{n} @samp{obs}-byte blocks in the output file before
9295 truncating or copying.
9296 If @var{n} ends in the letter @samp{B}, interpret @var{n}
9297 as a byte count rather than a block count.
9298 (@samp{B} and the @samp{oseek=} spelling are GNU extensions to POSIX.)
9302 Copy @var{n} @samp{ibs}-byte blocks from the input file, instead
9303 of everything until the end of the file.
9304 If @var{n} ends in the letter @samp{B},
9305 interpret @var{n} as a byte count rather than a block count;
9306 this is a GNU extension to POSIX.
9307 If short reads occur, as could be the case
9308 when reading from a pipe for example, @samp{iflag=fullblock}
9309 ensures that @samp{count=} counts complete input blocks
9310 rather than input read operations.
9311 As an extension to POSIX, @samp{count=0} copies zero blocks
9312 instead of copying all blocks.
9314 @item status=@var{level}
9316 Specify the amount of information printed.
9317 If this operand is given multiple times, the last one takes precedence.
9318 The @var{level} value can be one of the following:
9323 @opindex none @r{dd status=}
9324 Do not print any informational or warning messages to standard error.
9325 Error messages are output as normal.
9328 @opindex noxfer @r{dd status=}
9329 Do not print the final transfer rate and volume statistics
9330 that normally make up the last status line.
9333 @opindex progress @r{dd status=}
9334 Print the transfer rate and volume statistics on standard error,
9335 when processing each input block. Statistics are output
9336 on a single line at most once every second, but updates
9337 can be delayed when waiting on I/O.
9341 Transfer information is normally output to standard error upon
9342 receipt of the @samp{INFO} signal or when @command{dd} exits,
9343 and defaults to the following form in the C locale:
9347 116608+0 records out
9348 59703296 bytes (60 MB, 57 MiB) copied, 0.0427974 s, 1.4 GB/s
9351 The notation @samp{@var{w}+@var{p}} stands for @var{w} whole blocks
9352 and @var{p} partial blocks. A partial block occurs when a read or
9353 write operation succeeds but transfers less data than the block size.
9354 An additional line like @samp{1 truncated record} or @samp{10
9355 truncated records} is output after the @samp{records out} line if
9356 @samp{conv=block} processing truncated one or more input records.
9358 The @samp{status=} operand is a GNU extension to POSIX.
9360 @item conv=@var{conversion}[,@var{conversion}]@dots{}
9362 Convert the file as specified by the @var{conversion} argument(s).
9363 (No spaces around any comma(s).)
9370 @opindex ascii@r{, converting to}
9371 Convert EBCDIC to ASCII,
9372 using the conversion table specified by POSIX@.
9373 This provides a 1:1 translation for all 256 bytes.
9374 This implies @samp{conv=unblock}; input is converted to
9375 ASCII before trailing spaces are deleted.
9378 @opindex ebcdic@r{, converting to}
9379 Convert ASCII to EBCDIC@.
9380 This is the inverse of the @samp{ascii} conversion.
9381 This implies @samp{conv=block}; trailing spaces are added
9382 before being converted to EBCDIC@.
9385 @opindex alternate ebcdic@r{, converting to}
9386 This acts like @samp{conv=ebcdic}, except it
9387 uses the alternate conversion table specified by POSIX@.
9388 This is not a 1:1 translation, but reflects common historical practice
9389 for @samp{~}, @samp{[}, and @samp{]}.
9391 The @samp{ascii}, @samp{ebcdic}, and @samp{ibm} conversions are
9392 mutually exclusive. If you use any of these conversions, you should also
9393 use the @samp{cbs=} operand.
9396 @opindex block @r{(space-padding)}
9397 For each line in the input, output @samp{cbs} bytes, replacing the
9398 input newline with a space and truncating or padding input lines with
9399 spaces as necessary.
9403 Remove any trailing spaces in each @samp{cbs}-sized input block,
9404 and append a newline.
9406 The @samp{block} and @samp{unblock} conversions are mutually exclusive.
9407 If you use either of these conversions, you should also use the
9408 @samp{cbs=} operand.
9411 @opindex lcase@r{, converting to}
9412 Change uppercase letters to lowercase.
9415 @opindex ucase@r{, converting to}
9416 Change lowercase letters to uppercase.
9418 The @samp{lcase} and @samp{ucase} conversions are mutually exclusive.
9422 Try to seek rather than write NUL output blocks.
9423 On a file system that supports sparse files, this will create
9424 sparse output when extending the output file.
9425 Be careful when using this conversion in conjunction with
9426 @samp{conv=notrunc} or @samp{oflag=append}.
9427 With @samp{conv=notrunc}, existing data in the output file
9428 corresponding to NUL blocks from the input, will be untouched.
9429 With @samp{oflag=append} the seeks performed will be ineffective.
9430 Similarly, when the output is a device rather than a file,
9431 NUL input blocks are not copied, and therefore this conversion
9432 is most useful with virtual or pre zeroed devices.
9434 The @samp{sparse} conversion is a GNU extension to POSIX.
9437 @opindex swab @r{(byte-swapping)}
9438 @cindex byte-swapping
9439 Swap every pair of input bytes.
9442 @opindex sync @r{(padding with ASCII NULs)}
9443 Pad every input block to size of @samp{ibs} with trailing zero bytes.
9444 When used with @samp{block} or @samp{unblock}, pad with spaces instead of
9449 The following ``conversions'' are really file flags
9450 and don't affect internal processing:
9455 @cindex creating output file, requiring
9456 Fail if the output file already exists; @command{dd} must create the
9461 @cindex creating output file, avoiding
9462 Do not create the output file; the output file must already exist.
9464 The @samp{excl} and @samp{nocreat} conversions are mutually exclusive,
9465 and are GNU extensions to POSIX.
9469 @cindex truncating output file, avoiding
9470 Do not truncate the output file.
9474 @cindex read errors, ignoring
9475 Continue after read errors.
9479 @cindex synchronized data writes, before finishing
9480 Synchronize output data just before finishing,
9481 even if there were write errors.
9482 This forces a physical write of output data,
9483 so that even if power is lost the output data will be preserved.
9484 If neither this nor @samp{fsync} are specified, output is treated as
9485 usual with file systems, i.e., output data and metadata may be cached
9486 in primary memory for some time before the operating system physically
9487 writes it, and thus output data and metadata may be lost if power is lost.
9488 @xref{sync invocation}.
9489 This conversion is a GNU extension to POSIX.
9493 @cindex synchronized data and metadata writes, before finishing
9494 Synchronize output data and metadata just before finishing,
9495 even if there were write errors.
9496 This acts like @samp{fdatasync} except it also preserves output metadata,
9497 such as the last-modified time of the output file; for this reason it
9498 may be a bit slower than @samp{fdatasync} although the performance
9499 difference is typically insignificant for @command{dd}.
9500 This conversion is a GNU extension to POSIX.
9504 @item iflag=@var{flag}[,@var{flag}]@dots{}
9506 Access the input file using the flags specified by the @var{flag}
9507 argument(s). (No spaces around any comma(s).)
9509 @item oflag=@var{flag}[,@var{flag}]@dots{}
9511 Access the output file using the flags specified by the @var{flag}
9512 argument(s). (No spaces around any comma(s).)
9520 @cindex appending to the output file
9521 Write in append mode, so that even if some other process is writing to
9522 this file, every @command{dd} write will append to the current
9523 contents of the file. This flag makes sense only for output.
9524 If you combine this flag with the @samp{of=@var{file}} operand,
9525 you should also specify @samp{conv=notrunc} unless you want the
9526 output file to be truncated before being appended to.
9530 @cindex concurrent I/O
9531 Use concurrent I/O mode for data. This mode performs direct I/O
9532 and drops the POSIX requirement to serialize all I/O to the same file.
9533 A file cannot be opened in CIO mode and with a standard open at the
9539 Use direct I/O for data, avoiding the buffer cache.
9540 Note that the kernel may impose restrictions on read or write buffer sizes.
9541 For example, with an ext4 destination file system and a Linux-based kernel,
9542 using @samp{oflag=direct} will cause writes to fail with @code{EINVAL} if the
9543 output buffer size is not a multiple of 512.
9547 @cindex directory I/O
9549 Fail unless the file is a directory. Most operating systems do not
9550 allow I/O to a directory, so this flag has limited utility.
9554 @cindex synchronized data reads
9555 Use synchronized I/O for data. For the output file, this forces a
9556 physical write of output data on each write. For the input file,
9557 this flag can matter when reading from a remote file that has been
9558 written to synchronously by some other process. Metadata (e.g.,
9559 last-access and last-modified time) is not necessarily synchronized.
9563 @cindex synchronized data and metadata I/O
9564 Use synchronized I/O for both data and metadata.
9568 @cindex discarding file cache
9569 Request to discard the system data cache for a file.
9570 When count=0 all cached data for the file is specified,
9571 otherwise the cache is dropped for the processed
9572 portion of the file. Also when count=0,
9573 failure to discard the cache is diagnosed
9574 and reflected in the exit status.
9576 Note data that is not already persisted to storage will not
9577 be discarded from cache, so note the use of the @samp{sync} conversions
9578 in the examples below, which are used to maximize the
9579 effectiveness of the @samp{nocache} flag.
9581 Here are some usage examples:
9584 # Advise to drop cache for whole file
9585 dd if=ifile iflag=nocache count=0
9587 # Ensure drop cache for the whole file
9588 dd of=ofile oflag=nocache conv=notrunc,fdatasync count=0
9590 # Advise to drop cache for part of file
9591 # Note the kernel will only consider complete and
9592 # already persisted pages.
9593 dd if=ifile iflag=nocache skip=10 count=10 of=/dev/null
9595 # Stream data using just the read-ahead cache.
9596 # See also the @samp{direct} flag.
9597 dd if=ifile of=ofile iflag=nocache oflag=nocache,sync
9602 @cindex nonblocking I/O
9603 Use non-blocking I/O.
9607 @cindex access timestamp
9608 Do not update the file's access timestamp.
9609 @xref{File timestamps}.
9610 Some older file systems silently ignore this flag, so it is a good
9611 idea to test it on your files before relying on it.
9615 @cindex controlling terminal
9616 Do not assign the file to be a controlling terminal for @command{dd}.
9617 This has no effect when the file is not a terminal.
9618 On many hosts (e.g., GNU/Linux hosts), this flag has no effect
9623 @cindex symbolic links, following
9624 Do not follow symbolic links.
9629 Fail if the file has multiple hard links.
9634 Use binary I/O@. This flag has an effect only on nonstandard
9635 platforms that distinguish binary from text I/O.
9640 Use text I/O@. Like @samp{binary}, this flag has no effect on
9645 Accumulate full blocks from input. The @code{read} system call
9646 may return early if a full block is not available.
9647 When that happens, continue calling @code{read} to fill the remainder
9649 This flag can be used only with @code{iflag}.
9650 This flag is useful with pipes for example
9651 as they may return short reads. In that case,
9652 this flag is needed to ensure that a @samp{count=} argument is
9653 interpreted as a block count rather than a count of read operations.
9657 These flags are all GNU extensions to POSIX.
9658 They are not supported on all systems, and @samp{dd} rejects
9659 attempts to use them when they are not supported. When reading from
9660 standard input or writing to standard output, the @samp{nofollow} and
9661 @samp{noctty} flags should not be specified, and the other flags
9662 (e.g., @samp{nonblock}) can affect how other processes behave with the
9663 affected file descriptors, even after @command{dd} exits.
9667 The behavior of @command{dd} is unspecified if operands other than
9668 @samp{conv=}, @samp{iflag=}, @samp{oflag=}, and @samp{status=} are
9669 specified more than once.
9671 @cindex multipliers after numbers
9672 The numeric-valued strings above (@var{n} and @var{bytes})
9673 are unsigned decimal integers that
9674 can be followed by a multiplier: @samp{b}=512, @samp{c}=1,
9675 @samp{w}=2, @samp{x@var{m}}=@var{m}, or any of the
9676 standard block size suffixes like @samp{k}=1024 (@pxref{Block size}).
9677 These multipliers are GNU extensions to POSIX, except that
9678 POSIX allows @var{bytes} to be followed by @samp{k}, @samp{b}, and
9680 Block sizes (i.e., specified by @var{bytes} strings) must be nonzero.
9682 Any block size you specify via @samp{bs=}, @samp{ibs=}, @samp{obs=}, @samp{cbs=}
9683 should not be too large---values larger than a few megabytes
9684 are generally wasteful or (as in the gigabyte..exabyte case) downright
9685 counterproductive or error-inducing.
9687 To process data with offset or size that is not a multiple of the I/O
9688 block size, you can use a numeric string @var{n} that ends in the
9690 For example, the following shell commands copy data
9691 in 1 MiB blocks between a flash drive and a tape, but do not save
9692 or restore a 512-byte area at the start of the flash drive:
9698 # Copy all but the initial 512 bytes from flash to tape.
9699 dd if=$flash iseek=512B bs=1MiB of=$tape
9701 # Copy from tape back to flash, leaving initial 512 bytes alone.
9702 dd if=$tape bs=1MiB of=$flash oseek=512B
9706 @cindex storage devices, failing
9707 For failing storage devices, other tools come with a great variety of extra
9708 functionality to ease the saving of as much data as possible before the
9709 device finally dies, e.g.
9710 @uref{https://www.gnu.org/software/ddrescue/, GNU @command{ddrescue}}.
9711 However, in some cases such a tool is not available or the administrator
9712 feels more comfortable with the handling of @command{dd}.
9713 As a simple rescue method, call @command{dd} as shown in the following
9714 example: the operand @samp{conv=noerror,sync} is used to continue
9715 after read errors and to pad out bad reads with NULs, while
9716 @samp{iflag=fullblock} caters for short reads (which traditionally never
9717 occur on flash or similar devices):
9720 # Rescue data from an (unmounted!) partition of a failing device.
9721 dd conv=noerror,sync iflag=fullblock </dev/sda1 > /mnt/rescue.img
9724 Sending an @samp{INFO} signal (or @samp{USR1} signal where that is unavailable)
9725 to a running @command{dd} process makes it print I/O statistics to
9726 standard error and then resume copying. In the example below,
9727 @command{dd} is run in the background to copy 5GB of data.
9728 The @command{kill} command makes it output intermediate I/O statistics,
9729 and when @command{dd} completes normally or is killed by the
9730 @code{SIGINT} signal, it outputs the final statistics.
9733 # Ignore the signal so we never inadvertently terminate the dd child.
9734 # Note this is not needed when SIGINFO is available.
9737 # Run dd with the fullblock iflag to avoid short reads
9738 # which can be triggered by reception of signals.
9739 dd iflag=fullblock if=/dev/zero of=/dev/null count=5000000 bs=1000 & pid=$!
9741 # Output stats every second.
9742 while kill -s USR1 $pid 2>/dev/null; do sleep 1; done
9745 The above script will output in the following format:
9748 3441325+0 records in
9749 3441325+0 records out
9750 3441325000 bytes (3.4 GB, 3.2 GiB) copied, 1.00036 s, 3.4 GB/s
9751 5000000+0 records in
9752 5000000+0 records out
9753 5000000000 bytes (5.0 GB, 4.7 GiB) copied, 1.44433 s, 3.5 GB/s
9756 The @samp{status=progress} operand periodically updates the last line
9757 of the transfer statistics above.
9759 @vindex POSIXLY_CORRECT
9760 On systems lacking the @samp{INFO} signal @command{dd} responds to the
9761 @samp{USR1} signal instead, unless the @env{POSIXLY_CORRECT}
9762 environment variable is set.
9767 @node install invocation
9768 @section @command{install}: Copy files and set attributes
9771 @cindex copying files and setting attributes
9773 @command{install} copies files while setting their file mode bits and, if
9774 possible, their owner and group. Synopses:
9777 install [@var{option}]@dots{} [-T] @var{source} @var{dest}
9778 install [@var{option}]@dots{} @var{source}@dots{} @var{directory}
9779 install [@var{option}]@dots{} -t @var{directory} @var{source}@dots{}
9780 install [@var{option}]@dots{} -d @var{directory}@dots{}
9785 If two file names are given, @command{install} copies the first file to the
9789 If the @option{--target-directory} (@option{-t}) option is given, or
9790 failing that if the last file is a directory and the
9791 @option{--no-target-directory} (@option{-T}) option is not given,
9792 @command{install} copies each @var{source} file to the specified
9793 directory, using the @var{source}s' names.
9796 If the @option{--directory} (@option{-d}) option is given,
9797 @command{install} creates each @var{directory} and any missing parent
9798 directories. Parent directories are created with mode
9799 @samp{u=rwx,go=rx} (755), regardless of the @option{-m} option or the
9800 current umask. @xref{Directory Setuid and Setgid}, for how the
9801 set-user-ID and set-group-ID bits of parent directories are inherited.
9804 @cindex Makefiles, installing programs in
9805 @command{install} is similar to @command{cp}, but allows you to control the
9806 attributes of destination files. It is typically used in Makefiles to
9807 copy programs into their destination directories. It refuses to copy
9808 files onto themselves.
9810 @cindex extended attributes, xattr
9811 @command{install} never preserves extended attributes (xattr).
9813 The program accepts the following options. Also see @ref{Common options}.
9823 Compare content of source and destination files, and if there would be no
9824 change to the destination content, owner, group, permissions, and possibly
9825 SELinux context, then do not modify the destination at all.
9826 Note this option is best used in conjunction with @option{--user},
9827 @option{--group} and @option{--mode} options, lest @command{install}
9828 incorrectly determines the default attributes that installed files would have
9829 (as it doesn't consider setgid directories and POSIX default ACLs for example).
9830 This could result in redundant copies or attributes that are not reset to the
9835 Ignored; for compatibility with old Unix versions of @command{install}.
9839 Create any missing parent directories of @var{dest},
9840 then copy @var{source} to @var{dest}.
9841 Explicitly specifying the @option{--target-directory=@var{dir}} will similarly
9842 ensure the presence of that hierarchy before copying @var{source} arguments.
9847 @opindex --directory
9848 @cindex directories, creating with given attributes
9849 @cindex parent directories, creating missing
9850 @cindex leading directories, creating missing
9851 Create any missing parent directories, giving them the default
9852 attributes. Then create each given directory, setting their owner,
9853 group and mode as given on the command line or to the defaults.
9855 @item -g @var{group}
9856 @itemx --group=@var{group}
9859 @cindex group ownership of installed files, setting
9860 Set the group ownership of installed files or directories to
9861 @var{group}. The default is the process's current group. @var{group}
9862 may be either a group name or a numeric group ID.
9865 @itemx --mode=@var{mode}
9868 @cindex permissions of installed files, setting
9869 Set the file mode bits for the installed file or directory to @var{mode},
9870 which can be either an octal number, or a symbolic mode as in
9871 @command{chmod}, with @samp{a=} (no access allowed to anyone) as the
9872 point of departure (@pxref{File permissions}).
9873 The default mode is @samp{u=rwx,go=rx,a-s}---read, write, and
9874 execute for the owner, read and execute for group and other, and with
9875 set-user-ID and set-group-ID disabled.
9876 This default is not quite the same as @samp{755}, since it disables
9877 instead of preserving set-user-ID and set-group-ID on directories.
9878 @xref{Directory Setuid and Setgid}.
9880 @item -o @var{owner}
9881 @itemx --owner=@var{owner}
9884 @cindex ownership of installed files, setting
9885 @cindex appropriate privileges
9886 @vindex root @r{as default owner}
9887 If @command{install} has appropriate privileges (is run as root), set the
9888 ownership of installed files or directories to @var{owner}. The default
9889 is @code{root}. @var{owner} may be either a user name or a numeric user
9892 @item --preserve-context
9893 @opindex --preserve-context
9895 @cindex security context
9896 Preserve the SELinux security context of files and directories.
9897 Failure to preserve the context in all of the files or directories
9898 will result in an exit status of 1. If SELinux is disabled then
9899 print a warning and ignore the option.
9902 @itemx --preserve-timestamps
9904 @opindex --preserve-timestamps
9905 @cindex timestamps of installed files, preserving
9906 Set the time of last access and the time of last modification of each
9907 installed file to match those of each corresponding original file.
9908 When a file is installed without this option, its last access and
9909 last modification timestamps are both set to the time of installation.
9910 This option is useful if you want to use the last modification timestamps
9911 of installed files to keep track of when they were last built as opposed
9912 to when they were last installed.
9918 @cindex symbol table information, stripping
9919 @cindex stripping symbol table information
9920 Strip the symbol tables from installed binary executables.
9922 @item --strip-program=@var{program}
9923 @opindex --strip-program
9924 @cindex symbol table information, stripping, program
9925 Program used to strip binaries.
9930 Also specifying the @option{-D} option will ensure the directory is present.
9932 @optNoTargetDirectory
9938 Print the name of each file before copying it.
9941 This option is mutually exclusive with the @option{--preserve-context} option.
9950 @section @command{mv}: Move (rename) files
9954 @command{mv} moves or renames files (or directories). Synopses:
9957 mv [@var{option}]@dots{} [-T] @var{source} @var{dest}
9958 mv [@var{option}]@dots{} @var{source}@dots{} @var{directory}
9959 mv [@var{option}]@dots{} -t @var{directory} @var{source}@dots{}
9964 If two file names are given, @command{mv} moves the first file to the
9968 If the @option{--target-directory} (@option{-t}) option is given, or
9969 failing that if the last file is a directory and the
9970 @option{--no-target-directory} (@option{-T}) option is not given,
9971 @command{mv} moves each @var{source} file to the specified
9972 directory, using the @var{source}s' names.
9975 @command{mv} can move any type of file from one file system to another.
9976 Prior to version @code{4.0} of the fileutils,
9977 @command{mv} could move only regular files between file systems.
9978 For example, now @command{mv} can move an entire directory hierarchy
9979 including special device files from one partition to another. It first
9980 uses some of the same code that's used by @code{cp -a} to copy the
9981 requested directories and files, then (assuming the copy succeeded)
9982 it removes the originals. If the copy fails, then the part that was
9983 copied to the destination partition is removed. If you were to copy
9984 three directories from one partition to another and the copy of the first
9985 directory succeeded, but the second didn't, the first would be left on
9986 the destination partition and the second and third would be left on the
9989 @cindex extended attributes, xattr
9990 @command{mv} always tries to copy extended attributes (xattr), which may
9991 include SELinux context, ACLs or Capabilities.
9992 Upon failure all but @samp{Operation not supported} warnings are output.
9994 @cindex prompting, and @command{mv}
9995 If a destination file exists but is normally unwritable, standard input
9996 is a terminal, and the @option{-f} or @option{--force} option is not given,
9997 @command{mv} prompts the user for whether to replace the file. (You might
9998 own the file, or have write permission on its directory.) If the
9999 response is not affirmative, the file is skipped.
10001 @emph{Warning}: Avoid specifying a source name with a trailing slash,
10002 when it might be a symlink to a directory.
10003 Otherwise, @command{mv} may do something very surprising, since
10004 its behavior depends on the underlying rename system call.
10005 On a system with a modern Linux-based kernel, it fails with
10006 @code{errno=ENOTDIR}@.
10007 However, on other systems (at least FreeBSD 6.1 and Solaris 10) it silently
10008 renames not the symlink but rather the directory referenced by the symlink.
10009 @xref{Trailing slashes}.
10011 @emph{Note}: @command{mv} will only replace empty directories in the
10012 destination. Conflicting populated directories are skipped with a diagnostic.
10014 The program accepts the following options. Also see @ref{Common options}.
10024 @cindex prompts, omitting
10025 Do not prompt the user before removing a destination file.
10027 If you specify more than one of the @option{-i}, @option{-f}, @option{-n}
10028 options, only the final one takes effect.
10033 @itemx --interactive
10035 @opindex --interactive
10036 @cindex prompts, forcing
10037 Prompt whether to overwrite each existing destination file, regardless
10038 of its permissions.
10039 If the response is not affirmative, the file is skipped.
10043 @itemx --no-clobber
10045 @opindex --no-clobber
10046 @cindex prompts, omitting
10047 Do not overwrite an existing file; silently do nothing instead.
10049 This option is mutually exclusive with @option{-b} or @option{--backup} option.
10055 @cindex newer files, moving only
10056 Do not move a non-directory that has an existing destination with the
10057 same or newer modification timestamp.
10058 If the move is across file system boundaries, the comparison is to the
10059 source timestamp truncated to the resolutions of the destination file
10060 system and of the system calls used to update timestamps; this avoids
10061 duplicate work if several @samp{mv -u} commands are executed with the
10062 same source and destination.
10063 This option is ignored if the @option{-n} or @option{--no-clobber}
10064 option is also specified.
10070 Print the name of each file before moving it.
10072 @optStripTrailingSlashes
10076 @optTargetDirectory
10078 @optNoTargetDirectory
10084 @cindex SELinux, restoring security context
10085 @cindex security context
10086 This option functions similarly to the @command{restorecon} command,
10087 by adjusting the SELinux security context according
10088 to the system default type for destination files and each created directory.
10095 @node rm invocation
10096 @section @command{rm}: Remove files or directories
10099 @cindex removing files or directories
10101 @command{rm} removes each given @var{file}. By default, it does not remove
10102 directories. Synopsis:
10105 rm [@var{option}]@dots{} [@var{file}]@dots{}
10108 @cindex prompting, and @command{rm}
10109 If the @option{-I} or @option{--interactive=once} option is given,
10110 and there are more than three files or the @option{-r}, @option{-R},
10111 or @option{--recursive} are given, then @command{rm} prompts the user
10112 for whether to proceed with the entire operation. If the response is
10113 not affirmative, the entire command is aborted.
10115 Otherwise, if a file is unwritable, standard input is a terminal, and
10116 the @option{-f} or @option{--force} option is not given, or the
10117 @option{-i} or @option{--interactive=always} option @emph{is} given,
10118 @command{rm} prompts the user for whether to remove the file.
10119 If the response is not affirmative, the file is skipped.
10121 Any attempt to remove a file whose last file name component is
10122 @file{.} or @file{..} is rejected without any prompting, as mandated
10125 @emph{Warning}: If you use @command{rm} to remove a file, it is usually
10126 possible to recover the contents of that file. If you want more assurance
10127 that the contents are unrecoverable, consider using @command{shred}.
10129 The program accepts the following options. Also see @ref{Common options}.
10137 @cindex directories, removing
10138 Remove the listed directories if they are empty.
10144 Ignore nonexistent files and missing operands, and never prompt the user.
10145 Ignore any previous @option{--interactive} (@option{-i}) option.
10149 Prompt whether to remove each file.
10150 If the response is not affirmative, the file is skipped.
10151 Ignore any previous @option{--force} (@option{-f}) option.
10152 Equivalent to @option{--interactive=always}.
10156 Prompt once whether to proceed with the command, if more than three
10157 files are named or if a recursive removal is requested. Ignore any
10158 previous @option{--force} (@option{-f}) option. Equivalent to
10159 @option{--interactive=once}.
10161 @item --interactive [=@var{when}]
10162 @opindex --interactive
10163 Specify when to issue an interactive prompt. @var{when} may be
10164 omitted, or one of:
10167 @vindex never @r{interactive option}
10168 - Do not prompt at all.
10170 @vindex once @r{interactive option}
10171 - Prompt once if more than three files are named or if a recursive
10172 removal is requested. Equivalent to @option{-I}.
10174 @vindex always @r{interactive option}
10175 - Prompt for every file being removed. Equivalent to @option{-i}.
10177 @option{--interactive} with no @var{when} is equivalent to
10178 @option{--interactive=always}.
10180 @item --one-file-system
10181 @opindex --one-file-system
10182 @cindex one file system, restricting @command{rm} to
10183 When removing a hierarchy recursively, skip any directory that is on a
10184 file system different from that of the corresponding command line argument.
10186 This option is useful when removing a build ``chroot'' hierarchy,
10187 which normally contains no valuable data. However, it is not uncommon
10188 to bind-mount @file{/home} into such a hierarchy, to make it easier to
10189 use one's start-up file. The catch is that it's easy to forget to
10190 unmount @file{/home}. Then, when you use @command{rm -rf} to remove
10191 your normally throw-away chroot, that command will remove everything
10192 under @file{/home}, too.
10193 Use the @option{--one-file-system} option, and it will
10194 warn about and skip directories on other file systems.
10195 Of course, this will not save your @file{/home} if it and your
10196 chroot happen to be on the same file system.
10197 See also @option{--preserve-root=all} to protect command line arguments
10200 @item --preserve-root [=all]
10201 @opindex --preserve-root
10202 @cindex root directory, disallow recursive destruction
10203 Fail upon any attempt to remove the root directory, @file{/},
10204 when used with the @option{--recursive} option.
10205 This is the default behavior.
10206 @xref{Treating / specially}.
10207 When @samp{all} is specified, reject any command line argument
10208 that is not on the same file system as its parent.
10210 @item --no-preserve-root
10211 @opindex --no-preserve-root
10212 @cindex root directory, allow recursive destruction
10213 Do not treat @file{/} specially when removing recursively.
10214 This option is not recommended unless you really want to
10215 remove all the files on your computer.
10216 @xref{Treating / specially}.
10223 @opindex --recursive
10224 @cindex directories, removing (recursively)
10225 Remove the listed directories and their contents recursively.
10231 Print the name of each file before removing it.
10235 @cindex files beginning with @samp{-}, removing
10236 @cindex @samp{-}, removing files beginning with
10237 One common question is how to remove files whose names begin with a
10238 @samp{-}. GNU @command{rm}, like every program that uses the @code{getopt}
10239 function to parse its arguments, lets you use the @samp{--} option to
10240 indicate that all following arguments are non-options. To remove a file
10241 called @file{-f} in the current directory, you could type either:
10254 @opindex - @r{and Unix @command{rm}}
10255 The Unix @command{rm} program's use of a single @samp{-} for this purpose
10256 predates the development of the @code{getopt} standard syntax.
10261 @node shred invocation
10262 @section @command{shred}: Remove files more securely
10265 @cindex data, erasing
10266 @cindex erasing data
10268 @command{shred} overwrites devices or files, to help prevent even
10269 extensive forensics from recovering the data.
10271 Ordinarily when you remove a file (@pxref{rm invocation}), its data
10272 and metadata are not actually destroyed. Only the file's directory
10273 entry is removed, and the file's storage is reclaimed only when no
10274 process has the file open and no other directory entry links to the
10275 file. And even if file's data and metadata's storage space is freed
10276 for further reuse, there are undelete utilities that will attempt to
10277 reconstruct the file from the data in freed storage, and that can
10278 bring the file back if the storage was not rewritten.
10280 On a busy system with a nearly-full device, space can get reused in a few
10281 seconds. But there is no way to know for sure. And although the
10282 undelete utilities and already-existing processes require insider or
10283 superuser access, you may be wary of the superuser,
10284 of processes running on your behalf, or of attackers
10285 that can physically access the storage device. So if you have sensitive
10286 data, you may want to be sure that recovery is not possible
10287 by plausible attacks like these.
10289 The best way to remove something irretrievably is to destroy the media
10290 it's on with acid, melt it down, or the like. For cheap removable media
10291 this is often the preferred method. However, some storage devices
10292 are expensive or are harder to destroy, so the @command{shred} utility tries
10293 to achieve a similar effect non-destructively, by overwriting the file
10294 with non-sensitive data.
10296 @strong{Please note} that @command{shred} relies on a crucial
10297 assumption: that the file system and hardware overwrite data in place.
10298 Although this is common and is the traditional
10299 way to do things, but many modern file system designs do not satisfy this
10300 assumption. Exceptions include:
10305 Log-structured or journaled file systems, such as ext3/ext4 (in
10306 @code{data=journal} mode), Btrfs, NTFS, ReiserFS, XFS, ZFS, file
10307 systems supplied with AIX and Solaris, etc., when they are configured to
10311 File systems that write redundant data and carry on even if some writes
10312 fail, such as RAID-based file systems.
10315 File systems that make snapshots, such as Network Appliance's NFS server.
10318 File systems that cache in temporary locations, such as NFS version 3
10322 Compressed file systems.
10325 For ext3 and ext4 file systems, @command{shred} is less effective
10326 when the file system is in @code{data=journal}
10327 mode, which journals file data in addition to just metadata. In both
10328 the @code{data=ordered} (default) and @code{data=writeback} modes,
10329 @command{shred} works as usual. The ext3/ext4 journaling modes can be changed
10330 by adding the @code{data=something} option to the mount options for a
10331 particular file system in the @file{/etc/fstab} file, as documented in
10332 the @command{mount} man page (@samp{man mount}). Alternatively, if
10333 you know how large the journal is, you can shred the journal by
10334 shredding enough file data so that the journal cycles around and fills
10335 up with shredded data.
10337 If you are not sure how your file system operates, then you should assume
10338 that it does not overwrite data in place, which means @command{shred} cannot
10339 reliably operate on regular files in your file system.
10341 Generally speaking, it is more reliable to shred a device than a file,
10342 since this bypasses file system design issues mentioned above.
10343 However, devices are also problematic for shredding, for reasons
10344 such as the following:
10349 Solid-state storage devices (SSDs) typically do wear leveling to
10350 prolong service life, and this means writes are distributed to other
10351 blocks by the hardware, so ``overwritten'' data blocks are still
10352 present in the underlying device.
10355 Most storage devices map out bad blocks invisibly to
10356 the application; if the bad blocks contain sensitive data,
10357 @command{shred} won't be able to destroy it.
10360 With some obsolete storage technologies,
10361 it may be possible to take (say) a floppy disk back
10362 to a laboratory and use a lot of sensitive (and expensive) equipment
10363 to look for the faint ``echoes'' of the original data underneath the
10364 overwritten data. With these older technologies, if the file has been
10365 overwritten only once, it's reputedly not even that hard. Luckily,
10366 this kind of data recovery has become difficult, and there is no
10367 public evidence that today's higher-density storage devices can be
10368 analyzed in this way.
10370 The @command{shred} command can use many overwrite passes,
10371 with data patterns chosen to
10372 maximize the damage they do to the old data.
10373 By default the patterns are designed for best effect on hard drives using
10374 now-obsolete technology; for newer devices, a single pass should suffice.
10375 For more details, see the source code and Peter Gutmann's paper
10376 @uref{https://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html,
10377 @cite{Secure Deletion of Data from Magnetic and Solid-State Memory}},
10378 from the proceedings of the Sixth USENIX Security Symposium (San Jose,
10379 California, July 22--25, 1996).
10382 @command{shred} makes no attempt to detect or report these problems, just as
10383 it makes no attempt to do anything about backups. However, since it is
10384 more reliable to shred devices than files, @command{shred} by default does
10385 not deallocate or remove the output file. This default is more suitable
10386 for devices, which typically cannot be deallocated and should not be
10389 Finally, consider the risk of backups and mirrors.
10390 File system backups and remote mirrors may contain copies of the
10391 file that cannot be removed, and that will allow a shredded file
10392 to be recovered later. So if you keep any data you may later want
10393 to destroy using @command{shred}, be sure that it is not backed up or mirrored.
10396 shred [@var{option}]@dots{} @var{file}[@dots{}]
10399 The program accepts the following options. Also see @ref{Common options}.
10407 @cindex force deletion
10408 Override file permissions if necessary to allow overwriting.
10410 @item -n @var{number}
10411 @itemx --iterations=@var{number}
10412 @opindex -n @var{number}
10413 @opindex --iterations=@var{number}
10414 @cindex iterations, selecting the number of
10415 By default, @command{shred} uses @value{SHRED_DEFAULT_PASSES} passes of
10416 overwrite. You can reduce this to save time, or increase it if you think it's
10417 appropriate. After 25 passes all of the internal overwrite patterns will have
10418 been used at least once.
10420 @item --random-source=@var{file}
10421 @opindex --random-source
10422 @cindex random source for shredding
10423 Use @var{file} as a source of random data used to overwrite and to
10424 choose pass ordering. @xref{Random sources}.
10426 @item -s @var{bytes}
10427 @itemx --size=@var{bytes}
10428 @opindex -s @var{bytes}
10429 @opindex --size=@var{bytes}
10430 @cindex size of file to shred
10431 Shred the first @var{bytes} bytes of the file. The default is to shred
10432 the whole file. @var{bytes} can be followed by a size specification like
10433 @samp{K}, @samp{M}, or @samp{G} to specify a multiple. @xref{Block size}.
10436 @itemx --remove[=@var{how}]
10439 @opindex --remove=unlink
10440 @opindex --remove=wipe
10441 @opindex --remove=wipesync
10442 @cindex removing files after shredding
10443 After shredding a file, deallocate it (if possible) and then remove it.
10444 If a file has multiple links, only the named links will be removed.
10445 Often the file name is less sensitive than the file data, in which case
10446 the optional @var{how} parameter, supported with the long form option,
10447 gives control of how to more efficiently remove each directory entry.
10448 The @samp{unlink} parameter will just use a standard unlink call,
10449 @samp{wipe} will also first obfuscate bytes in the name, and
10450 @samp{wipesync} will also sync each obfuscated byte in the name to
10452 Note @samp{wipesync} is the default method, but can be expensive,
10453 requiring a sync for every character in every file. This can become
10454 significant with many files, or is redundant if your file system provides
10455 synchronous metadata updates.
10461 Display to standard error all status updates as sterilization proceeds.
10467 By default, @command{shred} rounds the size of a regular file up to the next
10468 multiple of the file system block size to fully erase the slack space in
10469 the last block of the file. This space may contain portions of the current
10470 system memory on some systems for example.
10471 Use @option{--exact} to suppress that behavior.
10472 Thus, by default if you shred a 10-byte regular file on a system with 512-byte
10473 blocks, the resulting file will be 512 bytes long. With this option,
10474 shred does not increase the apparent size of the file.
10480 Normally, the last pass that @command{shred} writes is made up of
10481 random data. If this would be conspicuous on your storage device (for
10482 example, because it looks like encrypted data), or you just think
10483 it's tidier, the @option{--zero} option adds an additional overwrite pass with
10484 all zero bits. This is in addition to the number of passes specified
10485 by the @option{--iterations} option.
10489 You might use the following command to erase the file system you
10490 created on a USB flash drive. This command typically takes several
10491 minutes, depending on the drive's size and write speed. On modern
10492 storage devices a single pass should be adequate, and will take one
10493 third the time of the default three-pass approach.
10496 shred -v -n 1 /dev/sdd1
10499 Similarly, to erase all data on a selected partition of
10500 your device, you could give a command like the following.
10503 # 1 pass, write pseudo-random data; 3x faster than the default
10504 shred -v -n1 /dev/sda5
10507 To be on the safe side, use at least one pass that overwrites using
10508 pseudo-random data. I.e., don't be tempted to use @samp{-n0 --zero},
10509 in case some device controller optimizes the process of writing blocks
10510 of all zeros, and thereby does not clear all bytes in a block.
10511 Some SSDs may do just that.
10513 A @var{file} of @samp{-} denotes standard output.
10514 The intended use of this is to shred a removed temporary file.
10521 echo "Hello, world" >&3
10526 However, the command @samp{shred - >file} does not shred the contents
10527 of @var{file}, since the shell truncates @var{file} before invoking
10528 @command{shred}. Use the command @samp{shred file} or (if using a
10529 Bourne-compatible shell) the command @samp{shred - 1<>file} instead.
10534 @node Special file types
10535 @chapter Special file types
10537 @cindex special file types
10538 @cindex file types, special
10540 This chapter describes commands which create special types of files (and
10541 @command{rmdir}, which removes directories, one special file type).
10543 @cindex special file types
10545 Although Unix-like operating systems have markedly fewer special file
10546 types than others, not @emph{everything} can be treated only as the
10547 undifferentiated byte stream of @dfn{normal files}. For example, when a
10548 file is created or removed, the system must record this information,
10549 which it does in a @dfn{directory}---a special type of file. Although
10550 you can read directories as normal files, if you're curious, in order
10551 for the system to do its job it must impose a structure, a certain
10552 order, on the bytes of the file. Thus it is a ``special'' type of file.
10554 Besides directories, other special file types include named pipes
10555 (FIFOs), symbolic links, sockets, and so-called @dfn{special files}.
10558 * link invocation:: Make a hard link via the link syscall
10559 * ln invocation:: Make links between files.
10560 * mkdir invocation:: Make directories.
10561 * mkfifo invocation:: Make FIFOs (named pipes).
10562 * mknod invocation:: Make block or character special files.
10563 * readlink invocation:: Print value of a symlink or canonical file name.
10564 * rmdir invocation:: Remove empty directories.
10565 * unlink invocation:: Remove files via the unlink syscall
10569 @node link invocation
10570 @section @command{link}: Make a hard link via the link syscall
10573 @cindex links, creating
10574 @cindex hard links, creating
10575 @cindex creating links (hard only)
10577 @command{link} creates a single hard link at a time.
10578 It is a minimalist interface to the system-provided
10579 @code{link} function. @xref{Hard Links, , , libc,
10580 The GNU C Library Reference Manual}.
10581 It avoids the bells and whistles of the more commonly-used
10582 @command{ln} command (@pxref{ln invocation}).
10586 link @var{filename} @var{linkname}
10589 @var{filename} must specify an existing file, and @var{linkname}
10590 must specify a nonexistent entry in an existing directory.
10591 @command{link} simply calls @code{link (@var{filename}, @var{linkname})}
10592 to create the link.
10594 On a GNU system, this command acts like @samp{ln --directory
10595 --no-target-directory @var{filename} @var{linkname}}. However, the
10596 @option{--directory} and @option{--no-target-directory} options are
10597 not specified by POSIX, and the @command{link} command is
10598 more portable in practice.
10600 If @var{filename} is a symbolic link, it is unspecified whether
10601 @var{linkname} will be a hard link to the symbolic link or to the
10602 target of the symbolic link. Use @command{ln -P} or @command{ln -L}
10603 to specify which behavior is desired.
10608 @node ln invocation
10609 @section @command{ln}: Make links between files
10612 @cindex links, creating
10613 @cindex hard links, creating
10614 @cindex symbolic (soft) links, creating
10615 @cindex creating links (hard or soft)
10617 @cindex file systems and hard links
10618 @command{ln} makes links between files. By default, it makes hard links;
10619 with the @option{-s} option, it makes symbolic (or @dfn{soft}) links.
10623 ln [@var{option}]@dots{} [-T] @var{target} @var{linkname}
10624 ln [@var{option}]@dots{} @var{target}
10625 ln [@var{option}]@dots{} @var{target}@dots{} @var{directory}
10626 ln [@var{option}]@dots{} -t @var{directory} @var{target}@dots{}
10632 If two file names are given, @command{ln} creates a link to the first
10633 file from the second.
10636 If one @var{target} is given, @command{ln} creates a link to that file
10637 in the current directory.
10640 If the @option{--target-directory} (@option{-t}) option is given, or
10641 failing that if the last file is a directory and the
10642 @option{--no-target-directory} (@option{-T}) option is not given,
10643 @command{ln} creates a link to each @var{target} file in the specified
10644 directory, using the @var{target}s' names.
10648 Normally @command{ln} does not replace existing files. Use the
10649 @option{--force} (@option{-f}) option to replace them unconditionally,
10650 the @option{--interactive} (@option{-i}) option to replace them
10651 conditionally, and the @option{--backup} (@option{-b}) option to
10652 rename them. Unless the @option{--backup} (@option{-b}) option is
10653 used there is no brief moment when the destination does not exist;
10654 this is an extension to POSIX.
10656 @cindex hard link, defined
10657 @cindex inode, and hard links
10658 A @dfn{hard link} is another name for an existing file; the link and the
10659 original are indistinguishable. Technically speaking, they share the
10660 same inode, and the inode contains all the information about a
10661 file---indeed, it is not incorrect to say that the inode @emph{is} the
10662 file. Most systems prohibit making a hard link to
10663 a directory; on those where it is allowed, only the super-user can do
10664 so (and with caution, since creating a cycle will cause problems to many
10665 other utilities). Hard links cannot cross file system boundaries. (These
10666 restrictions are not mandated by POSIX, however.)
10668 @cindex dereferencing symbolic links
10669 @cindex symbolic link, defined
10670 @dfn{Symbolic links} (@dfn{symlinks} for short), on the other hand, are
10671 a special file type (which not all kernels support: System V release 3
10672 (and older) systems lack symlinks) in which the link file actually
10673 refers to a different file, by name. When most operations (opening,
10674 reading, writing, and so on) are passed the symbolic link file, the
10675 kernel automatically @dfn{dereferences} the link and operates on the
10676 target of the link. But some operations (e.g., removing) work on the
10677 link file itself, rather than on its target. The owner and group of a
10678 symlink are not significant to file access performed through
10679 the link, but do have implications on deleting a symbolic link from a
10680 directory with the restricted deletion bit set. On the GNU system,
10681 the mode of a symlink has no significance and cannot be changed, but
10682 on some BSD systems, the mode can be changed and will affect whether
10683 the symlink will be traversed in file name resolution. @xref{Symbolic Links,,,
10684 libc, The GNU C Library Reference Manual}.
10686 Symbolic links can contain arbitrary strings; a @dfn{dangling symlink}
10687 occurs when the string in the symlink does not resolve to a file.
10688 There are no restrictions against creating dangling symbolic links.
10689 There are trade-offs to using absolute or relative symlinks. An
10690 absolute symlink always points to the same file, even if the directory
10691 containing the link is moved. However, if the symlink is visible from
10692 more than one machine (such as on a networked file system), the file
10693 pointed to might not always be the same. A relative symbolic link is
10694 resolved in relation to the directory that contains the link, and is
10695 often useful in referring to files on the same device without regards
10696 to what name that device is mounted on when accessed via networked
10699 When creating a relative symlink in a different location than the
10700 current directory, the resolution of the symlink will be different
10701 than the resolution of the same string from the current directory.
10702 Therefore, many users prefer to first change directories to the
10703 location where the relative symlink will be created, so that
10704 tab-completion or other file resolution will find the same target as
10705 what will be placed in the symlink.
10707 The program accepts the following options. Also see @ref{Common options}.
10718 @opindex --directory
10719 @cindex hard links to directories
10720 Allow users with appropriate privileges to attempt to make hard links
10722 However, note that this will probably fail due to
10723 system restrictions, even for the super-user.
10729 Remove existing destination files.
10732 @itemx --interactive
10734 @opindex --interactive
10735 @cindex prompting, and @command{ln}
10736 Prompt whether to remove existing destination files.
10742 If @option{-s} is not in effect, and the source file is a symbolic
10743 link, create the hard link to the file referred to by the symbolic
10744 link, rather than the symbolic link itself.
10747 @itemx --no-dereference
10749 @opindex --no-dereference
10750 Do not treat the last operand specially when it is a symbolic link to
10751 a directory. Instead, treat it as if it were a normal file.
10753 When the destination is an actual directory (not a symlink to one),
10754 there is no ambiguity. The link is created in that directory.
10755 But when the specified destination is a symlink to a directory,
10756 there are two ways to treat the user's request. @command{ln} can
10757 treat the destination just as it would a normal directory and create
10758 the link in it. On the other hand, the destination can be viewed as a
10759 non-directory---as the symlink itself. In that case, @command{ln}
10760 must delete or backup that symlink before creating the new link.
10761 The default is to treat a destination that is a symlink to a directory
10762 just like a directory.
10764 This option is weaker than the @option{--no-target-directory}
10765 (@option{-T}) option, so it has no effect if both options are given.
10770 @opindex --physical
10771 If @option{-s} is not in effect, and the source file is a symbolic
10772 link, create the hard link to the symbolic link itself. On platforms
10773 where this is not supported by the kernel, this option creates a
10774 symbolic link with identical contents; since symbolic link contents
10775 cannot be edited, any file name resolution performed through either
10776 link will be the same as if a hard link had been created.
10781 @opindex --relative
10782 Make symbolic links relative to the link location.
10783 This option is only valid with the @option{--symbolic} option.
10788 ln -srv /a/file /tmp
10789 '/tmp/file' -> '../a/file'
10792 Relative symbolic links are generated based on their canonicalized
10793 containing directory, and canonicalized targets. I.e., all symbolic
10794 links in these file names will be resolved.
10795 @xref{realpath invocation}, which gives greater control
10796 over relative file name generation, as demonstrated in the following example:
10801 test "$1" = --no-symlinks && { nosym=$1; shift; }
10803 test -d "$2" && link="$2/." || link="$2"
10804 rtarget="$(realpath $nosym -m "$target" \
10805 --relative-to "$(dirname "$link")")"
10806 ln -s -v "$rtarget" "$link"
10814 @opindex --symbolic
10815 Make symbolic links instead of hard links. This option merely produces
10816 an error message on systems that do not support symbolic links.
10820 @optTargetDirectory
10822 @optNoTargetDirectory
10828 Print the name of each file after linking it successfully.
10832 @cindex hard links to symbolic links
10833 @cindex symbolic links and @command{ln}
10834 If @option{-L} and @option{-P} are both given, the last one takes
10835 precedence. If @option{-s} is also given, @option{-L} and @option{-P}
10836 are silently ignored. If neither option is given, then this
10837 implementation defaults to @option{-P} if the system @code{link} supports
10838 hard links to symbolic links (such as the GNU system), and @option{-L}
10839 if @code{link} follows symbolic links (such as on BSD).
10848 # Create link ../a pointing to a in that directory.
10849 # Not really useful because it points to itself.
10854 # Change to the target before creating symlinks to avoid being confused.
10860 # Hard coded file names don't move well.
10861 ln -s $(pwd)/a /some/dir/
10865 # Relative file names survive directory moves and also
10866 # work across networked file systems.
10867 ln -s afile anotherfile
10868 ln -s ../adir/afile yetanotherfile
10872 @node mkdir invocation
10873 @section @command{mkdir}: Make directories
10876 @cindex directories, creating
10877 @cindex creating directories
10879 @command{mkdir} creates directories with the specified names. Synopsis:
10882 mkdir [@var{option}]@dots{} @var{name}@dots{}
10885 @command{mkdir} creates each directory @var{name} in the order given.
10886 It reports an error if @var{name} already exists, unless the
10887 @option{-p} option is given and @var{name} is a directory.
10889 The program accepts the following options. Also see @ref{Common options}.
10893 @item -m @var{mode}
10894 @itemx --mode=@var{mode}
10897 @cindex modes of created directories, setting
10898 Set the file permission bits of created directories to @var{mode},
10899 which uses the same syntax as
10900 in @command{chmod} and uses @samp{a=rwx} (read, write and execute allowed for
10901 everyone) for the point of the departure. @xref{File permissions}.
10902 This option affects only directories given on the command line;
10903 it does not affect any parents that may be created via the @option{-p} option.
10905 Normally the directory has the desired file mode bits at the moment it
10906 is created. As a GNU extension, @var{mode} may also mention
10907 special mode bits, but in this case there may be a temporary window
10908 during which the directory exists but its special mode bits are
10909 incorrect. @xref{Directory Setuid and Setgid}, for how the
10910 set-user-ID and set-group-ID bits of directories are inherited unless
10911 overridden in this way.
10917 @cindex parent directories, creating
10918 Make any missing parent directories for each argument, setting their
10919 file permission bits to @samp{=rwx,u+wx},
10920 that is, with the umask modified by @samp{u+wx}. Ignore
10921 existing parent directories, and do not change their file permission
10924 If the @option{-m} option is also given, it does not affect
10925 file permission bits of any newly-created parent directories.
10926 To control these bits, set the
10927 umask before invoking @command{mkdir}. For example, if the shell
10928 command @samp{(umask u=rwx,go=rx; mkdir -p P/Q)} creates the parent
10929 @file{P} it sets the parent's file permission bits to @samp{u=rwx,go=rx}.
10930 (The umask must include @samp{u=wx} for this method to work.)
10931 To set a parent's special mode bits as well, you can invoke
10932 @command{chmod} after @command{mkdir}. @xref{Directory Setuid and
10933 Setgid}, for how the set-user-ID and set-group-ID bits of
10934 newly-created parent directories are inherited.
10940 Print a message for each created directory. This is most useful with
10941 @option{--parents}.
10950 @node mkfifo invocation
10951 @section @command{mkfifo}: Make FIFOs (named pipes)
10954 @cindex FIFOs, creating
10955 @cindex named pipes, creating
10956 @cindex creating FIFOs (named pipes)
10958 @command{mkfifo} creates FIFOs (also called @dfn{named pipes}) with the
10959 specified names. Synopsis:
10962 mkfifo [@var{option}] @var{name}@dots{}
10965 A @dfn{FIFO} is a special file type that permits independent processes
10966 to communicate. One process opens the FIFO file for writing, and
10967 another for reading, after which data can flow as with the usual
10968 anonymous pipe in shells or elsewhere.
10970 The program accepts the following options. Also see @ref{Common options}.
10974 @item -m @var{mode}
10975 @itemx --mode=@var{mode}
10978 @cindex modes of created FIFOs, setting
10979 Set the mode of created FIFOs to @var{mode}, which is symbolic as in
10980 @command{chmod} and uses @samp{a=rw} (read and write allowed for everyone)
10981 for the point of departure. @var{mode} should specify only file
10982 permission bits. @xref{File permissions}.
10991 @node mknod invocation
10992 @section @command{mknod}: Make block or character special files
10995 @cindex block special files, creating
10996 @cindex character special files, creating
10998 @command{mknod} creates a FIFO, character special file, or block special
10999 file with the specified name. Synopsis:
11002 mknod [@var{option}]@dots{} @var{name} @var{type} [@var{major} @var{minor}]
11005 @cindex special files
11006 @cindex block special files
11007 @cindex character special files
11008 Unlike the phrase ``special file type'' above, the term @dfn{special
11009 file} has a technical meaning on Unix: something that can generate or
11010 receive data. Usually this corresponds to a physical piece of hardware,
11011 e.g., a printer or a flash drive. (These files are typically created at
11012 system-configuration time.) The @command{mknod} command is what creates
11013 files of this type. Such devices can be read either a character at a
11014 time or a ``block'' (many characters) at a time, hence we say there are
11015 @dfn{block special} files and @dfn{character special} files.
11017 @c mknod is a shell built-in at least with OpenBSD's /bin/sh
11018 @mayConflictWithShellBuiltIn{mknod}
11020 The arguments after @var{name} specify the type of file to make:
11025 @opindex p @r{for FIFO file}
11029 @opindex b @r{for block special file}
11030 for a block special file
11033 @c Don't document the 'u' option -- it's just a synonym for 'c'.
11034 @c Do *any* versions of mknod still use it?
11036 @opindex c @r{for character special file}
11037 @c @opindex u @r{for character special file}
11038 for a character special file
11042 When making a block or character special file, the major and minor
11043 device numbers must be given after the file type.
11044 If a major or minor device number begins with @samp{0x} or @samp{0X},
11045 it is interpreted as hexadecimal; otherwise, if it begins with @samp{0},
11046 as octal; otherwise, as decimal.
11048 The program accepts the following options. Also see @ref{Common options}.
11052 @item -m @var{mode}
11053 @itemx --mode=@var{mode}
11056 Set the mode of created files to @var{mode}, which is symbolic as in
11057 @command{chmod} and uses @samp{a=rw} as the point of departure.
11058 @var{mode} should specify only file permission bits.
11059 @xref{File permissions}.
11068 @node readlink invocation
11069 @section @command{readlink}: Print value of a symlink or canonical file name
11072 @cindex displaying value of a symbolic link
11073 @cindex canonical file name
11074 @cindex canonicalize a file name
11077 @command{readlink} may work in one of two supported modes:
11081 @item Readlink mode
11083 @command{readlink} outputs the value of the given symbolic links.
11084 If @command{readlink} is invoked with an argument other than the name
11085 of a symbolic link, it produces no output and exits with a nonzero exit code.
11087 @item Canonicalize mode
11089 @command{readlink} outputs the absolute name of the given files which contain
11090 no @file{.}, @file{..} components nor any repeated separators
11091 (@file{/}) or symbolic links. Note the @command{realpath} command is the
11092 preferred command to use for canonicalization. @xref{realpath invocation}.
11097 readlink [@var{option}]@dots{} @var{file}@dots{}
11100 By default, @command{readlink} operates in readlink mode.
11102 The program accepts the following options. Also see @ref{Common options}.
11107 @itemx --canonicalize
11109 @opindex --canonicalize
11110 Activate canonicalize mode.
11111 If any component of the file name except the last one is missing or unavailable,
11112 @command{readlink} produces no output and exits with a nonzero exit
11113 code. A trailing slash is ignored.
11116 @itemx --canonicalize-existing
11118 @opindex --canonicalize-existing
11119 Activate canonicalize mode.
11120 If any component is missing or unavailable, @command{readlink} produces
11121 no output and exits with a nonzero exit code. A trailing slash
11122 requires that the name resolve to a directory.
11125 @itemx --canonicalize-missing
11127 @opindex --canonicalize-missing
11128 Activate canonicalize mode.
11129 If any component is missing or unavailable, @command{readlink} treats it
11133 @itemx --no-newline
11135 @opindex --no-newline
11136 Do not print the output delimiter, when a single @var{file} is specified.
11137 Print a warning if specified along with multiple @var{file}s.
11147 Suppress most error messages. On by default.
11153 Report error messages.
11159 The @command{readlink} utility first appeared in OpenBSD 2.1.
11161 The @command{realpath} command without options, operates like
11162 @command{readlink} in canonicalize mode.
11167 @node rmdir invocation
11168 @section @command{rmdir}: Remove empty directories
11171 @cindex removing empty directories
11172 @cindex directories, removing empty
11174 @command{rmdir} removes empty directories. Synopsis:
11177 rmdir [@var{option}]@dots{} @var{directory}@dots{}
11180 If any @var{directory} argument does not refer to an existing empty
11181 directory, it is an error.
11183 The program accepts the following options. Also see @ref{Common options}.
11187 @item --ignore-fail-on-non-empty
11188 @opindex --ignore-fail-on-non-empty
11189 @cindex directory deletion, ignoring failures
11190 Ignore each failure to remove a directory that is non-empty.
11196 @cindex parent directories, removing
11197 Remove @var{directory}, then try to remove each component of @var{directory}.
11198 So, for example, @samp{rmdir -p a/b/c} is similar to @samp{rmdir a/b/c a/b a}.
11199 As such, it fails if any of those directories turns out not to be empty.
11200 Use the @option{--ignore-fail-on-non-empty} option to make it so such
11201 a failure does not evoke a diagnostic and does not cause @command{rmdir} to
11202 exit unsuccessfully.
11208 @cindex directory deletion, reporting
11209 Give a diagnostic for each successful removal.
11210 @var{directory} is removed.
11214 @xref{rm invocation}, for how to remove non-empty directories recursively.
11216 To remove all empty directories under @var{dirname}, including
11217 directories that become empty because other directories are removed,
11218 you can use either of the following commands:
11221 # This uses GNU extensions.
11222 find @var{dirname} -type d -empty -delete
11224 # This runs on any POSIX platform.
11225 find @var{dirname} -depth -type d -exec rmdir @{@} +
11231 @node unlink invocation
11232 @section @command{unlink}: Remove files via the unlink syscall
11235 @cindex removing files or directories (via the unlink syscall)
11237 @command{unlink} deletes a single specified file name.
11238 It is a minimalist interface to the system-provided
11239 @code{unlink} function. @xref{Deleting Files, , , libc,
11240 The GNU C Library Reference Manual}. Synopsis:
11241 It avoids the bells and whistles of the more commonly-used
11242 @command{rm} command (@pxref{rm invocation}).
11245 unlink @var{filename}
11248 On some systems @code{unlink} can be used to delete the name of a
11249 directory. On others, it can be used that way only by a privileged user.
11250 In the GNU system @code{unlink} can never delete the name of a directory.
11252 The @command{unlink} command honors the @option{--help} and
11253 @option{--version} options. To remove a file whose name begins with
11254 @samp{-}, prefix the name with @samp{./}, e.g., @samp{unlink ./--help}.
11259 @node Changing file attributes
11260 @chapter Changing file attributes
11262 @cindex changing file attributes
11263 @cindex file attributes, changing
11264 @cindex attributes, file
11266 A file is not merely its contents, a name, and a file type
11267 (@pxref{Special file types}). A file also has an owner (a user ID), a
11268 group (a group ID), permissions (what the owner can do with the file,
11269 what people in the group can do, and what everyone else can do), various
11270 timestamps, and other information. Collectively, we call these a file's
11273 These commands change file attributes.
11276 * chown invocation:: Change file owners and groups.
11277 * chgrp invocation:: Change file groups.
11278 * chmod invocation:: Change access permissions.
11279 * touch invocation:: Change file timestamps.
11283 @node chown invocation
11284 @section @command{chown}: Change file owner and group
11287 @cindex file ownership, changing
11288 @cindex group ownership, changing
11289 @cindex changing file ownership
11290 @cindex changing group ownership
11292 @command{chown} changes the user and/or group ownership of each given @var{file}
11293 to @var{new-owner} or to the user and group of an existing reference file.
11297 chown [@var{option}]@dots{} @{@var{new-owner} | --reference=@var{ref_file}@}@c
11301 If used, @var{new-owner} specifies the new owner and/or group as follows
11302 (with no embedded white space):
11305 [@var{owner}] [ : [@var{group}] ]
11312 If only an @var{owner} (a user name or numeric user ID) is given, that
11313 user is made the owner of each given file, and the files' group is not
11316 @item owner@samp{:}group
11317 If the @var{owner} is followed by a colon and a @var{group} (a
11318 group name or numeric group ID), with no spaces between them, the group
11319 ownership of the files is changed as well (to @var{group}).
11321 @item owner@samp{:}
11322 If a colon but no group name follows @var{owner}, that user is
11323 made the owner of the files and the group of the files is changed to
11324 @var{owner}'s login group.
11326 @item @samp{:}group
11327 If the colon and following @var{group} are given, but the owner
11328 is omitted, only the group of the files is changed; in this case,
11329 @command{chown} performs the same function as @command{chgrp}.
11332 If only a colon is given, or if @var{new-owner} is empty, neither the
11333 owner nor the group is changed.
11337 If @var{owner} or @var{group} is intended to represent a numeric user
11338 or group ID, then you may specify it with a leading @samp{+}.
11339 @xref{Disambiguating names and IDs}.
11341 Some older scripts may still use @samp{.} in place of the @samp{:} separator.
11342 POSIX 1003.1-2001 (@pxref{Standards conformance}) does not
11343 require support for that, but for backward compatibility GNU
11344 @command{chown} supports @samp{.} so long as no ambiguity results,
11345 although it issues a warning and support may be removed in future versions.
11346 New scripts should avoid the use of @samp{.} because it is not
11347 portable, and because it has undesirable results if the entire
11348 @var{owner@samp{.}group} happens to identify a user whose name
11351 @macro chownGroupRestrictions
11352 It is system dependent whether a user can change the group to an arbitrary one,
11353 or the more portable behavior of being restricted to setting a group of
11354 which the user is a member.
11356 @chownGroupRestrictions
11358 The @command{chown} command sometimes clears the set-user-ID or
11359 set-group-ID permission bits. This behavior depends on the policy and
11360 functionality of the underlying @code{chown} system call, which may
11361 make system-dependent file mode modifications outside the control of
11362 the @command{chown} command. For example, the @command{chown} command
11363 might not affect those bits when invoked by a user with appropriate
11364 privileges, or when the
11365 bits signify some function other than executable permission (e.g.,
11366 mandatory locking).
11367 When in doubt, check the underlying system behavior.
11369 The program accepts the following options. Also see @ref{Common options}.
11377 @cindex changed owners, verbosely describing
11378 Verbosely describe the action for each @var{file} whose ownership
11387 @cindex error messages, omitting
11388 Do not print error messages about files whose ownership cannot be
11391 @item --from=@var{old-owner}
11393 @cindex symbolic links, changing owner
11394 Change a @var{file}'s ownership only if it has current attributes specified
11395 by @var{old-owner}. @var{old-owner} has the same form as @var{new-owner}
11397 This option is useful primarily from a security standpoint in that
11398 it narrows considerably the window of potential abuse.
11399 For example, to reflect a user ID numbering change for one user's files
11400 without an option like this, @code{root} might run
11403 find / -owner OLDUSER -print0 | xargs -0 chown -h NEWUSER
11406 But that is dangerous because the interval between when the @command{find}
11407 tests the existing file's owner and when the @command{chown} is actually run
11408 may be quite large.
11409 One way to narrow the gap would be to invoke chown for each file
11413 find / -owner OLDUSER -exec chown -h NEWUSER @{@} \;
11416 But that is very slow if there are many affected files.
11417 With this option, it is safer (the gap is narrower still)
11418 though still not perfect:
11421 chown -h -R --from=OLDUSER NEWUSER /
11424 @item --dereference
11425 @opindex --dereference
11426 @cindex symbolic links, changing owner
11428 Do not act on symbolic links themselves but rather on what they point to.
11429 This is the default when not operating recursively.
11430 @warnOptDerefWithRec
11433 @itemx --no-dereference
11435 @opindex --no-dereference
11436 @cindex symbolic links, changing owner
11438 Act on symbolic links themselves instead of what they point to.
11439 This mode relies on the @code{lchown} system call.
11440 On systems that do not provide the @code{lchown} system call,
11441 @command{chown} fails when a file specified on the command line
11442 is a symbolic link.
11443 By default, no diagnostic is issued for symbolic links encountered
11444 during a recursive traversal, but see @option{--verbose}.
11446 @item --preserve-root
11447 @opindex --preserve-root
11448 @cindex root directory, disallow recursive modification
11449 Fail upon any attempt to recursively change the root directory, @file{/}.
11450 Without @option{--recursive}, this option has no effect.
11451 @xref{Treating / specially}.
11453 @item --no-preserve-root
11454 @opindex --no-preserve-root
11455 @cindex root directory, allow recursive modification
11456 Cancel the effect of any preceding @option{--preserve-root} option.
11457 @xref{Treating / specially}.
11459 @item --reference=@var{ref_file}
11460 @opindex --reference
11461 Change the user and group of each @var{file} to be the same as those of
11462 @var{ref_file}. If @var{ref_file} is a symbolic link, do not use the
11463 user and group of the symbolic link, but rather those of the file it
11470 Output a diagnostic for every file processed.
11471 If a symbolic link is encountered during a recursive traversal
11472 on a system without the @code{lchown} system call, and @option{--no-dereference}
11473 is in effect, then issue a diagnostic saying neither the symbolic link nor
11474 its referent is being changed.
11479 @opindex --recursive
11480 @cindex recursively changing file ownership
11481 Recursively change ownership of directories and their contents.
11484 @xref{Traversing symlinks}.
11487 @warnOptDerefWithRec
11488 @xref{Traversing symlinks}.
11491 @xref{Traversing symlinks}.
11500 # Change the owner of /u to "root".
11503 # Likewise, but also change its group to "staff".
11504 chown root:staff /u
11506 # Change the owner of /u and subfiles to "root".
11511 @node chgrp invocation
11512 @section @command{chgrp}: Change group ownership
11515 @cindex group ownership, changing
11516 @cindex changing group ownership
11518 @command{chgrp} changes the group ownership of each given @var{file}
11519 to @var{group} (which can be either a group name or a numeric group ID)
11520 or to the group of an existing reference file. @xref{chown invocation}.
11524 chgrp [@var{option}]@dots{} @{@var{group} | --reference=@var{ref_file}@}@c
11528 If @var{group} is intended to represent a
11529 numeric group ID, then you may specify it with a leading @samp{+}.
11530 @xref{Disambiguating names and IDs}.
11532 @chownGroupRestrictions
11534 The program accepts the following options. Also see @ref{Common options}.
11542 @cindex changed files, verbosely describing
11543 Verbosely describe the action for each @var{file} whose group actually
11552 @cindex error messages, omitting
11553 Do not print error messages about files whose group cannot be
11556 @item --dereference
11557 @opindex --dereference
11558 @cindex symbolic links, changing owner
11560 Do not act on symbolic links themselves but rather on what they point to.
11561 This is the default when not operating recursively.
11562 @warnOptDerefWithRec
11565 @itemx --no-dereference
11567 @opindex --no-dereference
11568 @cindex symbolic links, changing group
11570 Act on symbolic links themselves instead of what they point to.
11571 This mode relies on the @code{lchown} system call.
11572 On systems that do not provide the @code{lchown} system call,
11573 @command{chgrp} fails when a file specified on the command line
11574 is a symbolic link.
11575 By default, no diagnostic is issued for symbolic links encountered
11576 during a recursive traversal, but see @option{--verbose}.
11578 @item --preserve-root
11579 @opindex --preserve-root
11580 @cindex root directory, disallow recursive modification
11581 Fail upon any attempt to recursively change the root directory, @file{/}.
11582 Without @option{--recursive}, this option has no effect.
11583 @xref{Treating / specially}.
11585 @item --no-preserve-root
11586 @opindex --no-preserve-root
11587 @cindex root directory, allow recursive modification
11588 Cancel the effect of any preceding @option{--preserve-root} option.
11589 @xref{Treating / specially}.
11591 @item --reference=@var{ref_file}
11592 @opindex --reference
11593 Change the group of each @var{file} to be the same as that of
11594 @var{ref_file}. If @var{ref_file} is a symbolic link, do not use the
11595 group of the symbolic link, but rather that of the file it refers to.
11601 Output a diagnostic for every file processed.
11602 If a symbolic link is encountered during a recursive traversal
11603 on a system without the @code{lchown} system call, and @option{--no-dereference}
11604 is in effect, then issue a diagnostic saying neither the symbolic link nor
11605 its referent is being changed.
11610 @opindex --recursive
11611 @cindex recursively changing group ownership
11612 Recursively change the group ownership of directories and their contents.
11615 @xref{Traversing symlinks}.
11618 @warnOptDerefWithRec
11619 @xref{Traversing symlinks}.
11622 @xref{Traversing symlinks}.
11631 # Change the group of /u to "staff".
11634 # Change the group of /u and subfiles to "staff".
11639 @node chmod invocation
11640 @section @command{chmod}: Change access permissions
11643 @cindex changing access permissions
11644 @cindex access permissions, changing
11645 @cindex permissions, changing access
11647 @command{chmod} changes the access permissions of the named files. Synopsis:
11650 chmod [@var{option}]@dots{} @{@var{mode} | --reference=@var{ref_file}@}@c
11654 @cindex symbolic links, permissions of
11655 @command{chmod} never changes the permissions of symbolic links, since
11656 the @command{chmod} system call cannot change their permissions.
11657 This is not a problem since the permissions of symbolic links are
11658 never used. However, for each symbolic link listed on the command
11659 line, @command{chmod} changes the permissions of the pointed-to file.
11660 In contrast, @command{chmod} ignores symbolic links encountered during
11661 recursive directory traversals.
11663 Only a process whose effective user ID matches the user ID of the file,
11664 or a process with appropriate privileges, is permitted to change the
11665 file mode bits of a file.
11667 A successful use of @command{chmod} clears the set-group-ID bit of a
11668 regular file if the file's group ID does not match the user's
11669 effective group ID or one of the user's supplementary group IDs,
11670 unless the user has appropriate privileges. Additional restrictions
11671 may cause the set-user-ID and set-group-ID bits of @var{mode} or
11672 @var{ref_file} to be ignored. This behavior depends on the policy and
11673 functionality of the underlying @code{chmod} system call. When in
11674 doubt, check the underlying system behavior.
11676 If used, @var{mode} specifies the new file mode bits.
11677 For details, see the section on @ref{File permissions}.
11678 If you really want @var{mode} to have a leading @samp{-}, you should
11679 use @option{--} first, e.g., @samp{chmod -- -w file}. Typically,
11680 though, @samp{chmod a-w file} is preferable, and @command{chmod -w
11681 file} (without the @option{--}) complains if it behaves differently
11682 from what @samp{chmod a-w file} would do.
11684 The program accepts the following options. Also see @ref{Common options}.
11692 Verbosely describe the action for each @var{file} whose permissions
11701 @cindex error messages, omitting
11702 Do not print error messages about files whose permissions cannot be
11705 @item --preserve-root
11706 @opindex --preserve-root
11707 @cindex root directory, disallow recursive modification
11708 Fail upon any attempt to recursively change the root directory, @file{/}.
11709 Without @option{--recursive}, this option has no effect.
11710 @xref{Treating / specially}.
11712 @item --no-preserve-root
11713 @opindex --no-preserve-root
11714 @cindex root directory, allow recursive modification
11715 Cancel the effect of any preceding @option{--preserve-root} option.
11716 @xref{Treating / specially}.
11722 Verbosely describe the action or non-action taken for every @var{file}.
11724 @item --reference=@var{ref_file}
11725 @opindex --reference
11726 Change the mode of each @var{file} to be the same as that of @var{ref_file}.
11727 @xref{File permissions}.
11728 If @var{ref_file} is a symbolic link, do not use the mode
11729 of the symbolic link, but rather that of the file it refers to.
11734 @opindex --recursive
11735 @cindex recursively changing access permissions
11736 Recursively change permissions of directories and their contents.
11745 # Change file permissions of FOO to be world readable
11746 # and user writable, with no other permissions.
11750 # Add user and group execute permissions to FOO.
11754 # Set file permissions of DIR and subsidiary files to
11755 # be the umask default, assuming execute permissions for
11756 # directories and for files already executable.
11757 chmod -R a=,+rwX dir
11761 @node touch invocation
11762 @section @command{touch}: Change file timestamps
11765 @cindex changing file timestamps
11766 @cindex file timestamps, changing
11767 @cindex timestamps, changing file
11769 @command{touch} changes the access and/or modification timestamps of the
11770 specified files. Synopsis:
11773 touch [@var{option}]@dots{} @var{file}@dots{}
11776 @cindex empty files, creating
11777 Any @var{file} argument that does not exist is created empty, unless
11778 option @option{--no-create} (@option{-c}) or @option{--no-dereference}
11779 (@option{-h}) was in effect.
11781 A @var{file} argument string of @samp{-} is handled specially and
11782 causes @command{touch} to change the times of the file associated with
11785 By default, @command{touch} sets file timestamps to the current time.
11786 Because @command{touch} acts on its operands left to right, the
11787 resulting timestamps of earlier and later operands may disagree.
11789 @cindex permissions, for changing file timestamps
11790 When setting file timestamps to the current time, @command{touch} can
11791 change the timestamps for files that the user does not own but has
11792 write permission for. Otherwise, the user must own the files. Some
11793 older systems have a further restriction: the user must own the files
11794 unless both the access and modification timestamps are being set to the
11797 The @command{touch} command cannot set a file's status change timestamp to
11798 a user-specified value, and cannot change the file's birth time (if
11799 supported) at all. Also, @command{touch} has issues similar to those
11800 affecting all programs that update file timestamps. For example,
11801 @command{touch} may set a file's timestamp to a value that differs
11802 slightly from the requested time. @xref{File timestamps}.
11805 Timestamps assume the time zone rules specified by the @env{TZ}
11806 environment variable, or by the system default rules if @env{TZ} is
11807 not set. @xref{TZ Variable,, Specifying the Time Zone with @env{TZ},
11808 libc, The GNU C Library Reference Manual}.
11809 You can avoid ambiguities during
11810 daylight saving transitions by using UTC timestamps.
11812 The program accepts the following options. Also see @ref{Common options}.
11817 @itemx --time=atime
11818 @itemx --time=access
11822 @opindex atime@r{, changing}
11823 @opindex access @r{time, changing}
11824 @opindex use @r{time, changing}
11825 Change the access timestamp only. @xref{File timestamps}.
11830 @opindex --no-create
11831 Do not warn about or create files that do not exist.
11833 @item -d @var{time}
11834 @itemx --date=@var{time}
11838 Use @var{time} instead of the current time. It can contain month names,
11839 time zones, @samp{am} and @samp{pm}, @samp{yesterday}, etc. For
11840 example, @option{--date="2020-07-21 14:19:13.489392193 +0530"}
11841 specifies the instant of time that is 489,392,193 nanoseconds after
11842 July 21, 2020 at 2:19:13 PM in a time zone that is 5 hours and 30
11843 minutes east of UTC@. @xref{Date input formats}.
11844 File systems that do not support high-resolution timestamps
11845 silently ignore any excess precision here.
11849 @cindex BSD @command{touch} compatibility
11850 Ignored; for compatibility with BSD versions of @command{touch}.
11853 @itemx --no-dereference
11855 @opindex --no-dereference
11856 @cindex symbolic links, changing time
11858 Attempt to change the timestamps of a symbolic link, rather than what
11859 the link refers to. When using this option, empty files are not
11860 created, but option @option{-c} must also be used to avoid warning
11861 about files that do not exist. Not all systems support changing the
11862 timestamps of symlinks, since underlying system support for this
11863 action was not required until POSIX 2008. Also, on some
11864 systems, the mere act of examining a symbolic link changes the access
11865 timestamp, such that only changes to the modification timestamp will persist
11866 long enough to be observable. When coupled with option @option{-r}, a
11867 reference timestamp is taken from a symbolic link rather than the file
11871 @itemx --time=mtime
11872 @itemx --time=modify
11875 @opindex mtime@r{, changing}
11876 @opindex modify @r{time, changing}
11877 Change the modification timestamp only.
11879 @item -r @var{file}
11880 @itemx --reference=@var{file}
11882 @opindex --reference
11883 Use the times of the reference @var{file} instead of the current time.
11884 If this option is combined with the @option{--date=@var{time}}
11885 (@option{-d @var{time}}) option, the reference @var{file}'s time is
11886 the origin for any relative @var{time}s given, but is otherwise ignored.
11887 For example, @samp{-r foo -d '-5 seconds'} specifies a timestamp
11888 equal to five seconds before the corresponding timestamp for @file{foo}.
11889 If @var{file} is a symbolic link, the reference timestamp is taken
11890 from the target of the symlink, unless @option{-h} was also in effect.
11892 @item -t [[@var{cc}]@var{yy}]@var{mmddhhmm}[.@var{ss}]
11893 @cindex leap seconds
11894 Use the argument (optional four-digit or two-digit years, months,
11895 days, hours, minutes, optional seconds) instead of the current time.
11896 If the year is specified with only two digits, then @var{cc}
11897 is 20 for years in the range 0 @dots{} 68, and 19 for years in
11898 69 @dots{} 99. If no digits of the year are specified,
11899 the argument is interpreted as a date in the current year.
11900 On the atypical systems that support leap seconds, @var{ss} may be
11905 @vindex _POSIX2_VERSION
11906 On systems predating POSIX 1003.1-2001,
11907 @command{touch} supports an obsolete syntax, as follows.
11908 If no timestamp is given with any of the @option{-d}, @option{-r}, or
11909 @option{-t} options, and if there are two or more @var{file}s and the
11910 first @var{file} is of the form @samp{@var{mmddhhmm}[@var{yy}]} and this
11911 would be a valid argument to the @option{-t} option (if the @var{yy}, if
11912 any, were moved to the front), and if the represented year
11913 is in the range 1969--1999, that argument is interpreted as the time
11914 for the other files instead of as a file name.
11915 Although this obsolete behavior can be controlled with the
11916 @env{_POSIX2_VERSION} environment variable (@pxref{Standards
11917 conformance}), portable scripts should avoid commands whose
11918 behavior depends on this variable.
11919 For example, use @samp{touch ./12312359 main.c} or @samp{touch -t
11920 12312359 main.c} rather than the ambiguous @samp{touch 12312359 main.c}.
11925 @node File space usage
11926 @chapter File space usage
11928 @cindex File space usage
11931 No file system can hold an infinite amount of data. These commands report
11932 how much storage is in use or available, report other file and
11933 file status information, and write buffers to file systems.
11936 * df invocation:: Report file system space usage.
11937 * du invocation:: Estimate file space usage.
11938 * stat invocation:: Report file or file system status.
11939 * sync invocation:: Synchronize cached writes to persistent storage.
11940 * truncate invocation:: Shrink or extend the size of a file.
11944 @node df invocation
11945 @section @command{df}: Report file system space usage
11948 @cindex file system usage
11949 @cindex disk usage by file system
11951 @command{df} reports the amount of space used and available on
11952 file systems. Synopsis:
11955 df [@var{option}]@dots{} [@var{file}]@dots{}
11958 With no arguments, @command{df} reports the space used and available on all
11959 currently mounted file systems (of all types). Otherwise, @command{df}
11960 reports on the file system containing each argument @var{file}.
11962 Normally the space is printed in units of
11963 1024 bytes, but this can be overridden (@pxref{Block size}).
11964 Non-integer quantities are rounded up to the next higher unit.
11966 For bind mounts and without arguments, @command{df} only outputs the statistics
11967 for that device with the shortest mount point name in the list of file systems
11968 (@var{mtab}), i.e., it hides duplicate entries, unless the @option{-a} option is
11971 With the same logic, @command{df} elides a mount entry of a dummy pseudo device
11972 if there is another mount entry of a real block device for that mount point with
11973 the same device number, e.g. the early-boot pseudo file system @samp{rootfs} is
11974 not shown per default when already the real root device has been mounted.
11976 @cindex disk device file
11977 @cindex device file
11978 If an argument @var{file} resolves to a special file containing
11979 a mounted file system, @command{df} shows the space available on that
11980 file system rather than on the file system containing the device node.
11981 GNU @command{df} does not attempt to determine the usage
11982 on unmounted file systems, because on most kinds of systems doing so
11983 requires extremely nonportable intimate knowledge of file system structures.
11985 The program accepts the following options. Also see @ref{Common options}.
11993 @cindex ignore file systems
11994 Include in the listing dummy, duplicate, or inaccessible file systems, which
11995 are omitted by default. Dummy file systems are typically special purpose
11996 pseudo file systems such as @samp{/proc}, with no associated storage.
11997 Duplicate file systems are local or remote file systems that are mounted
11998 at separate locations in the local file hierarchy, or bind mounted locations.
11999 Inaccessible file systems are those which are mounted but subsequently
12000 over-mounted by another file system at that point, or otherwise inaccessible
12001 due to permissions of the mount point etc.
12003 @item -B @var{size}
12004 @itemx --block-size=@var{size}
12006 @opindex --block-size
12007 @cindex file system sizes
12008 Scale sizes by @var{size} before printing them (@pxref{Block size}).
12009 For example, @option{-BG} prints sizes in units of 1,073,741,824 bytes.
12015 Equivalent to @option{--si}.
12021 @cindex inode usage
12022 List inode usage information instead of block usage. An inode (short
12023 for index node) contains information about a file such as its owner,
12024 permissions, timestamps, and location on the file system.
12028 @cindex kibibytes for file system sizes
12029 Print sizes in 1024-byte blocks, overriding the default block size
12030 (@pxref{Block size}).
12031 This option is equivalent to @option{--block-size=1K}.
12037 @cindex file system types, limiting output to certain
12038 Limit the listing to local file systems. By default, remote file systems
12043 @cindex file system space, retrieving old data more quickly
12044 Do not invoke the @code{sync} system call before getting any usage data.
12045 This may make @command{df} run significantly faster on systems with many
12046 file systems, but on some systems (notably Solaris) the results may be slightly
12047 out of date. This is the default.
12050 @itemx --output[=@var{field_list}]
12052 Use the output format defined by @var{field_list}, or print all fields if
12053 @var{field_list} is omitted. In the latter case, the order of the columns
12054 conforms to the order of the field descriptions below.
12056 The use of the @option{--output} together with each of the options @option{-i},
12057 @option{-P}, and @option{-T} is mutually exclusive.
12059 FIELD_LIST is a comma-separated list of columns to be included in @command{df}'s
12060 output and therefore effectively controls the order of output columns.
12061 Each field can thus be used at the place of choice, but yet must only be
12064 Valid field names in the @var{field_list} are:
12067 The source of the mount point, usually a device.
12072 Total number of inodes.
12074 Number of used inodes.
12076 Number of available inodes.
12078 Percentage of @var{iused} divided by @var{itotal}.
12081 Total number of blocks.
12083 Number of used blocks.
12085 Number of available blocks.
12087 Percentage of @var{used} divided by @var{size}.
12090 The file name if specified on the command line.
12095 The fields for block and inodes statistics are affected by the scaling
12096 options like @option{-h} as usual.
12098 The definition of the @var{field_list} can even be split among several
12099 @option{--output} uses.
12103 # Print the TARGET (i.e., the mount point) along with their percentage
12104 # statistic regarding the blocks and the inodes.
12105 df --out=target --output=pcent,ipcent
12107 # Print all available fields.
12113 @itemx --portability
12115 @opindex --portability
12116 @cindex one-line output format
12117 @cindex POSIX output format
12118 @cindex portable output format
12119 @cindex output format, portable
12120 Use the POSIX output format. This is like the default format except
12125 The information about each file system is always printed on exactly
12126 one line; a mount device is never put on a line by itself. This means
12127 that if the mount device name is more than 20 characters long (e.g., for
12128 some network mounts), the columns are misaligned.
12131 The labels in the header output line are changed to conform to POSIX.
12134 The default block size and output format are unaffected by the
12135 @env{DF_BLOCK_SIZE}, @env{BLOCK_SIZE} and @env{BLOCKSIZE} environment
12136 variables. However, the default block size is still affected by
12137 @env{POSIXLY_CORRECT}: it is 512 if @env{POSIXLY_CORRECT} is set, 1024
12138 otherwise. @xref{Block size}.
12145 @cindex file system space, retrieving current data more slowly
12146 Invoke the @code{sync} system call before getting any usage data. On
12147 some systems (notably Solaris), doing this yields more up to date results,
12148 but in general this option makes @command{df} much slower, especially when
12149 there are many or very busy file systems.
12153 @cindex grand total of file system size, usage and available space
12154 Print a grand total of all arguments after all arguments have
12155 been processed. This can be used to find out the total size, usage
12156 and available space of all listed devices. If no arguments are specified
12157 df will try harder to elide file systems insignificant to the total
12158 available space, by suppressing duplicate remote file systems.
12160 For the grand total line, @command{df} prints @samp{"total"} into the
12161 @var{source} column, and @samp{"-"} into the @var{target} column.
12162 If there is no @var{source} column (see @option{--output}), then
12163 @command{df} prints @samp{"total"} into the @var{target} column,
12166 @item -t @var{fstype}
12167 @itemx --type=@var{fstype}
12170 @cindex file system types, limiting output to certain
12171 Limit the listing to file systems of type @var{fstype}. Multiple
12172 file system types can be specified by giving multiple @option{-t} options.
12173 By default, nothing is omitted.
12176 @itemx --print-type
12178 @opindex --print-type
12179 @cindex file system types, printing
12180 Print each file system's type. The types printed here are the same ones
12181 you can include or exclude with @option{-t} and @option{-x}. The particular
12182 types printed are whatever is supported by the system. Here are some of
12183 the common names (this list is certainly not exhaustive):
12188 @cindex NFS file system type
12189 An NFS file system, i.e., one mounted over a network from another
12190 machine. This is the one type name which seems to be used uniformly by
12193 @item ext2@r{, }ext3@r{, }ext4@r{, }xfs@r{, }btrfs@dots{}
12194 @cindex Linux file system types
12195 @cindex local file system types
12196 @opindex ext2 @r{file system type}
12197 @opindex ext3 @r{file system type}
12198 @opindex ext4 @r{file system type}
12199 @opindex xfs @r{file system type}
12200 @opindex btrfs @r{file system type}
12201 A file system on a locally-mounted device. (The system might even
12202 support more than one type here; GNU/Linux does.)
12204 @item iso9660@r{, }cdfs
12205 @cindex CD-ROM file system type
12206 @cindex DVD file system type
12207 @cindex ISO9660 file system type
12208 @opindex iso9660 @r{file system type}
12209 @opindex cdfs @r{file system type}
12210 A file system on a CD or DVD drive. HP-UX uses @samp{cdfs}, most other
12211 systems use @samp{iso9660}.
12214 @cindex NTFS file system
12215 @cindex DOS file system
12216 @cindex MS-DOS file system
12217 @cindex MS-Windows file system
12218 @opindex ntfs @r{file system file}
12219 @opindex fat @r{file system file}
12220 File systems used by MS-Windows / MS-DOS.
12224 @item -x @var{fstype}
12225 @itemx --exclude-type=@var{fstype}
12227 @opindex --exclude-type
12228 Limit the listing to file systems not of type @var{fstype}.
12229 Multiple file system types can be eliminated by giving multiple
12230 @option{-x} options. By default, no file system types are omitted.
12233 Ignored; for compatibility with System V versions of @command{df}.
12237 @command{df} is installed only on systems that have usable mount tables,
12238 so portable scripts should not rely on its existence.
12241 Failure includes the case where no output is generated, so you can
12242 inspect the exit status of a command like @samp{df -t ext3 -t reiserfs
12243 @var{dir}} to test whether @var{dir} is on a file system of type
12244 @samp{ext3} or @samp{reiserfs}.
12246 Since the list of file systems (@var{mtab}) is needed to determine the
12247 file system type, failure includes the cases when that list cannot
12248 be read and one or more of the options @option{-a}, @option{-l}, @option{-t}
12249 or @option{-x} is used together with a file name argument.
12252 @node du invocation
12253 @section @command{du}: Estimate file space usage
12256 @cindex file space usage
12257 @cindex disk usage for files
12259 @command{du} reports the amount of file system space used by the set
12260 of specified files and for each subdirectory (of directory arguments).
12264 du [@var{option}]@dots{} [@var{file}]@dots{}
12267 With no arguments, @command{du} reports the file system space for the current
12268 directory. Normally the space is printed in units of
12269 1024 bytes, but this can be overridden (@pxref{Block size}).
12270 Non-integer quantities are rounded up to the next higher unit.
12272 If two or more hard links point to the same file, only one of the hard
12273 links is counted. The @var{file} argument order affects which links
12274 are counted, and changing the argument order may change the numbers
12275 and entries that @command{du} outputs.
12277 The program accepts the following options. Also see @ref{Common options}.
12287 Show counts for all files, not just directories.
12289 @item --apparent-size
12290 @opindex --apparent-size
12291 Print apparent sizes, rather than file system usage. The apparent size of a
12292 file is the number of bytes reported by @code{wc -c} on regular files,
12293 or more generally, @code{ls -l --block-size=1} or @code{stat --format=%s}.
12294 For example, a file containing the word @samp{zoo} with no newline would,
12295 of course, have an apparent size of 3. Such a small file may require
12296 anywhere from 0 to 16 KiB or more of file system space, depending on
12297 the type and configuration of the file system on which the file resides.
12298 However, a sparse file created with this command:
12301 dd bs=1 seek=2GiB if=/dev/null of=big
12305 has an apparent size of 2 GiB, yet on most modern
12306 file systems, it actually uses almost no space.
12308 @item -B @var{size}
12309 @itemx --block-size=@var{size}
12311 @opindex --block-size
12313 Scale sizes by @var{size} before printing them (@pxref{Block size}).
12314 For example, @option{-BG} prints sizes in units of 1,073,741,824 bytes.
12320 Equivalent to @code{--apparent-size --block-size=1}.
12326 @cindex grand total of file system space
12327 Print a grand total of all arguments after all arguments have
12328 been processed. This can be used to find out the total file system usage of
12329 a given set of files or directories.
12332 @itemx --dereference-args
12334 @opindex --dereference-args
12335 Dereference symbolic links that are command line arguments.
12336 Does not affect other symbolic links. This is helpful for finding
12337 out the file system usage of directories, such as @file{/usr/tmp}, which
12338 are often symbolic links.
12340 @item -d @var{depth}
12341 @itemx --max-depth=@var{depth}
12342 @opindex -d @var{depth}
12343 @opindex --max-depth=@var{depth}
12344 @cindex limiting output of @command{du}
12345 Show the total for each directory (and file if --all) that is at
12346 most MAX_DEPTH levels down from the root of the hierarchy. The root
12347 is at level 0, so @code{du --max-depth=0} is equivalent to @code{du -s}.
12349 @c --files0-from=FILE
12350 @filesZeroFromOption{du,, with the @option{--total} (@option{-c}) option}
12354 Equivalent to @option{--dereference-args} (@option{-D}).
12360 @cindex inode usage, dereferencing in @command{du}
12361 List inode usage information instead of block usage.
12362 This option is useful for finding directories which contain many files, and
12363 therefore eat up most of the inodes space of a file system (see @command{df},
12364 option @option{--inodes}).
12365 It can well be combined with the options @option{-a}, @option{-c},
12366 @option{-h}, @option{-l}, @option{-s}, @option{-S}, @option{-t} and
12367 @option{-x}; however, passing other options regarding the block size, for
12368 example @option{-b}, @option{-m} and @option{--apparent-size}, is ignored.
12372 @cindex kibibytes for file sizes
12373 Print sizes in 1024-byte blocks, overriding the default block size
12374 (@pxref{Block size}).
12375 This option is equivalent to @option{--block-size=1K}.
12378 @itemx --dereference
12380 @opindex --dereference
12381 @cindex symbolic links, dereferencing in @command{du}
12382 Dereference symbolic links (show the file system space used by the file
12383 or directory that the link points to instead of the space used by
12387 @itemx --count-links
12389 @opindex --count-links
12390 @cindex hard links, counting in @command{du}
12391 Count the size of all files, even if they have appeared already (as a
12396 @cindex mebibytes for file sizes
12397 Print sizes in 1,048,576-byte blocks, overriding the default block size
12398 (@pxref{Block size}).
12399 This option is equivalent to @option{--block-size=1M}.
12402 @itemx --no-dereference
12404 @opindex --no-dereference
12405 @cindex symbolic links, dereferencing in @command{du}
12406 For each symbolic link encountered by @command{du},
12407 consider the file system space used by the symbolic link itself.
12410 @itemx --separate-dirs
12412 @opindex --separate-dirs
12413 Normally, in the output of @command{du} (when not using @option{--summarize}),
12414 the size listed next to a directory name, @var{d}, represents the sum
12415 of sizes of all entries beneath @var{d} as well as the size of @var{d} itself.
12416 With @option{--separate-dirs}, the size reported for a directory name,
12417 @var{d}, will exclude the size of any subdirectories.
12424 @opindex --summarize
12425 Display only a total for each argument.
12427 @item -t @var{size}
12428 @itemx --threshold=@var{size}
12430 @opindex --threshold
12431 Exclude entries based on a given @var{size}. The @var{size} refers to used
12432 blocks in normal mode (@pxref{Block size}), or inodes count in conjunction
12433 with the @option{--inodes} option.
12435 If @var{size} is positive, then @command{du} will only print entries with a size
12436 greater than or equal to that.
12438 If @var{size} is negative, then @command{du} will only print entries with a size
12439 smaller than or equal to that.
12441 Although GNU @command{find} can be used to find files of a certain size,
12442 @command{du}'s @option{--threshold} option can be used to also filter
12443 directories based on a given size.
12445 Please note that the @option{--threshold} option can be combined with the
12446 @option{--apparent-size} option, and in this case would elide entries based on
12449 Please note that the @option{--threshold} option can be combined with the
12450 @option{--inodes} option, and in this case would elide entries based on
12453 Here's how you would use @option{--threshold} to find directories with a size
12454 greater than or equal to 200 megabytes:
12457 du --threshold=200MB
12460 Here's how you would use @option{--threshold} to find directories and files -
12461 note the @option{-a} - with an apparent size smaller than or equal to 500 bytes:
12464 du -a -t -500 --apparent-size
12467 Here's how you would use @option{--threshold} to find directories on the root
12468 file system with more than 20000 inodes used in the directory tree below:
12471 du --inodes -x --threshold=20000 /
12477 @cindex last modified dates, displaying in @command{du}
12478 Show the most recent modification timestamp (mtime) of any file in the
12479 directory, or any of its subdirectories. @xref{File timestamps}.
12482 @itemx --time=status
12485 @opindex ctime@r{, show the most recent}
12486 @opindex status time@r{, show the most recent}
12487 @opindex use time@r{, show the most recent}
12488 Show the most recent status change timestamp (ctime) of any file in
12489 the directory, or any of its subdirectories. @xref{File timestamps}.
12492 @itemx --time=access
12494 @opindex atime@r{, show the most recent}
12495 @opindex access timestamp@r{, show the most recent}
12496 Show the most recent access timestamp (atime) of any file in the
12497 directory, or any of its subdirectories. @xref{File timestamps}.
12499 @item --time-style=@var{style}
12500 @opindex --time-style
12502 List timestamps in style @var{style}. This option has an effect only if
12503 the @option{--time} option is also specified. The @var{style} should
12504 be one of the following:
12507 @item +@var{format}
12509 List timestamps using @var{format}, where @var{format} is interpreted
12510 like the format argument of @command{date} (@pxref{date invocation}).
12511 For example, @option{--time-style="+%Y-%m-%d %H:%M:%S"} causes
12512 @command{du} to list timestamps like @samp{2020-07-21 23:45:56}. As
12513 with @command{date}, @var{format}'s interpretation is affected by the
12514 @env{LC_TIME} locale category.
12517 List timestamps in full using ISO 8601-like date, time, and time zone
12518 components with nanosecond precision, e.g., @samp{2020-07-21
12519 23:45:56.477817180 -0400}. This style is equivalent to
12520 @samp{+%Y-%m-%d %H:%M:%S.%N %z}.
12523 List ISO 8601 date and time components with minute precision, e.g.,
12524 @samp{2020-07-21 23:45}. These timestamps are shorter than
12525 @samp{full-iso} timestamps, and are usually good enough for everyday
12526 work. This style is equivalent to @samp{+%Y-%m-%d %H:%M}.
12529 List ISO 8601 dates for timestamps, e.g., @samp{2020-07-21}.
12530 This style is equivalent to @samp{+%Y-%m-%d}.
12534 You can specify the default value of the @option{--time-style} option
12535 with the environment variable @env{TIME_STYLE}; if @env{TIME_STYLE} is not set
12536 the default style is @samp{long-iso}. For compatibility with @command{ls},
12537 if @env{TIME_STYLE} begins with @samp{+} and contains a newline,
12538 the newline and any later characters are ignored; if @env{TIME_STYLE}
12539 begins with @samp{posix-} the @samp{posix-} is ignored; and if
12540 @env{TIME_STYLE} is @samp{locale} it is ignored.
12542 @item -X @var{file}
12543 @itemx --exclude-from=@var{file}
12544 @opindex -X @var{file}
12545 @opindex --exclude-from=@var{file}
12546 @cindex excluding files from @command{du}
12547 Like @option{--exclude}, except take the patterns to exclude from @var{file},
12548 one per line. If @var{file} is @samp{-}, take the patterns from standard
12551 @item --exclude=@var{pattern}
12552 @opindex --exclude=@var{pattern}
12553 @cindex excluding files from @command{du}
12554 When recursing, skip subdirectories or files matching @var{pattern}.
12555 For example, @code{du --exclude='*.o'} excludes files whose names
12559 @itemx --one-file-system
12561 @opindex --one-file-system
12562 @cindex one file system, restricting @command{du} to
12563 Skip directories that are on different file systems from the one that
12564 the argument being processed is on.
12568 @cindex NFS mounts from BSD to HP-UX
12569 On BSD systems, @command{du} reports sizes that are half the correct
12570 values for files that are NFS-mounted from HP-UX systems. On HP-UX
12571 systems, it reports sizes that are twice the correct values for
12572 files that are NFS-mounted from BSD systems. This is due to a flaw
12573 in HP-UX; it also affects the HP-UX @command{du} program.
12578 @node stat invocation
12579 @section @command{stat}: Report file or file system status
12582 @cindex file status
12583 @cindex file system status
12585 @command{stat} displays information about the specified file(s). Synopsis:
12588 stat [@var{option}]@dots{} [@var{file}]@dots{}
12591 With no option, @command{stat} reports all information about the given files.
12592 But it also can be used to report the information of the file systems the
12593 given files are located on. If the files are links, @command{stat} can
12594 also give information about the files the links point to.
12596 @mayConflictWithShellBuiltIn{stat}
12601 @itemx --dereference
12603 @opindex --dereference
12604 @cindex symbolic links, dereferencing in @command{stat}
12605 Change how @command{stat} treats symbolic links.
12606 With this option, @command{stat} acts on the file referenced
12607 by each symbolic link argument.
12608 Without it, @command{stat} acts on any symbolic link argument directly.
12611 @itemx --file-system
12613 @opindex --file-system
12614 @cindex file systems
12615 Report information about the file systems where the given files are located
12616 instead of information about the files themselves.
12617 This option implies the @option{-L} option.
12619 @item --cached=@var{mode}
12620 @opindex --cached=@var{mode}
12621 @cindex attribute caching
12622 Control how attributes are read from the file system;
12623 if supported by the system. This allows one to
12624 control the trade-off between freshness and efficiency
12625 of attribute access, especially useful with remote file systems.
12630 Always read the already cached attributes if available.
12633 Always sychronize with the latest file system attributes.
12634 This also mounts automounted files.
12637 Leave the caching behavior to the underlying file system.
12642 @itemx --format=@var{format}
12644 @opindex --format=@var{format}
12645 @cindex output format
12646 Use @var{format} rather than the default format.
12647 @var{format} is automatically newline-terminated, so
12648 running a command like the following with two or more @var{file}
12649 operands produces a line of output for each operand:
12651 $ stat --format=%d:%i / /usr
12656 @item --printf=@var{format}
12657 @opindex --printf=@var{format}
12658 @cindex output format
12659 Use @var{format} rather than the default format.
12660 Like @option{--format}, but interpret backslash escapes,
12661 and do not output a mandatory trailing newline.
12662 If you want a newline, include @samp{\n} in the @var{format}.
12663 Here's how you would use @option{--printf} to print the device
12664 and inode numbers of @file{/} and @file{/usr}:
12666 $ stat --printf='%d:%i\n' / /usr
12675 @cindex terse output
12676 Print the information in terse form, suitable for parsing by other programs.
12678 The output of the following commands are identical and the @option{--format}
12679 also identifies the items printed (in fuller form) in the default format.
12680 Note the format string would include another @samp{%C} at the end with an
12681 active SELinux security context.
12683 $ stat --format="%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %W %o" ...
12687 The same illustrating terse output in @option{--file-system} mode:
12689 $ stat -f --format="%n %i %l %t %s %S %b %f %a %c %d" ...
12690 $ stat -f --terse ...
12694 The valid @var{format} directives for files with @option{--format} and
12695 @option{--printf} are:
12698 @item %a - Permission bits in octal (note @samp{#} and @samp{0} printf flags)
12699 @item %A - Permission bits in symbolic form (similar to @command{ls -ld})
12700 @item %b - Number of blocks allocated (see @samp{%B})
12701 @item %B - The size in bytes of each block reported by @samp{%b}
12702 @item %C - The SELinux security context of a file, if available
12703 @item %d - Device number in decimal (st_dev)
12704 @item %D - Device number in hex (st_dev)
12705 @item %Hd - Major device number in decimal
12706 @item %Ld - Minor device number in decimal
12707 @item %f - Raw mode in hex
12708 @item %F - File type
12709 @item %g - Group ID of owner
12710 @item %G - Group name of owner
12711 @item %h - Number of hard links
12712 @item %i - Inode number
12713 @item %m - Mount point (See note below)
12714 @item %n - File name
12715 @item %N - Quoted file name with dereference if symbolic link (see below)
12716 @item %o - Optimal I/O transfer size hint
12717 @item %s - Total size, in bytes
12718 @item %r - Device type in decimal (st_rdev)
12719 @item %R - Device type in hex (st_rdev)
12720 @item %Hr - Major device type in decimal (see below)
12721 @item %Lr - Minor device type in decimal (see below)
12722 @item %t - Major device type in hex (see below)
12723 @item %T - Minor device type in hex (see below)
12724 @item %u - User ID of owner
12725 @item %U - User name of owner
12726 @item %w - Time of file birth, or @samp{-} if unknown
12727 @item %W - Time of file birth as seconds since Epoch, or @samp{0}
12728 @item %x - Time of last access
12729 @item %X - Time of last access as seconds since Epoch
12730 @item %y - Time of last data modification
12731 @item %Y - Time of last data modification as seconds since Epoch
12732 @item %z - Time of last status change
12733 @item %Z - Time of last status change as seconds since Epoch
12736 The @samp{%a} format prints the octal mode, and so it is useful
12737 to control the zero padding of the output with the @samp{#} and @samp{0}
12738 printf flags. For example to pad to at least 3 wide while making larger
12739 numbers unambiguously octal, you can use @samp{%#03a}.
12741 The @samp{%N} format can be set with the environment variable
12742 @env{QUOTING_STYLE}@. If that environment variable is not set,
12743 the default value is @samp{shell-escape-always}. Valid quoting styles are:
12746 The @samp{r}, @samp{R}, @samp{%t}, and @samp{%T} formats operate on the st_rdev
12747 member of the stat(2) structure, i.e., the represented device rather than
12748 the containing device, and so are only defined for character and block
12749 special files. On some systems or file types, st_rdev may be used to
12750 represent other quantities.
12752 The @samp{%W}, @samp{%X}, @samp{%Y}, and @samp{%Z} formats accept a
12753 precision preceded by a period to specify the number of digits to
12754 print after the decimal point. For example, @samp{%.3X} outputs the
12755 access timestamp to millisecond precision. If a period is given but no
12756 precision, @command{stat} uses 9 digits, so @samp{%.X} is equivalent to
12757 @samp{%.9X}@. When discarding excess precision, timestamps are truncated
12758 toward minus infinity.
12762 $ stat -c '[%015Y]' /usr
12765 $ stat -c '[%15Y]' /usr
12767 $ stat -c '[%-15Y]' /usr
12770 $ stat -c '[%.3Y]' /usr
12772 $ stat -c '[%.Y]' /usr
12773 [1288929712.114951834]
12776 The mount point printed by @samp{%m} is similar to that output
12777 by @command{df}, except that:
12780 stat does not dereference symlinks by default
12781 (unless @option{-L} is specified)
12783 stat does not search for specified device nodes in the
12784 file system list, instead operating on them directly
12787 stat outputs the alias for a bind mounted file, rather than
12788 the initial mount point of its backing device.
12789 One can recursively call stat until there is no change in output,
12790 to get the current base mount point
12793 When listing file system information (@option{--file-system} (@option{-f})),
12794 you must use a different set of @var{format} directives:
12797 @item %a - Free blocks available to non-super-user
12798 @item %b - Total data blocks in file system
12799 @item %c - Total file nodes in file system
12800 @item %d - Free file nodes in file system
12801 @item %f - Free blocks in file system
12802 @item %i - File System ID in hex
12803 @item %l - Maximum length of file names
12804 @item %n - File name
12805 @item %s - Block size (for faster transfers)
12806 @item %S - Fundamental block size (for block counts)
12807 @item %t - Type in hex
12808 @item %T - Type in human readable form
12812 Timestamps are listed according to the time zone rules specified by
12813 the @env{TZ} environment variable, or by the system default rules if
12814 @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
12815 with @env{TZ}, libc, The GNU C Library Reference Manual}.
12820 @node sync invocation
12821 @section @command{sync}: Synchronize cached writes to persistent storage
12824 @cindex synchronize file system and memory
12825 @cindex Synchronize cached writes to persistent storage
12827 @command{sync} synchronizes in memory files or file systems to persistent
12831 sync [@var{option}] [@var{file}]@dots{}
12834 @cindex superblock, writing
12835 @cindex inodes, written buffered
12836 @command{sync} writes any data buffered in memory out to the storage device.
12838 include (but is not limited to) modified superblocks, modified inodes,
12839 and delayed reads and writes. This must be implemented by the kernel;
12840 The @command{sync} program does nothing but exercise the @code{sync},
12841 @code{syncfs}, @code{fsync}, and @code{fdatasync} system calls.
12843 @cindex crashes and corruption
12844 The kernel keeps data in memory to avoid doing (relatively slow) device
12845 reads and writes. This improves performance, but if the computer
12846 crashes, data may be lost or the file system corrupted as a
12847 result. The @command{sync} command instructs the kernel to write
12848 data in memory to persistent storage.
12850 If any argument is specified then only those files will be
12851 synchronized using the fsync(2) syscall by default.
12853 If at least one file is specified, it is possible to change the
12854 synchronization method with the following options. Also see
12855 @ref{Common options}.
12861 Use fdatasync(2) to sync only the data for the file,
12862 and any metadata required to maintain file system consistency.
12865 @itemx --file-system
12866 @opindex --file-system
12867 Synchronize all the I/O waiting for the file systems that contain the file,
12868 using the syscall syncfs(2). Note you would usually @emph{not} specify
12869 this option if passing a device node like @samp{/dev/sda} for example,
12870 as that would sync the containing file system rather than the referenced one.
12871 Note also that depending on the system, passing individual device nodes or files
12872 may have different sync characteristics than using no arguments.
12873 I.e., arguments passed to fsync(2) may provide greater guarantees through
12874 write barriers, than a global sync(2) used when no arguments are provided.
12880 @node truncate invocation
12881 @section @command{truncate}: Shrink or extend the size of a file
12884 @cindex truncating, file sizes
12886 @command{truncate} shrinks or extends the size of each @var{file} to the
12887 specified size. Synopsis:
12890 truncate @var{option}@dots{} @var{file}@dots{}
12893 @cindex files, creating
12894 Any @var{file} that does not exist is created.
12896 @cindex sparse files, creating
12897 @cindex holes, creating files with
12898 If a @var{file} is larger than the specified size, the extra data is lost.
12899 If a @var{file} is shorter, it is extended and the sparse extended part
12900 (or hole) reads as zero bytes.
12902 The program accepts the following options. Also see @ref{Common options}.
12909 @opindex --no-create
12910 Do not create files that do not exist.
12915 @opindex --io-blocks
12916 Treat @var{size} as number of I/O blocks of the @var{file} rather than bytes.
12918 @item -r @var{rfile}
12919 @itemx --reference=@var{rfile}
12921 @opindex --reference
12922 Base the size of each @var{file} on the size of @var{rfile}.
12924 @item -s @var{size}
12925 @itemx --size=@var{size}
12928 Set or adjust the size of each @var{file} according to @var{size}.
12929 @var{size} is in bytes unless @option{--io-blocks} is specified.
12930 @multiplierSuffixesNoBlocks{size}
12932 @var{size} may also be prefixed by one of the following to adjust
12933 the size of each @var{file} based on its current size:
12935 @samp{+} => extend by
12936 @samp{-} => reduce by
12937 @samp{<} => at most
12938 @samp{>} => at least
12939 @samp{/} => round down to multiple of
12940 @samp{%} => round up to multiple of
12948 @node Printing text
12949 @chapter Printing text
12951 @cindex printing text, commands for
12952 @cindex commands for printing text
12954 This section describes commands that display text strings.
12957 * echo invocation:: Print a line of text.
12958 * printf invocation:: Format and print data.
12959 * yes invocation:: Print a string until interrupted.
12963 @node echo invocation
12964 @section @command{echo}: Print a line of text
12967 @cindex displaying text
12968 @cindex printing text
12969 @cindex text, displaying
12970 @cindex arbitrary text, displaying
12972 @command{echo} writes each given @var{string} to standard output, with a
12973 space between each and a newline after the last one. Synopsis:
12976 echo [@var{option}]@dots{} [@var{string}]@dots{}
12979 @mayConflictWithShellBuiltIn{echo}
12981 Due to historical and backwards compatibility reasons, certain bare option-like
12982 strings cannot be passed to @command{echo} as non-option arguments.
12983 It is therefore not advisable to use @command{echo} for printing unknown or
12984 variable arguments. The @command{printf} command is recommended as a more
12985 portable and flexible replacement for tasks historically performed by
12986 @command{echo}. @xref{printf invocation}.
12988 The program accepts the following options. Also see @ref{Common options}.
12989 Options must precede operands, and the normally-special argument
12990 @samp{--} has no special meaning and is treated like any other
12996 Do not output the trailing newline.
13000 @cindex backslash escapes
13001 Enable interpretation of the following backslash-escaped characters in
13010 produce no further output
13026 the eight-bit value that is the octal number @var{nnn}
13027 (zero to three octal digits), if @var{nnn} is
13028 a nine-bit value, the ninth bit is ignored
13030 the eight-bit value that is the octal number @var{nnn}
13031 (one to three octal digits), if @var{nnn} is
13032 a nine-bit value, the ninth bit is ignored
13034 the eight-bit value that is the hexadecimal number @var{hh}
13035 (one or two hexadecimal digits)
13040 @cindex backslash escapes
13041 Disable interpretation of backslash escapes in each @var{string}.
13042 This is the default. If @option{-e} and @option{-E} are both
13043 specified, the last one given takes effect.
13047 @vindex POSIXLY_CORRECT
13048 If the @env{POSIXLY_CORRECT} environment variable is set, then when
13049 @command{echo}'s first argument is not @option{-n} it outputs
13050 option-like arguments instead of treating them as options. For
13051 example, @code{echo -ne hello} outputs @samp{-ne hello} instead of
13052 plain @samp{hello}. Also backslash escapes are always enabled.
13053 Note to echo the string @samp{-n}, one of the characters
13054 can be escaped in either octal or hexadecimal representation.
13055 For example, @code{echo -e '\x2dn'}.
13057 POSIX does not require support for any options, and says
13058 that the behavior of @command{echo} is implementation-defined if any
13059 @var{string} contains a backslash or if the first argument is @option{-n}.
13060 Portable programs should use the @command{printf} command instead.
13061 @xref{printf invocation}.
13066 @node printf invocation
13067 @section @command{printf}: Format and print data
13070 @command{printf} does formatted printing of text. Synopsis:
13073 printf @var{format} [@var{argument}]@dots{}
13076 @command{printf} prints the @var{format} string, interpreting @samp{%}
13077 directives and @samp{\} escapes to format numeric and string arguments
13078 in a way that is mostly similar to the C @samp{printf} function.
13079 @xref{Output Conversion Syntax,, @command{printf} format directives,
13080 libc, The GNU C Library Reference Manual}, for details.
13081 The differences are listed below.
13083 @mayConflictWithShellBuiltIn{printf}
13088 The @var{format} argument is reused as necessary to convert all the
13089 given @var{argument}s. For example, the command @samp{printf %s a b}
13093 Missing @var{argument}s are treated as null strings or as zeros,
13094 depending on whether the context expects a string or a number. For
13095 example, the command @samp{printf %sx%d} prints @samp{x0}.
13099 An additional escape, @samp{\c}, causes @command{printf} to produce no
13100 further output. For example, the command @samp{printf 'A%sC\cD%sF' B
13101 E} prints @samp{ABC}.
13104 The hexadecimal escape sequence @samp{\x@var{hh}} has at most two
13105 digits, as opposed to C where it can have an unlimited number of
13106 digits. For example, the command @samp{printf '\x07e'} prints two
13107 bytes, whereas the C statement @samp{printf ("\x07e")} prints just
13112 An additional directive @samp{%b}, prints its
13113 argument string with @samp{\} escapes interpreted in the same way as in
13114 the @var{format} string, except that octal escapes are of the form
13115 @samp{\0@var{ooo}} where @var{ooo} is 0 to 3 octal digits. If
13116 @samp{\@var{ooo}} is nine-bit value, ignore the ninth bit.
13117 If a precision is also given, it limits the number of bytes printed
13118 from the converted string.
13122 An additional directive @samp{%q}, prints its argument string
13123 in a format that can be reused as input by most shells.
13124 Non-printable characters are escaped with the POSIX proposed @samp{$''} syntax,
13125 and shell metacharacters are quoted appropriately.
13126 This is an equivalent format to @command{ls --quoting=shell-escape} output.
13129 Numeric arguments must be single C constants, possibly with leading
13130 @samp{+} or @samp{-}. For example, @samp{printf %.4d -3} outputs
13134 @vindex POSIXLY_CORRECT
13135 If the leading character of a numeric argument is @samp{"} or @samp{'}
13136 then its value is the numeric value of the immediately following
13137 character. Any remaining characters are silently ignored if the
13138 @env{POSIXLY_CORRECT} environment variable is set; otherwise, a
13139 warning is printed. For example, @samp{printf "%d" "'a"} outputs
13140 @samp{97} on hosts that use the ASCII character set, since
13141 @samp{a} has the numeric value 97 in ASCII.
13146 A floating point argument is interpreted according to
13147 the @env{LC_NUMERIC} category of either the current or the C locale,
13148 and is printed according to the current locale.
13149 For example, in a locale whose decimal point character is a comma,
13150 the command @samp{printf '%g %g' 2,5 2.5} outputs @samp{2,5 2,5}.
13151 @xref{Floating point}.
13155 @command{printf} interprets @samp{\@var{ooo}} in @var{format} as an octal number
13156 (if @var{ooo} is 1 to 3 octal digits) specifying a byte to print,
13157 and @samp{\x@var{hh}} as a hexadecimal number (if @var{hh} is 1 to 2 hex
13158 digits) specifying a character to print.
13159 Note however that when @samp{\@var{ooo}} specifies a number larger than 255,
13160 @command{printf} ignores the ninth bit.
13161 For example, @samp{printf '\400'} is equivalent to @samp{printf '\0'}.
13166 @cindex ISO/IEC 10646
13168 @command{printf} interprets two character syntaxes introduced in
13170 @samp{\u} for 16-bit Unicode (ISO/IEC 10646)
13171 characters, specified as
13172 four hexadecimal digits @var{hhhh}, and @samp{\U} for 32-bit Unicode
13173 characters, specified as eight hexadecimal digits @var{hhhhhhhh}.
13174 @command{printf} outputs the Unicode characters
13175 according to the @env{LC_CTYPE} locale. Unicode characters in the ranges
13176 U+0000@dots{}U+009F, U+D800@dots{}U+DFFF cannot be specified by this syntax,
13177 except for U+0024 ($), U+0040 (@@), and U+0060 (@`).
13179 The processing of @samp{\u} and @samp{\U} requires a full-featured
13180 @code{iconv} facility. It is activated on systems with glibc 2.2 (or newer),
13181 or when @code{libiconv} is installed prior to this package. Otherwise
13182 @samp{\u} and @samp{\U} will print as-is.
13184 The only options are a lone @option{--help} or
13185 @option{--version}. @xref{Common options}.
13186 Options must precede operands.
13188 The Unicode character syntaxes are useful for writing strings in a locale
13189 independent way. For example, a string containing the Euro currency symbol
13192 $ env printf '\u20AC 14.95'
13196 will be output correctly in all locales supporting the Euro symbol
13197 (ISO-8859-15, UTF-8, and others). Similarly, a Chinese string
13200 $ env printf '\u4e2d\u6587'
13204 will be output correctly in all Chinese locales (GB2312, BIG5, UTF-8, etc).
13206 Note that in these examples, the @command{printf} command has been
13207 invoked via @command{env} to ensure that we run the program found via
13208 your shell's search path, and not a shell alias or a built-in function.
13210 For larger strings, you don't need to look up the hexadecimal code
13211 values of each character one by one. ASCII characters mixed with \u
13212 escape sequences is also known as the JAVA source file encoding. You can
13213 use GNU recode 3.5c (or newer) to convert strings to this encoding. Here
13214 is how to convert a piece of text into a shell script which will output
13215 this text in a locale-independent way:
13218 $ LC_CTYPE=zh_CN.big5 /usr/local/bin/printf \
13219 '\u4e2d\u6587\n' > sample.txt
13220 $ recode BIG5..JAVA < sample.txt \
13221 | sed -e "s|^|/usr/local/bin/printf '|" -e "s|$|\\\\n'|" \
13228 @node yes invocation
13229 @section @command{yes}: Print a string until interrupted
13232 @cindex repeated output of a string
13234 @command{yes} prints the command line arguments, separated by spaces and
13235 followed by a newline, forever until it is killed. If no arguments are
13236 given, it prints @samp{y} followed by a newline forever until killed.
13238 Upon a write error, @command{yes} exits with status @samp{1}.
13240 The only options are a lone @option{--help} or @option{--version}.
13241 To output an argument that begins with
13242 @samp{-}, precede it with @option{--}, e.g., @samp{yes -- --help}.
13243 @xref{Common options}.
13247 @chapter Conditions
13250 @cindex commands for exit status
13251 @cindex exit status commands
13253 This section describes commands that are primarily useful for their exit
13254 status, rather than their output. Thus, they are often used as the
13255 condition of shell @code{if} statements, or as the last command in a
13259 * false invocation:: Do nothing, unsuccessfully.
13260 * true invocation:: Do nothing, successfully.
13261 * test invocation:: Check file types and compare values.
13262 * expr invocation:: Evaluate expressions.
13266 @node false invocation
13267 @section @command{false}: Do nothing, unsuccessfully
13270 @cindex do nothing, unsuccessfully
13271 @cindex failure exit status
13272 @cindex exit status of @command{false}
13274 @command{false} does nothing except return an exit status of 1, meaning
13275 @dfn{failure}. It can be used as a place holder in shell scripts
13276 where an unsuccessful command is needed.
13277 In most modern shells, @command{false} is a built-in command, so when
13278 you use @samp{false} in a script, you're probably using the built-in
13279 command, not the one documented here.
13281 @command{false} honors the @option{--help} and @option{--version} options.
13283 This version of @command{false} is implemented as a C program, and is thus
13284 more secure and faster than a shell script implementation, and may safely
13285 be used as a dummy shell for the purpose of disabling accounts.
13287 Note that @command{false} (unlike all other programs documented herein)
13288 exits unsuccessfully, even when invoked with
13289 @option{--help} or @option{--version}.
13291 Portable programs should not assume that the exit status of
13292 @command{false} is 1, as it is greater than 1 on some
13296 @node true invocation
13297 @section @command{true}: Do nothing, successfully
13300 @cindex do nothing, successfully
13302 @cindex successful exit
13303 @cindex exit status of @command{true}
13305 @command{true} does nothing except return an exit status of 0, meaning
13306 @dfn{success}. It can be used as a place holder in shell scripts
13307 where a successful command is needed, although the shell built-in
13308 command @code{:} (colon) may do the same thing faster.
13309 In most modern shells, @command{true} is a built-in command, so when
13310 you use @samp{true} in a script, you're probably using the built-in
13311 command, not the one documented here.
13313 @command{true} honors the @option{--help} and @option{--version} options.
13315 Note, however, that it is possible to cause @command{true}
13316 to exit with nonzero status: with the @option{--help} or @option{--version}
13317 option, and with standard
13318 output already closed or redirected to a file that evokes an I/O error.
13319 For example, using a Bourne-compatible shell:
13322 $ ./true --version >&-
13323 ./true: write error: Bad file number
13324 $ ./true --version > /dev/full
13325 ./true: write error: No space left on device
13328 This version of @command{true} is implemented as a C program, and is thus
13329 more secure and faster than a shell script implementation, and may safely
13330 be used as a dummy shell for the purpose of disabling accounts.
13332 @node test invocation
13333 @section @command{test}: Check file types and compare values
13336 @cindex check file types
13337 @cindex compare values
13338 @cindex expression evaluation
13340 @command{test} returns a status of 0 (true) or 1 (false) depending on the
13341 evaluation of the conditional expression @var{expr}. Each part of the
13342 expression must be a separate argument.
13344 @command{test} has file status checks, string operators, and numeric
13345 comparison operators.
13347 @command{test} has an alternate form that uses opening and closing
13348 square brackets instead a leading @samp{test}. For example, instead
13349 of @samp{test -d /}, you can write @samp{[ -d / ]}. The square
13350 brackets must be separate arguments; for example, @samp{[-d /]} does
13351 not have the desired effect. Since @samp{test @var{expr}} and @samp{[
13352 @var{expr} ]} have the same meaning, only the former form is discussed
13358 test @var{expression}
13360 [ @var{expression} ]
13365 @mayConflictWithShellBuiltIn{test}
13367 If @var{expression} is omitted, @command{test} returns false.
13368 If @var{expression} is a single argument,
13369 @command{test} returns false if the argument is null and true
13370 otherwise. The argument
13371 can be any string, including strings like @samp{-d}, @samp{-1},
13372 @samp{--}, @samp{--help}, and @samp{--version} that most other
13373 programs would treat as options. To get help and version information,
13374 invoke the commands @samp{[ --help} and @samp{[ --version}, without
13375 the usual closing brackets. @xref{Common options}.
13377 @cindex exit status of @command{test}
13381 0 if the expression is true,
13382 1 if the expression is false,
13383 2 if an error occurred.
13387 * File type tests:: -[bcdfhLpSt]
13388 * Access permission tests:: -[gkruwxOG]
13389 * File characteristic tests:: -e -s -nt -ot -ef
13390 * String tests:: -z -n = == !=
13391 * Numeric tests:: -eq -ne -lt -le -gt -ge
13392 * Connectives for test:: ! -a -o
13396 @node File type tests
13397 @subsection File type tests
13399 @cindex file type tests
13401 These options test for particular types of files. (Everything's a file,
13402 but not all files are the same!)
13406 @item -b @var{file}
13408 @cindex block special check
13409 True if @var{file} exists and is a block special device.
13411 @item -c @var{file}
13413 @cindex character special check
13414 True if @var{file} exists and is a character special device.
13416 @item -d @var{file}
13418 @cindex directory check
13419 True if @var{file} exists and is a directory.
13421 @item -f @var{file}
13423 @cindex regular file check
13424 True if @var{file} exists and is a regular file.
13426 @item -h @var{file}
13427 @itemx -L @var{file}
13430 @cindex symbolic link check
13431 True if @var{file} exists and is a symbolic link.
13432 Unlike all other file-related tests, this test does not dereference
13433 @var{file} if it is a symbolic link.
13435 @item -p @var{file}
13437 @cindex named pipe check
13438 True if @var{file} exists and is a named pipe.
13440 @item -S @var{file}
13442 @cindex socket check
13443 True if @var{file} exists and is a socket.
13447 @cindex terminal check
13448 True if @var{fd} is a file descriptor that is associated with a
13454 @node Access permission tests
13455 @subsection Access permission tests
13457 @cindex access permission tests
13458 @cindex permission tests
13460 These options test for particular access permissions.
13464 @item -g @var{file}
13466 @cindex set-group-ID check
13467 True if @var{file} exists and has its set-group-ID bit set.
13469 @item -k @var{file}
13471 @cindex sticky bit check
13472 True if @var{file} exists and has its @dfn{sticky} bit set.
13474 @item -r @var{file}
13476 @cindex readable file check
13477 True if @var{file} exists and the user has read access.
13479 @item -u @var{file}
13481 @cindex set-user-ID check
13482 True if @var{file} exists and has its set-user-ID bit set.
13484 @item -w @var{file}
13486 @cindex writable file check
13487 True if @var{file} exists and the user has write access.
13489 @item -x @var{file}
13491 @cindex executable file check
13492 True if @var{file} exists and the user has execute access
13493 (or search permission, if it is a directory).
13495 @item -O @var{file}
13497 @cindex owned by effective user ID check
13498 True if @var{file} exists and is owned by the current effective user ID.
13500 @item -G @var{file}
13502 @cindex owned by effective group ID check
13503 True if @var{file} exists and is owned by the current effective group ID.
13507 @node File characteristic tests
13508 @subsection File characteristic tests
13510 @cindex file characteristic tests
13512 These options test other file characteristics.
13516 @item -e @var{file}
13518 @cindex existence-of-file check
13519 True if @var{file} exists.
13521 @item -s @var{file}
13523 @cindex nonempty file check
13524 True if @var{file} exists and has a size greater than zero.
13526 @item @var{file1} -nt @var{file2}
13528 @cindex newer-than file check
13529 True if @var{file1} is newer (according to modification date) than
13530 @var{file2}, or if @var{file1} exists and @var{file2} does not.
13532 @item @var{file1} -ot @var{file2}
13534 @cindex older-than file check
13535 True if @var{file1} is older (according to modification date) than
13536 @var{file2}, or if @var{file2} exists and @var{file1} does not.
13538 @item @var{file1} -ef @var{file2}
13540 @cindex same file check
13541 @cindex hard link check
13542 True if @var{file1} and @var{file2} have the same device and inode
13543 numbers, i.e., if they are hard links to each other.
13545 @item -N @var{file}
13547 @cindex mtime-greater-atime file check
13548 True if @var{file} exists and has been modified (mtime) since it was
13555 @subsection String tests
13557 @cindex string tests
13559 These options test string characteristics. You may need to quote
13560 @var{string} arguments for the shell. For example:
13566 The quotes here prevent the wrong arguments from being passed to
13567 @command{test} if @samp{$V} is empty or contains special characters.
13571 @item -z @var{string}
13573 @cindex zero-length string check
13574 True if the length of @var{string} is zero.
13576 @item -n @var{string}
13577 @itemx @var{string}
13579 @cindex nonzero-length string check
13580 True if the length of @var{string} is nonzero.
13582 @item @var{string1} = @var{string2}
13584 @cindex equal string check
13585 True if the strings are equal.
13587 @item @var{string1} == @var{string2}
13589 @cindex equal string check
13590 True if the strings are equal (synonym for =).
13591 Note this form is not as portable to other
13592 shells and systems.
13594 @item @var{string1} != @var{string2}
13596 @cindex not-equal string check
13597 True if the strings are not equal.
13602 @node Numeric tests
13603 @subsection Numeric tests
13605 @cindex numeric tests
13606 @cindex arithmetic tests
13608 Numeric relational operators. The arguments must be entirely numeric
13609 (possibly negative), or the special expression @w{@code{-l @var{string}}},
13610 which evaluates to the length of @var{string}.
13614 @item @var{arg1} -eq @var{arg2}
13615 @itemx @var{arg1} -ne @var{arg2}
13616 @itemx @var{arg1} -lt @var{arg2}
13617 @itemx @var{arg1} -le @var{arg2}
13618 @itemx @var{arg1} -gt @var{arg2}
13619 @itemx @var{arg1} -ge @var{arg2}
13626 These arithmetic binary operators return true if @var{arg1} is equal,
13627 not-equal, less-than, less-than-or-equal, greater-than, or
13628 greater-than-or-equal than @var{arg2}, respectively.
13635 test -1 -gt -2 && echo yes
13637 test -l abc -gt 1 && echo yes
13640 @error{} test: integer expression expected before -eq
13644 @node Connectives for test
13645 @subsection Connectives for @command{test}
13647 @cindex logical connectives
13648 @cindex connectives, logical
13650 Note it's preferred to use shell logical primitives
13651 rather than these logical connectives internal to @command{test},
13652 because an expression may become ambiguous
13653 depending on the expansion of its parameters.
13655 For example, this becomes ambiguous when @samp{$1}
13656 is set to @samp{'!'} and @samp{$2} to the empty string @samp{''}:
13662 and should be written as:
13665 test "$1" && test "$2"
13668 Note the shell logical primitives also benefit from
13669 short circuit operation, which can be significant
13670 for file attribute tests.
13676 True if @var{expr} is false.
13677 @samp{!} has lower precedence than all parts of @var{expr}.
13678 Note @samp{!} needs to be specified to the left
13679 of a binary expression, I.e., @samp{'!' 1 -gt 2}
13680 rather than @samp{1 '!' -gt 2}.
13681 Also @samp{!} is often a shell special character
13682 and is best used quoted.
13685 @item @var{expr1} -a @var{expr2}
13687 @cindex logical and operator
13688 @cindex and operator
13689 True if both @var{expr1} and @var{expr2} are true.
13690 @samp{-a} is left associative,
13691 and has a higher precedence than @samp{-o}.
13693 @item @var{expr1} -o @var{expr2}
13695 @cindex logical or operator
13696 @cindex or operator
13697 True if either @var{expr1} or @var{expr2} is true.
13698 @samp{-o} is left associative.
13703 @node expr invocation
13704 @section @command{expr}: Evaluate expressions
13707 @cindex expression evaluation
13708 @cindex evaluation of expressions
13710 @command{expr} evaluates an expression and writes the result on standard
13711 output. Each token of the expression must be a separate argument.
13713 Operands are either integers or strings. Integers consist of one or
13714 more decimal digits, with an optional leading @samp{-}.
13715 @command{expr} converts
13716 anything appearing in an operand position to an integer or a string
13717 depending on the operation being applied to it.
13719 Strings are not quoted for @command{expr} itself, though you may need to
13720 quote them to protect characters with special meaning to the shell,
13721 e.g., spaces. However, regardless of whether it is quoted, a string
13722 operand should not be a parenthesis or any of @command{expr}'s
13723 operators like @code{+}, so you cannot safely pass an arbitrary string
13724 @code{$str} to expr merely by quoting it to the shell. One way to
13725 work around this is to use the GNU extension @code{+},
13726 (e.g., @code{+ "$str" = foo}); a more portable way is to use
13727 @code{@w{" $str"}} and to adjust the rest of the expression to take
13728 the leading space into account (e.g., @code{@w{" $str" = " foo"}}).
13730 You should not pass a negative integer or a string with leading
13731 @samp{-} as @command{expr}'s first argument, as it might be
13732 misinterpreted as an option; this can be avoided by parenthesization.
13733 Also, portable scripts should not use a string operand that happens to
13734 take the form of an integer; this can be worked around by inserting
13735 leading spaces as mentioned above.
13737 @cindex parentheses for grouping
13738 Operators may be given as infix symbols or prefix keywords. Parentheses
13739 may be used for grouping in the usual manner. You must quote
13740 parentheses and many operators to avoid the shell evaluating them,
13743 Because @command{expr} uses multiple-precision arithmetic, it works
13744 with integers wider than those of machine registers.
13746 The only options are @option{--help} and @option{--version}. @xref{Common
13747 options}. Options must precede operands.
13749 @cindex exit status of @command{expr}
13753 0 if the expression is neither null nor 0,
13754 1 if the expression is null or 0,
13755 2 if the expression is invalid,
13756 3 if an internal error occurred (e.g., arithmetic overflow).
13760 * String expressions:: + : match substr index length
13761 * Numeric expressions:: + - * / %
13762 * Relations for expr:: | & < <= = == != >= >
13763 * Examples of expr:: Examples.
13767 @node String expressions
13768 @subsection String expressions
13770 @cindex string expressions
13771 @cindex expressions, string
13773 @command{expr} supports pattern matching and other string operators. These
13774 have higher precedence than both the numeric and relational operators (in
13775 the next sections).
13779 @item @var{string} : @var{regex}
13780 @cindex pattern matching
13781 @cindex regular expression matching
13782 @cindex matching patterns
13783 Perform pattern matching. The arguments are converted to strings and the
13784 second is considered to be a (basic, a la GNU @code{grep}) regular
13785 expression, with a @code{^} implicitly prepended. The first argument is
13786 then matched against this regular expression.
13788 If @var{regex} does not use @samp{\(} and @samp{\)}, the @code{:}
13789 expression returns the number of characters matched, or 0 if the match
13792 If @var{regex} uses @samp{\(} and @samp{\)}, the @code{:} expression
13793 returns the part of @var{string} that matched the subexpression, or
13794 the null string if the match failed or the subexpression did not
13795 contribute to the match.
13797 @kindex \( @r{regexp operator}
13798 Only the first @samp{\( @dots{} \)} pair is relevant to the return
13799 value; additional pairs are meaningful only for grouping the regular
13800 expression operators.
13802 @kindex \+ @r{regexp operator}
13803 @kindex \? @r{regexp operator}
13804 @kindex \| @r{regexp operator}
13805 In the regular expression, @code{\+}, @code{\?}, and @code{\|} are
13806 operators which respectively match one or more, zero or one, or separate
13807 alternatives. These operators are GNU extensions. @xref{Regular Expressions,,
13808 Regular Expressions, grep, The GNU Grep Manual}, for details of
13809 regular expression syntax. Some examples are in @ref{Examples of expr}.
13811 @item match @var{string} @var{regex}
13813 An alternative way to do pattern matching. This is the same as
13814 @w{@samp{@var{string} : @var{regex}}}.
13816 @item substr @var{string} @var{position} @var{length}
13818 Returns the substring of @var{string} beginning at @var{position}
13819 with length at most @var{length}. If either @var{position} or
13820 @var{length} is negative, zero, or non-numeric, returns the null string.
13822 @item index @var{string} @var{charset}
13824 Returns the first position in @var{string} where the first character in
13825 @var{charset} was found. If no character in @var{charset} is found in
13826 @var{string}, return 0.
13828 @item length @var{string}
13830 Returns the length of @var{string}.
13832 @item + @var{token}
13834 Interpret @var{token} as a string, even if it is a keyword like @var{match}
13835 or an operator like @code{/}.
13836 This makes it possible to test @code{expr length + "$x"} or
13837 @code{expr + "$x" : '.*/\(.\)'} and have it do the right thing even if
13838 the value of @var{$x} happens to be (for example) @code{/} or @code{index}.
13839 This operator is a GNU extension. Portable shell scripts should use
13840 @code{@w{" $token"} : @w{' \(.*\)'}} instead of @code{+ "$token"}.
13844 To make @command{expr} interpret keywords as strings, you must use the
13845 @code{quote} operator.
13848 @node Numeric expressions
13849 @subsection Numeric expressions
13851 @cindex numeric expressions
13852 @cindex expressions, numeric
13854 @command{expr} supports the usual numeric operators, in order of increasing
13855 precedence. These numeric operators have lower precedence than the
13856 string operators described in the previous section, and higher precedence
13857 than the connectives (next section).
13865 @cindex subtraction
13866 Addition and subtraction. Both arguments are converted to integers;
13867 an error occurs if this cannot be done.
13873 @cindex multiplication
13876 Multiplication, division, remainder. Both arguments are converted to
13877 integers; an error occurs if this cannot be done.
13882 @node Relations for expr
13883 @subsection Relations for @command{expr}
13885 @cindex connectives, logical
13886 @cindex logical connectives
13887 @cindex relations, numeric or string
13889 @command{expr} supports the usual logical connectives and relations. These
13890 have lower precedence than the string and numeric operators
13891 (previous sections). Here is the list, lowest-precedence operator first.
13897 @cindex logical or operator
13898 @cindex or operator
13899 Returns its first argument if that is neither null nor zero, otherwise
13900 its second argument if it is neither null nor zero, otherwise 0. It
13901 does not evaluate its second argument if its first argument is neither
13906 @cindex logical and operator
13907 @cindex and operator
13908 Return its first argument if neither argument is null or zero, otherwise
13909 0. It does not evaluate its second argument if its first argument is
13912 @item < <= = == != >= >
13919 @cindex comparison operators
13921 Compare the arguments and return 1 if the relation is true, 0 otherwise.
13922 @code{==} is a synonym for @code{=}. @command{expr} first tries to convert
13923 both arguments to integers and do a numeric comparison; if either
13924 conversion fails, it does a lexicographic comparison using the character
13925 collating sequence specified by the @env{LC_COLLATE} locale.
13930 @node Examples of expr
13931 @subsection Examples of using @command{expr}
13933 @cindex examples of @command{expr}
13934 Here are a few examples, including quoting for shell metacharacters.
13936 To add 1 to the shell variable @code{foo}, in Bourne-compatible shells:
13939 foo=$(expr $foo + 1)
13942 To print the non-directory part of the file name stored in
13943 @code{$fname}, which need not contain a @code{/}:
13946 expr $fname : '.*/\(.*\)' '|' $fname
13949 An example showing that @code{\+} is an operator:
13957 expr abc : 'a\(.\)c'
13959 expr index abcdef cz
13962 @error{} expr: syntax error
13963 expr index + index a
13969 @chapter Redirection
13971 @cindex redirection
13972 @cindex commands for redirection
13974 Unix shells commonly provide several forms of @dfn{redirection}---ways
13975 to change the input source or output destination of a command. But one
13976 useful redirection is performed by a separate command, not by the shell;
13977 it's described here.
13980 * tee invocation:: Redirect output to multiple files or processes.
13984 @node tee invocation
13985 @section @command{tee}: Redirect output to multiple files or processes
13988 @cindex pipe fitting
13989 @cindex destinations, multiple output
13990 @cindex read from standard input and write to standard output and files
13992 The @command{tee} command copies standard input to standard output and also
13993 to any files given as arguments. This is useful when you want not only
13994 to send some data down a pipe, but also to save a copy. Synopsis:
13997 tee [@var{option}]@dots{} [@var{file}]@dots{}
14000 If a file being written to does not already exist, it is created. If a
14001 file being written to already exists, the data it previously contained
14002 is overwritten unless the @option{-a} option is used.
14004 In previous versions of GNU Coreutils (v5.3.0 -- v8.23),
14005 a @var{file} of @samp{-}
14006 caused @command{tee} to send another copy of input to standard output.
14007 However, as the interleaved output was not very useful, @command{tee} now
14008 conforms to POSIX and treats @samp{-} as a file name.
14010 The program accepts the following options. Also see @ref{Common options}.
14017 Append standard input to the given files rather than overwriting
14021 @itemx --ignore-interrupts
14023 @opindex --ignore-interrupts
14024 Ignore interrupt signals.
14027 @itemx --output-error[=@var{mode}]
14029 @opindex --output-error
14030 Adjust the behavior with errors on the outputs,
14031 with the long form option supporting selection
14032 between the following @var{mode}s:
14036 Warn on error opening or writing any output, including pipes.
14037 Writing is continued to still open files/pipes.
14038 Exit status indicates failure if any output has an error.
14041 This is the default @var{mode} when not specified,
14042 or when the short form @option{-p} is used.
14043 Warn on error opening or writing any output, except pipes.
14044 Writing is continued to still open files/pipes.
14045 Exit status indicates failure if any non pipe output had an error.
14048 Exit on error opening or writing any output, including pipes.
14051 Exit on error opening or writing any output, except pipes.
14056 The @command{tee} command is useful when you happen to be transferring a large
14057 amount of data and also want to summarize that data without reading
14058 it a second time. For example, when you are downloading a DVD image,
14059 you often want to verify its signature or checksum right away.
14060 The inefficient way to do it is simply:
14063 wget https://example.com/some.iso && sha1sum some.iso
14066 One problem with the above is that it makes you wait for the
14067 download to complete before starting the time-consuming SHA1 computation.
14068 Perhaps even more importantly, the above requires reading
14069 the DVD image a second time (the first was from the network).
14071 The efficient way to do it is to interleave the download
14072 and SHA1 computation. Then, you'll get the checksum for
14073 free, because the entire process parallelizes so well:
14076 # slightly contrived, to demonstrate process substitution
14077 wget -O - https://example.com/dvd.iso \
14078 | tee >(sha1sum > dvd.sha1) > dvd.iso
14081 That makes @command{tee} write not just to the expected output file,
14082 but also to a pipe running @command{sha1sum} and saving the final
14083 checksum in a file named @file{dvd.sha1}.
14085 Note, however, that this example relies on a feature of modern shells
14086 called @dfn{process substitution}
14087 (the @samp{>(command)} syntax, above;
14088 @xref{Process Substitution,,Process Substitution, bash,
14089 The Bash Reference Manual}.),
14090 so it works with @command{zsh}, @command{bash}, and @command{ksh},
14091 but not with @command{/bin/sh}. So if you write code like this
14092 in a shell script, be sure to start the script with @samp{#!/bin/bash}.
14094 Note also that if any of the process substitutions (or piped standard output)
14095 might exit early without consuming all the data, the @option{-p} option
14096 is needed to allow @command{tee} to continue to process the input
14097 to any remaining outputs.
14099 Since the above example writes to one file and one process,
14100 a more conventional and portable use of @command{tee} is even better:
14103 wget -O - https://example.com/dvd.iso \
14104 | tee dvd.iso | sha1sum > dvd.sha1
14107 You can extend this example to make @command{tee} write to two processes,
14108 computing MD5 and SHA1 checksums in parallel. In this case,
14109 process substitution is required:
14112 wget -O - https://example.com/dvd.iso \
14113 | tee >(sha1sum > dvd.sha1) \
14114 >(md5sum > dvd.md5) \
14118 This technique is also useful when you want to make a @emph{compressed}
14119 copy of the contents of a pipe.
14120 Consider a tool to graphically summarize file system usage data from
14122 For a large hierarchy, @samp{du -ak} can run for a long time,
14123 and can easily produce terabytes of data, so you won't want to
14124 rerun the command unnecessarily. Nor will you want to save
14125 the uncompressed output.
14127 Doing it the inefficient way, you can't even start the GUI
14128 until after you've compressed all of the @command{du} output:
14131 du -ak | gzip -9 > /tmp/du.gz
14132 gzip -d /tmp/du.gz | checkspace -a
14135 With @command{tee} and process substitution, you start the GUI
14136 right away and eliminate the decompression completely:
14139 du -ak | tee >(gzip -9 > /tmp/du.gz) | checkspace -a
14142 Finally, if you regularly create more than one type of
14143 compressed tarball at once, for example when @code{make dist} creates
14144 both @command{gzip}-compressed and @command{bzip2}-compressed tarballs,
14145 there may be a better way.
14146 Typical @command{automake}-generated @file{Makefile} rules create
14147 the two compressed tar archives with commands in sequence, like this
14148 (slightly simplified):
14151 tardir=your-pkg-M.N
14152 tar chof - "$tardir" | gzip -9 -c > your-pkg-M.N.tar.gz
14153 tar chof - "$tardir" | bzip2 -9 -c > your-pkg-M.N.tar.bz2
14156 However, if the hierarchy you are archiving and compressing is larger
14157 than a couple megabytes, and especially if you are using a multi-processor
14158 system with plenty of memory, then you can do much better by reading the
14159 directory contents only once and running the compression programs in parallel:
14162 tardir=your-pkg-M.N
14163 tar chof - "$tardir" \
14164 | tee >(gzip -9 -c > your-pkg-M.N.tar.gz) \
14165 | bzip2 -9 -c > your-pkg-M.N.tar.bz2
14168 If you want to further process the output from process substitutions,
14169 and those processes write atomically (i.e., write less than the system's
14170 PIPE_BUF size at a time), that's possible with a construct like:
14173 tardir=your-pkg-M.N
14174 tar chof - "$tardir" \
14175 | tee >(md5sum --tag) > >(sha256sum --tag) \
14176 | sort | gpg --clearsign > your-pkg-M.N.tar.sig
14182 @node File name manipulation
14183 @chapter File name manipulation
14185 @cindex file name manipulation
14186 @cindex manipulation of file names
14187 @cindex commands for file name manipulation
14189 This section describes commands that manipulate file names.
14192 * basename invocation:: Strip directory and suffix from a file name.
14193 * dirname invocation:: Strip last file name component.
14194 * pathchk invocation:: Check file name validity and portability.
14195 * mktemp invocation:: Create temporary file or directory.
14196 * realpath invocation:: Print resolved file names.
14200 @node basename invocation
14201 @section @command{basename}: Strip directory and suffix from a file name
14204 @cindex strip directory and suffix from file names
14205 @cindex directory, stripping from file names
14206 @cindex suffix, stripping from file names
14207 @cindex file names, stripping directory and suffix
14208 @cindex leading directory components, stripping
14210 @command{basename} removes any leading directory components from
14211 @var{name}. Synopsis:
14214 basename @var{name} [@var{suffix}]
14215 basename @var{option}@dots{} @var{name}@dots{}
14218 If @var{suffix} is specified and is identical to the end of @var{name},
14219 it is removed from @var{name} as well. Note that since trailing slashes
14220 are removed prior to suffix matching, @var{suffix} will do nothing if it
14221 contains slashes. @command{basename} prints the result on standard
14224 @c This test is used both here and in the section on dirname.
14225 @macro basenameAndDirname
14226 Together, @command{basename} and @command{dirname} are designed such
14227 that if @samp{ls "$name"} succeeds, then the command sequence @samp{cd
14228 "$(dirname "$name")"; ls "$(basename "$name")"} will, too. This works
14229 for everything except file names containing a trailing newline.
14231 @basenameAndDirname
14233 POSIX allows the implementation to define the results if
14234 @var{name} is empty or @samp{//}. In the former case, GNU
14235 @command{basename} returns the empty string. In the latter case, the
14236 result is @samp{//} on platforms where @var{//} is distinct from
14237 @var{/}, and @samp{/} on platforms where there is no difference.
14239 The program accepts the following options. Also see @ref{Common options}.
14240 Options must precede operands.
14247 @opindex --multiple
14248 Support more than one argument. Treat every argument as a @var{name}.
14249 With this, an optional @var{suffix} must be specified using the
14250 @option{-s} option.
14252 @item -s @var{suffix}
14253 @itemx --suffix=@var{suffix}
14256 Remove a trailing @var{suffix}.
14257 This option implies the @option{-a} option.
14269 basename /usr/bin/sort
14272 basename include/stdio.h .h
14275 basename -s .h include/stdio.h
14277 # Output "stdio" followed by "stdlib"
14278 basename -a -s .h include/stdio.h include/stdlib.h
14282 @node dirname invocation
14283 @section @command{dirname}: Strip last file name component
14286 @cindex directory components, printing
14287 @cindex stripping non-directory suffix
14288 @cindex non-directory suffix, stripping
14290 @command{dirname} prints all but the final slash-delimited component
14291 of each @var{name}. Slashes on either side of the final component are
14292 also removed. If the string contains no slash, @command{dirname}
14293 prints @samp{.} (meaning the current directory). Synopsis:
14296 dirname [@var{option}] @var{name}@dots{}
14299 @var{name} need not be a file name, but if it is, this operation
14300 effectively lists the directory that contains the final component,
14301 including the case when the final component is itself a directory.
14303 @basenameAndDirname
14305 POSIX allows the implementation to define the results if
14306 @var{name} is @samp{//}. With GNU @command{dirname}, the
14307 result is @samp{//} on platforms where @var{//} is distinct from
14308 @var{/}, and @samp{/} on platforms where there is no difference.
14310 The program accepts the following option. Also see @ref{Common options}.
14323 # Output "/usr/bin".
14324 dirname /usr/bin/sort
14325 dirname /usr/bin//.//
14327 # Output "dir1" followed by "dir2"
14328 dirname dir1/str dir2/str
14335 @node pathchk invocation
14336 @section @command{pathchk}: Check file name validity and portability
14339 @cindex file names, checking validity and portability
14340 @cindex valid file names, checking for
14341 @cindex portable file names, checking for
14343 @command{pathchk} checks validity and portability of file names. Synopsis:
14346 pathchk [@var{option}]@dots{} @var{name}@dots{}
14349 For each @var{name}, @command{pathchk} prints an error message if any of
14350 these conditions is true:
14354 One of the existing directories in @var{name} does not have search
14355 (execute) permission,
14357 The length of @var{name} is larger than the maximum supported by the
14360 The length of one component of @var{name} is longer than
14361 its file system's maximum.
14364 A nonexistent @var{name} is not an error, so long as a file with that
14365 name could be created under the above conditions.
14367 The program accepts the following options. Also see @ref{Common options}.
14368 Options must precede operands.
14374 Instead of performing checks based on the underlying file system,
14375 print an error message if any of these conditions is true:
14379 A file name is empty.
14382 A file name contains a character outside the POSIX portable file
14383 name character set, namely, the ASCII letters and digits, @samp{.},
14384 @samp{_}, @samp{-}, and @samp{/}.
14387 The length of a file name or one of its components exceeds the
14388 POSIX minimum limits for portability.
14393 Print an error message if a file name is empty, or if it contains a component
14394 that begins with @samp{-}.
14396 @item --portability
14397 @opindex --portability
14398 Print an error message if a file name is not portable to all POSIX
14399 hosts. This option is equivalent to @samp{-p -P}.
14403 @cindex exit status of @command{pathchk}
14407 0 if all specified file names passed all checks,
14411 @node mktemp invocation
14412 @section @command{mktemp}: Create temporary file or directory
14415 @cindex file names, creating temporary
14416 @cindex directory, creating temporary
14417 @cindex temporary files and directories
14419 @command{mktemp} manages the creation of temporary files and
14420 directories. Synopsis:
14423 mktemp [@var{option}]@dots{} [@var{template}]
14426 Safely create a temporary file or directory based on @var{template},
14427 and print its name. If given, @var{template} must include at least
14428 three consecutive @samp{X}s in the last component. If omitted, the template
14429 @samp{tmp.XXXXXXXXXX} is used, and option @option{--tmpdir} is
14430 implied. The final run of @samp{X}s in the @var{template} will be replaced
14431 by alpha-numeric characters; thus, on a case-sensitive file system,
14432 and with a @var{template} including a run of @var{n} instances of @samp{X},
14433 there are @samp{62**@var{n}} potential file names.
14435 Older scripts used to create temporary files by simply joining the
14436 name of the program with the process id (@samp{$$}) as a suffix.
14437 However, that naming scheme is easily predictable, and suffers from a
14438 race condition where the attacker can create an appropriately named
14439 symbolic link, such that when the script then opens a handle to what
14440 it thought was an unused file, it is instead modifying an existing
14441 file. Using the same scheme to create a directory is slightly safer,
14442 since the @command{mkdir} will fail if the target already exists, but
14443 it is still inferior because it allows for denial of service attacks.
14444 Therefore, modern scripts should use the @command{mktemp} command to
14445 guarantee that the generated name will be unpredictable, and that
14446 knowledge of the temporary file name implies that the file was created
14447 by the current script and cannot be modified by other users.
14449 When creating a file, the resulting file has read and write
14450 permissions for the current user, but no permissions for the group or
14451 others; these permissions are reduced if the current umask is more
14454 Here are some examples (although note that if you repeat them, you
14455 will most likely get different file names):
14460 Create a temporary file in the current directory.
14467 Create a temporary file with a known suffix.
14469 $ mktemp --suffix=.txt file-XXXX
14471 $ mktemp file-XXXX-XXXX.txt
14476 Create a secure fifo relative to the user's choice of @env{TMPDIR},
14477 but falling back to the current directory rather than @file{/tmp}.
14478 Note that @command{mktemp} does not create fifos, but can create a
14479 secure directory in which the fifo can live. Exit the shell if the
14480 directory or fifo could not be created.
14482 $ dir=$(mktemp -p "$@{TMPDIR:-.@}" -d dir-XXXX) || exit 1
14484 $ mkfifo "$fifo" || @{ rmdir "$dir"; exit 1; @}
14488 Create and use a temporary file if possible, but ignore failure. The
14489 file will reside in the directory named by @env{TMPDIR}, if specified,
14490 or else in @file{/tmp}.
14492 $ file=$(mktemp -q) && @{
14493 > # Safe to use $file only within this block. Use quotes,
14494 > # since $TMPDIR, and thus $file, may contain whitespace.
14495 > echo ... > "$file"
14501 Act as a semi-random character generator (it is not fully random,
14502 since it is impacted by the contents of the current directory). To
14503 avoid security holes, do not use the resulting names to create a file.
14513 The program accepts the following options. Also see @ref{Common options}.
14520 @opindex --directory
14521 Create a directory rather than a file. The directory will have read,
14522 write, and search permissions for the current user, but no permissions
14523 for the group or others; these permissions are reduced if the current
14524 umask is more restrictive.
14530 Suppress diagnostics about failure to create a file or directory. The
14531 exit status will still reflect whether a file was created.
14537 Generate a temporary name that does not name an existing file, without
14538 changing the file system contents. Using the output of this command
14539 to create a new file is inherently unsafe, as there is a window of
14540 time between generating the name and using it where another process
14541 can create an object by the same name.
14544 @itemx --tmpdir[=@var{dir}]
14547 Treat @var{template} relative to the directory @var{dir}. If
14548 @var{dir} is not specified (only possible with the long option
14549 @option{--tmpdir}) or is the empty string, use the value of
14550 @env{TMPDIR} if available, otherwise use @samp{/tmp}. If this is
14551 specified, @var{template} must not be absolute. However,
14552 @var{template} can still contain slashes, although intermediate
14553 directories must already exist.
14555 @item --suffix=@var{suffix}
14557 Append @var{suffix} to the @var{template}. @var{suffix} must not
14558 contain slash. If @option{--suffix} is specified, @var{template} must
14559 end in @samp{X}; if it is not specified, then an appropriate
14560 @option{--suffix} is inferred by finding the last @samp{X} in
14561 @var{template}. This option exists for use with the default
14562 @var{template} and for the creation of a @var{suffix} that starts with
14567 Treat @var{template} as a single file relative to the value of
14568 @env{TMPDIR} if available, or to the directory specified by
14569 @option{-p}, otherwise to @samp{/tmp}. @var{template} must not
14570 contain slashes. This option is deprecated; the use of @option{-p}
14571 without @option{-t} offers better defaults (by favoring the command
14572 line over @env{TMPDIR}) and more flexibility (by allowing intermediate
14577 @cindex exit status of @command{mktemp}
14581 0 if the file was created,
14586 @node realpath invocation
14587 @section @command{realpath}: Print the resolved file name.
14590 @cindex file names, canonicalization
14591 @cindex symlinks, resolution
14592 @cindex canonical file name
14593 @cindex canonicalize a file name
14597 @command{realpath} expands all symbolic links and resolves references to
14598 @samp{/./}, @samp{/../} and extra @samp{/} characters. By default,
14599 all but the last component of the specified files must exist. Synopsis:
14602 realpath [@var{option}]@dots{} @var{file}@dots{}
14605 The file name canonicalization functionality overlaps with that of the
14606 @command{readlink} command. This is the preferred command for
14607 canonicalization as it's a more suitable and standard name. In addition
14608 this command supports relative file name processing functionality.
14610 The program accepts the following options. Also see @ref{Common options}.
14615 @itemx --canonicalize-existing
14617 @opindex --canonicalize-existing
14618 Ensure that all components of the specified file names exist.
14619 If any component is missing or unavailable, @command{realpath} will output
14620 a diagnostic unless the @option{-q} option is specified, and exit with a
14621 nonzero exit code. A trailing slash requires that the name resolve to a
14625 @itemx --canonicalize-missing
14627 @opindex --canonicalize-missing
14628 If any component of a specified file name is missing or unavailable,
14629 treat it as a directory.
14635 Symbolic links are resolved in the specified file names,
14636 but they are resolved after any subsequent @samp{..} components are processed.
14641 @opindex --physical
14642 Symbolic links are resolved in the specified file names,
14643 and they are resolved before any subsequent @samp{..} components are processed.
14644 This is the default mode of operation.
14650 Suppress diagnostic messages for specified file names.
14652 @item --relative-to=@var{dir}
14653 @opindex --relative-to
14655 Print the resolved file names relative to the specified directory.
14656 Note this option honors the @option{-m} and @option{-e} options
14657 pertaining to file existence.
14659 @item --relative-base=@var{dir}
14660 @opindex --relative-base
14661 Print the resolved file names as relative @emph{if} the files
14662 are descendants of @var{dir}.
14663 Otherwise, print the resolved file names as absolute.
14664 Note this option honors the @option{-m} and @option{-e} options
14665 pertaining to file existence.
14666 For details about combining @option{--relative-to} and @option{--relative-base},
14667 @pxref{Realpath usage examples}.
14671 @itemx --no-symlinks
14674 @opindex --no-symlinks
14675 Do not resolve symbolic links. Only resolve references to
14676 @samp{/./}, @samp{/../} and remove extra @samp{/} characters.
14677 When combined with the @option{-m} option, realpath operates
14678 only on the file name, and does not touch any actual file.
14684 @cindex exit status of @command{realpath}
14688 0 if all file names were printed without issue.
14693 * Realpath usage examples:: Realpath usage examples.
14697 @node Realpath usage examples
14698 @subsection Realpath usage examples
14700 @opindex --relative-to
14701 @opindex --relative-base
14703 By default, @command{realpath} prints the absolute file name of given files
14704 (symlinks are resolved, @file{words} is resolved to @file{american-english}):
14709 realpath /usr/bin/sort /tmp/foo /usr/share/dict/words 1.txt
14710 @result{} /usr/bin/sort
14712 @result{} /usr/share/dict/american-english
14713 @result{} /home/user/1.txt
14717 With @option{--relative-to}, file names are printed relative to
14718 the given directory:
14722 realpath --relative-to=/usr/bin \
14723 /usr/bin/sort /tmp/foo /usr/share/dict/words 1.txt
14725 @result{} ../../tmp/foo
14726 @result{} ../share/dict/american-english
14727 @result{} ../../home/user/1.txt
14731 With @option{--relative-base}, relative file names are printed @emph{if}
14732 the resolved file name is below the given base directory. For files outside the
14733 base directory absolute file names are printed:
14737 realpath --relative-base=/usr \
14738 /usr/bin/sort /tmp/foo /usr/share/dict/words 1.txt
14741 @result{} share/dict/american-english
14742 @result{} /home/user/1.txt
14746 When both @option{--relative-to=DIR1} and @option{--relative-base=DIR2}
14747 are used, file names are printed relative to @var{dir1} @emph{if} they are
14748 located below @var{dir2}. If the files are not below @var{dir2}, they are
14749 printed as absolute file names:
14753 realpath --relative-to=/usr/bin --relative-base=/usr \
14754 /usr/bin/sort /tmp/foo /usr/share/dict/words 1.txt
14757 @result{} ../share/dict/american-english
14758 @result{} /home/user/1.txt
14762 When both @option{--relative-to=DIR1} and @option{--relative-base=DIR2}
14763 are used, @var{dir1} @emph{must} be a subdirectory of @var{dir2}. Otherwise,
14764 @command{realpath} prints absolutes file names.
14767 @node Working context
14768 @chapter Working context
14770 @cindex working context
14771 @cindex commands for printing the working context
14773 This section describes commands that display or alter the context in
14774 which you are working: the current directory, the terminal settings, and
14775 so forth. See also the user-related commands in the next section.
14778 * pwd invocation:: Print working directory.
14779 * stty invocation:: Print or change terminal characteristics.
14780 * printenv invocation:: Print environment variables.
14781 * tty invocation:: Print file name of terminal on standard input.
14785 @node pwd invocation
14786 @section @command{pwd}: Print working directory
14789 @cindex print name of current directory
14790 @cindex current working directory, printing
14791 @cindex working directory, printing
14794 @command{pwd} prints the name of the current directory. Synopsis:
14797 pwd [@var{option}]@dots{}
14800 The program accepts the following options. Also see @ref{Common options}.
14807 If the contents of the environment variable @env{PWD} provide an
14808 absolute name of the current directory with no @samp{.} or @samp{..}
14809 components, but possibly with symbolic links, then output those
14810 contents. Otherwise, fall back to default @option{-P} handling.
14815 @opindex --physical
14816 Print a fully resolved name for the current directory. That is, all
14817 components of the printed name will be actual directory names---none
14818 will be symbolic links.
14821 @cindex symbolic links and @command{pwd}
14822 If @option{-L} and @option{-P} are both given, the last one takes
14823 precedence. If neither option is given, then this implementation uses
14824 @option{-P} as the default unless the @env{POSIXLY_CORRECT}
14825 environment variable is set.
14827 @mayConflictWithShellBuiltIn{pwd}
14832 @node stty invocation
14833 @section @command{stty}: Print or change terminal characteristics
14836 @cindex change or print terminal settings
14837 @cindex terminal settings
14838 @cindex line settings of terminal
14840 @command{stty} prints or changes terminal characteristics, such as baud rate.
14844 stty [@var{option}] [@var{setting}]@dots{}
14845 stty [@var{option}]
14848 If given no line settings, @command{stty} prints the baud rate, line
14849 discipline number (on systems that support it), and line settings
14850 that have been changed from the values set by @samp{stty sane}.
14851 By default, mode reading and setting are performed on the tty line
14852 connected to standard input, although this can be modified by the
14853 @option{--file} option.
14855 @command{stty} accepts many non-option arguments that change aspects of
14856 the terminal line operation, as described below.
14858 The program accepts the following options. Also see @ref{Common options}.
14865 Print all current settings in human-readable form. This option may not
14866 be used in combination with any line settings.
14868 @item -F @var{device}
14869 @itemx --file=@var{device}
14872 Set the line opened by the file name specified in @var{device} instead of
14873 the tty line connected to standard input. This option is necessary
14874 because opening a POSIX tty requires use of the
14875 @code{O_NONDELAY} flag to prevent a POSIX tty from blocking
14876 until the carrier detect line is high if
14877 the @code{clocal} flag is not set. Hence, it is not always possible
14878 to allow the shell to open the device in the traditional manner.
14884 @cindex machine-readable @command{stty} output
14885 Print all current settings in a form that can be used as an argument to
14886 another @command{stty} command to restore the current settings. This option
14887 may not be used in combination with any line settings.
14891 Many settings can be turned off by preceding them with a @samp{-}.
14892 Such arguments are marked below with ``May be negated'' in their
14893 description. The descriptions themselves refer to the positive
14894 case, that is, when @emph{not} negated (unless stated otherwise,
14897 Some settings are not available on all POSIX systems, since they use
14898 extensions. Such arguments are marked below with
14899 ``Non-POSIX'' in their description. On non-POSIX
14900 systems, those or other settings also may not
14901 be available, but it's not feasible to document all the variations: just
14904 @command{stty} is installed only on platforms with the POSIX terminal
14905 interface, so portable scripts should not rely on its existence on
14906 non-POSIX platforms.
14911 * Control:: Control settings
14912 * Input:: Input settings
14913 * Output:: Output settings
14914 * Local:: Local settings
14915 * Combination:: Combination settings
14916 * Characters:: Special characters
14917 * Special:: Special settings
14922 @subsection Control settings
14924 @cindex control settings
14930 @cindex two-way parity
14931 Generate parity bit in output and expect parity bit in input.
14937 @cindex even parity
14938 Set odd parity (even if negated). May be negated.
14942 @cindex constant parity
14943 @cindex stick parity
14944 @cindex mark parity
14945 @cindex space parity
14946 Use "stick" (mark/space) parity. If parodd is set, the parity bit is
14947 always 1; if parodd is not set, the parity bit is always zero.
14948 Non-POSIX@. May be negated.
14955 @cindex character size
14956 @cindex eight-bit characters
14957 Set character size to 5, 6, 7, or 8 bits.
14962 Send a hangup signal when the last process closes the tty. May be
14968 Use two stop bits per character (one if negated). May be negated.
14972 Allow input to be received. May be negated.
14976 @cindex modem control
14977 Disable modem control signals. May be negated.
14981 @cindex hardware flow control
14982 @cindex flow control, hardware
14983 @cindex RTS/CTS flow control
14984 Enable RTS/CTS flow control. Non-POSIX@. May be negated.
14988 @cindex hardware flow control
14989 @cindex flow control, hardware
14990 @cindex DTR/DSR flow control
14991 Enable DTR/DSR flow control. Non-POSIX@. May be negated.
14996 @subsection Input settings
14998 @cindex input settings
14999 These settings control operations on data received from the terminal.
15004 @cindex breaks, ignoring
15005 Ignore break characters. May be negated.
15009 @cindex breaks, cause interrupts
15010 Make breaks cause an interrupt signal. May be negated.
15014 @cindex parity, ignoring
15015 Ignore characters with parity errors. May be negated.
15019 @cindex parity errors, marking
15020 Mark parity errors (with a 255-0-character sequence). May be negated.
15024 Enable input parity checking. May be negated.
15028 @cindex eight-bit input
15029 Clear high (8th) bit of input characters. May be negated.
15033 @cindex newline, translating to return
15034 Translate newline to carriage return. May be negated.
15038 @cindex return, ignoring
15039 Ignore carriage return. May be negated.
15043 @cindex return, translating to newline
15044 Translate carriage return to newline. May be negated.
15048 @cindex input encoding, UTF-8
15049 Assume input characters are UTF-8 encoded. May be negated.
15053 @kindex C-s/C-q flow control
15054 @cindex XON/XOFF flow control
15055 Enable XON/XOFF flow control (that is, @kbd{Ctrl-S}/@kbd{Ctrl-Q}). May
15062 @cindex software flow control
15063 @cindex flow control, software
15064 Enable sending of @code{stop} character when the system input buffer
15065 is almost full, and @code{start} character when it becomes almost
15066 empty again. May be negated.
15070 @cindex uppercase, translating to lowercase
15071 Translate uppercase characters to lowercase. Non-POSIX@. May be
15072 negated. Note ilcuc is not implemented, as one would not be able to issue
15073 almost any (lowercase) Unix command, after invoking it.
15077 Allow any character to restart output (only the start character
15078 if negated). Non-POSIX@. May be negated.
15082 @cindex beeping at input buffer full
15083 Enable beeping and not flushing input buffer if a character arrives
15084 when the input buffer is full. Non-POSIX@. May be negated.
15089 @subsection Output settings
15091 @cindex output settings
15092 These settings control operations on data sent to the terminal.
15097 Postprocess output. May be negated.
15101 @cindex lowercase, translating to output
15102 Translate lowercase characters to uppercase. Non-POSIX@. May be
15103 negated. (Note ouclc is not currently implemented.)
15107 @cindex return, translating to newline
15108 Translate carriage return to newline. Non-POSIX@. May be negated.
15112 @cindex newline, translating to crlf
15113 Translate newline to carriage return-newline. Non-POSIX@. May be
15118 Do not print carriage returns in the first column. Non-POSIX@.
15123 Newline performs a carriage return. Non-POSIX@. May be negated.
15127 @cindex pad instead of timing for delaying
15128 Use fill (padding) characters instead of timing for delays.
15134 @cindex pad character
15135 Use ASCII DEL characters for fill instead of
15136 ASCII NUL characters. Non-POSIX@.
15142 Newline delay style. Non-POSIX.
15149 Carriage return delay style. Non-POSIX.
15155 @opindex tab@var{n}
15156 Horizontal tab delay style. Non-POSIX.
15161 Backspace delay style. Non-POSIX.
15166 Vertical tab delay style. Non-POSIX.
15171 Form feed delay style. Non-POSIX.
15176 @subsection Local settings
15178 @cindex local settings
15183 Enable @code{interrupt}, @code{quit}, and @code{suspend} special
15184 characters. May be negated.
15188 Enable @code{erase}, @code{kill}, @code{werase}, and @code{rprnt}
15189 special characters. May be negated.
15193 Enable non-POSIX special characters. May be negated.
15197 Echo input characters. May be negated.
15203 Echo @code{erase} characters as backspace-space-backspace. May be
15208 @cindex newline echoing after @code{kill}
15209 Echo a newline after a @code{kill} character. May be negated.
15213 @cindex newline, echoing
15214 Echo newline even if not echoing other characters. May be negated.
15218 @cindex flushing, disabling
15219 Disable flushing after @code{interrupt} and @code{quit} special
15220 characters. May be negated.
15224 @cindex case translation
15225 Enable input and output of uppercase characters by preceding their
15226 lowercase equivalents with @samp{\}, when @code{icanon} is set.
15227 Non-POSIX@. May be negated.
15231 @cindex background jobs, stopping at terminal write
15232 Stop background jobs that try to write to the terminal. Non-POSIX@.
15239 Echo erased characters backward, between @samp{\} and @samp{/}.
15240 Non-POSIX@. May be negated.
15246 @cindex control characters, using @samp{^@var{c}}
15247 @cindex hat notation for control characters
15248 Echo control characters in hat notation (@samp{^@var{c}}) instead
15249 of literally. Non-POSIX@. May be negated.
15255 Echo the @code{kill} special character by erasing each character on
15256 the line as indicated by the @code{echoprt} and @code{echoe} settings,
15257 instead of by the @code{echoctl} and @code{echok} settings.
15263 Enable @samp{LINEMODE}, which is used to avoid echoing
15264 each character over high latency links. See also
15265 @uref{https://tools.ietf.org/search/rfc1116, Internet RFC 1116}.
15272 Note this setting is currently ignored on GNU/Linux systems.
15279 @subsection Combination settings
15281 @cindex combination settings
15282 Combination settings:
15289 Same as @code{parenb -parodd cs7}. May be negated. If negated, same
15290 as @code{-parenb cs8}.
15294 Same as @code{parenb parodd cs7}. May be negated. If negated, same
15295 as @code{-parenb cs8}.
15299 Same as @code{-icrnl -onlcr}. May be negated. If negated, same as
15300 @code{icrnl -inlcr -igncr onlcr -ocrnl -onlret}.
15304 Reset the @code{erase} and @code{kill} special characters to their default
15311 @c This is too long to write inline.
15313 cread -ignbrk brkint -inlcr -igncr icrnl
15314 icanon iexten echo echoe echok -echonl -noflsh
15315 -ixoff -iutf8 -iuclc -ixany imaxbel -xcase -olcuc -ocrnl
15316 opost -ofill onlcr -onocr -onlret nl0 cr0 tab0 bs0 vt0 ff0
15317 isig -tostop -ofdel -echoprt echoctl echoke -extproc
15321 and also sets all special characters to their default values.
15325 Same as @code{brkint ignpar istrip icrnl ixon opost isig icanon}, plus
15326 sets the @code{eof} and @code{eol} characters to their default values
15327 if they are the same as the @code{min} and @code{time} characters.
15328 May be negated. If negated, same as @code{raw}.
15335 -ignbrk -brkint -ignpar -parmrk -inpck -istrip
15336 -inlcr -igncr -icrnl -ixon -ixoff -icanon -opost
15337 -isig -iuclc -ixany -imaxbel -xcase min 1 time 0
15341 May be negated. If negated, same as @code{cooked}.
15345 Same as @option{-icanon}. May be negated. If negated, same as
15350 @cindex eight-bit characters
15351 Same as @code{-parenb -istrip cs8}. May be negated. If negated,
15352 same as @code{parenb istrip cs7}.
15356 Same as @option{-parenb -istrip -opost cs8}. May be negated.
15357 If negated, same as @code{parenb istrip opost cs7}.
15361 Same as @option{-ixany}. Non-POSIX@. May be negated.
15365 Same as @code{tab0}. Non-POSIX@. May be negated. If negated, same
15372 Same as @code{xcase iuclc olcuc}. Non-POSIX@. May be negated.
15373 (Used for terminals with uppercase characters only.)
15377 Same as @code{echoe echoctl echoke}.
15381 Same as @code{echoe echoctl echoke -ixany intr ^C erase ^? kill C-u}.
15386 @subsection Special characters
15388 @cindex special characters
15389 @cindex characters, special
15391 The special characters' default values vary from system to system.
15392 They are set with the syntax @samp{name value}, where the names are
15393 listed below and the value can be given either literally, in hat
15394 notation (@samp{^@var{c}}), or as an integer which may start with
15395 @samp{0x} to indicate hexadecimal, @samp{0} to indicate octal, or
15396 any other digit to indicate decimal.
15398 @cindex disabling special characters
15399 @kindex u@r{, and disabling special characters}
15400 For GNU stty, giving a value of @code{^-} or @code{undef} disables that
15401 special character. (This is incompatible with Ultrix @command{stty},
15402 which uses a value of @samp{u} to disable a special character. GNU
15403 @command{stty} treats a value @samp{u} like any other, namely to set that
15404 special character to @key{U}.)
15410 Send an interrupt signal.
15414 Send a quit signal.
15418 Erase the last character typed.
15422 Erase the current line.
15426 Send an end of file (terminate the input).
15434 Alternate character to end the line. Non-POSIX.
15439 Alternate character to toggle discarding of output. Non-POSIX.
15443 Switch to a different shell layer. Non-POSIX.
15447 Send an info signal. Not currently supported on GNU/Linux. Non-POSIX.
15451 Restart the output after stopping it.
15459 Send a terminal stop signal.
15463 Send a terminal stop signal after flushing the input. Non-POSIX.
15467 Redraw the current line. Non-POSIX.
15471 Erase the last word typed. Non-POSIX.
15475 Enter the next character typed literally, even if it is a special
15476 character. Non-POSIX.
15481 @subsection Special settings
15483 @cindex special settings
15488 Set the minimum number of characters that will satisfy a read until
15489 the time value has expired, when @option{-icanon} is set.
15493 Set the number of tenths of a second before reads time out if the minimum
15494 number of characters have not been read, when @option{-icanon} is set.
15496 @item ispeed @var{n}
15498 Set the input speed to @var{n}.
15500 @item ospeed @var{n}
15502 Set the output speed to @var{n}.
15506 Tell the tty kernel driver that the terminal has @var{n} rows.
15510 @itemx columns @var{n}
15513 Tell the kernel that the terminal has @var{n} columns. Non-POSIX.
15517 @cindex nonblocking @command{stty} setting
15518 Apply settings after first waiting for pending output to be transmitted.
15519 This is enabled by default for GNU @command{stty}.
15520 It is useful to disable this option
15521 in cases where the system may be in a state where serial transmission
15523 For example, if the system has received the @samp{DC3} character
15524 with @code{ixon} (software flow control) enabled, then @command{stty} would
15525 block without @code{-drain} being specified.
15526 May be negated. Non-POSIX.
15532 Print the number of rows and columns that the kernel thinks the
15533 terminal has. (Systems that don't support rows and columns in the kernel
15534 typically use the environment variables @env{LINES} and @env{COLUMNS}
15535 instead; however, GNU @command{stty} does not know anything about them.)
15540 Use line discipline @var{n}. Non-POSIX.
15544 Print the terminal speed.
15547 @cindex baud rate, setting
15548 Set the input and output speeds to @var{n}. @var{n} can be one of: 0
15549 50 75 110 134 134.5 150 200 300 600 1200 1800 2400 4800 9600 19200
15550 38400 @code{exta} @code{extb}. @code{exta} is the same as 19200;
15551 @code{extb} is the same as 38400. Many systems, including GNU/Linux,
15552 support higher speeds. The @command{stty} command includes support
15569 4000000 where the system supports these.
15570 0 hangs up the line if @option{-clocal} is set.
15574 @node printenv invocation
15575 @section @command{printenv}: Print all or some environment variables
15578 @cindex printing all or some environment variables
15579 @cindex environment variables, printing
15581 @command{printenv} prints environment variable values. Synopsis:
15584 printenv [@var{option}] [@var{variable}]@dots{}
15587 If no @var{variable}s are specified, @command{printenv} prints the value of
15588 every environment variable. Otherwise, it prints the value of each
15589 @var{variable} that is set, and nothing for those that are not set.
15591 The program accepts the following option. Also see @ref{Common options}.
15599 @cindex exit status of @command{printenv}
15603 0 if all variables specified were found
15604 1 if at least one specified variable was not found
15605 2 if a write error occurred
15609 @node tty invocation
15610 @section @command{tty}: Print file name of terminal on standard input
15613 @cindex print terminal file name
15614 @cindex terminal file name, printing
15616 @command{tty} prints the file name of the terminal connected to its standard
15617 input. It prints @samp{not a tty} if standard input is not a terminal.
15621 tty [@var{option}]@dots{}
15624 The program accepts the following option. Also see @ref{Common options}.
15634 Print nothing; only return an exit status.
15638 @cindex exit status of @command{tty}
15642 0 if standard input is a terminal
15643 1 if standard input is a non-terminal file
15644 2 if given incorrect arguments
15645 3 if a write error occurs
15649 @node User information
15650 @chapter User information
15652 @cindex user information, commands for
15653 @cindex commands for printing user information
15655 This section describes commands that print user-related information:
15656 logins, groups, and so forth.
15659 * id invocation:: Print user identity.
15660 * logname invocation:: Print current login name.
15661 * whoami invocation:: Print effective user ID.
15662 * groups invocation:: Print group names a user is in.
15663 * users invocation:: Print login names of users currently logged in.
15664 * who invocation:: Print who is currently logged in.
15668 @node id invocation
15669 @section @command{id}: Print user identity
15672 @cindex real user and group IDs, printing
15673 @cindex effective user and group IDs, printing
15674 @cindex printing real and effective user and group IDs
15676 @command{id} prints information about the given user, or the process
15677 running it if no user is specified. Synopsis:
15680 id [@var{option}]@dots{} [@var{user}]@dots{}
15683 @var{user} can be either a user ID or a name, with name look-up
15684 taking precedence unless the ID is specified with a leading @samp{+}.
15685 @xref{Disambiguating names and IDs}.
15687 @vindex POSIXLY_CORRECT
15688 By default, it prints the real user ID, real group ID, effective user ID
15689 if different from the real user ID, effective group ID if different from
15690 the real group ID, and supplemental group IDs.
15691 In addition, if SELinux
15692 is enabled and the @env{POSIXLY_CORRECT} environment variable is not set,
15693 then print @samp{context=@var{c}}, where @var{c} is the security context.
15695 Each of these numeric values is preceded by an identifying string and
15696 followed by the corresponding user or group name in parentheses.
15698 The options cause @command{id} to print only part of the above information.
15699 Also see @ref{Common options}.
15706 Print only the group ID.
15712 Print only the group ID and the supplementary groups.
15718 Print the user or group name instead of the ID number. Requires
15719 @option{-u}, @option{-g}, or @option{-G}.
15725 Print the real, instead of effective, user or group ID@. Requires
15726 @option{-u}, @option{-g}, or @option{-G}.
15732 Print only the user ID.
15739 @cindex security context
15740 Print only the security context of the process, which is generally
15741 the user's security context inherited from the parent process.
15742 If neither SELinux or SMACK is enabled then print a warning and
15743 set the exit status to 1.
15749 Delimit output items with ASCII NUL characters.
15750 This option is not permitted when using the default format.
15751 When multiple users are specified, and the @option{--groups} option
15752 is also in effect, groups are delimited with a single NUL character,
15753 while users are delimited with two NUL characters.
15758 users <NUL> devs <NUL>
15763 @macro primaryAndSupplementaryGroups{cmd,arg}
15764 Primary and supplementary groups for a process are normally inherited
15765 from its parent and are usually unchanged since login. This means
15766 that if you change the group database after logging in, @command{\cmd\}
15767 will not reflect your changes within your existing login session.
15768 Running @command{\cmd\} with a \arg\ causes the user and group
15769 database to be consulted afresh, and so will give a different result.
15771 @primaryAndSupplementaryGroups{id,user argument}
15775 @node logname invocation
15776 @section @command{logname}: Print current login name
15779 @cindex printing user's login name
15780 @cindex login name, printing
15781 @cindex user name, printing
15784 @command{logname} prints the calling user's name, as found in a
15785 system-maintained file (often @file{/var/run/utmp} or
15786 @file{/etc/utmp}), and exits with a status of 0. If there is no entry
15787 for the calling process, @command{logname} prints
15788 an error message and exits with a status of 1.
15790 The only options are @option{--help} and @option{--version}. @xref{Common
15796 @node whoami invocation
15797 @section @command{whoami}: Print effective user name
15800 @cindex effective user name, printing
15801 @cindex printing the effective user ID
15803 @command{whoami} prints the user name associated with the current
15804 effective user ID@. It is equivalent to the command @samp{id -un}.
15806 The only options are @option{--help} and @option{--version}. @xref{Common
15812 @node groups invocation
15813 @section @command{groups}: Print group names a user is in
15816 @cindex printing groups a user is in
15817 @cindex supplementary groups, printing
15819 @command{groups} prints the names of the primary and any supplementary
15820 groups for each given @var{username}, or the current process if no names
15821 are given. If more than one name is given, the name of each user is
15823 the list of that user's groups and the user name is separated from the
15824 group list by a colon. Synopsis:
15827 groups [@var{username}]@dots{}
15830 The group lists are equivalent to the output of the command @samp{id -Gn}.
15832 The only options are @option{--help} and @option{--version}. @xref{Common
15835 @primaryAndSupplementaryGroups{groups,list of users}
15839 @node users invocation
15840 @section @command{users}: Print login names of users currently logged in
15843 @cindex printing current usernames
15844 @cindex usernames, printing current
15846 @cindex login sessions, printing users with
15847 @command{users} prints on a single line a blank-separated list of user
15848 names of users currently logged in to the current host. Each user name
15849 corresponds to a login session, so if a user has more than one login
15850 session, that user's name will appear the same number of times in the
15859 With no @var{file} argument, @command{users} extracts its information from
15860 a system-maintained file (often @file{/var/run/utmp} or
15861 @file{/etc/utmp}). If a file argument is given, @command{users} uses
15862 that file instead. A common choice is @file{/var/log/wtmp}.
15864 The only options are @option{--help} and @option{--version}. @xref{Common
15867 The @command{users} command is installed only on platforms with the
15868 POSIX @code{<utmpx.h>} include file or equivalent, so portable scripts
15869 should not rely on its existence on non-POSIX platforms.
15874 @node who invocation
15875 @section @command{who}: Print who is currently logged in
15878 @cindex printing current user information
15879 @cindex information, about current users
15881 @command{who} prints information about users who are currently logged on.
15885 @command{who} [@var{option}] [@var{file}] [am i]
15888 @cindex terminal lines, currently used
15890 @cindex remote hostname
15891 If given no non-option arguments, @command{who} prints the following
15892 information for each user currently logged on: login name, terminal
15893 line, login time, and remote hostname or X display.
15897 If given one non-option argument, @command{who} uses that instead of
15898 a default system-maintained file (often @file{/var/run/utmp} or
15899 @file{/etc/utmp}) as the name of the file containing the record of
15900 users logged on. @file{/var/log/wtmp} is commonly given as an argument
15901 to @command{who} to look at who has previously logged on.
15905 If given two non-option arguments, @command{who} prints only the entry
15906 for the user running it (determined from its standard input), preceded
15907 by the hostname. Traditionally, the two arguments given are @samp{am
15908 i}, as in @samp{who am i}.
15911 Timestamps are listed according to the time zone rules specified by
15912 the @env{TZ} environment variable, or by the system default rules if
15913 @env{TZ} is not set. @xref{TZ Variable,, Specifying the Time Zone
15914 with @env{TZ}, libc, The GNU C Library Reference Manual}.
15916 The program accepts the following options. Also see @ref{Common options}.
15924 Same as @samp{-b -d --login -p -r -t -T -u}.
15930 Print the date and time of last system boot.
15936 Print information corresponding to dead processes.
15942 Print a line of column headings.
15948 List only the entries that correspond to processes via which the
15949 system is waiting for a user to login. The user name is always @samp{LOGIN}.
15953 Attempt to canonicalize hostnames found in utmp through a DNS lookup. This
15954 is not the default because it can cause significant delays on systems with
15955 automatic dial-up internet access.
15959 Same as @samp{who am i}.
15965 List active processes spawned by init.
15971 Print only the login names and the number of users logged on.
15972 Overrides all other options.
15977 @opindex --runlevel
15978 Print the current (and maybe previous) run-level of the init process.
15982 Ignored; for compatibility with other versions of @command{who}.
15988 Print last system clock change.
15993 After the login time, print the number of hours and minutes that the
15994 user has been idle. @samp{.} means the user was active in the last minute.
15995 @samp{old} means the user has been idle for more than 24 hours.
16006 @opindex --writable
16007 @cindex message status
16008 @pindex write@r{, allowed}
16009 After each login name print a character indicating the user's message status:
16012 @samp{+} allowing @code{write} messages
16013 @samp{-} disallowing @code{write} messages
16014 @samp{?} cannot find terminal device
16019 The @command{who} command is installed only on platforms with the
16020 POSIX @code{<utmpx.h>} include file or equivalent, so portable scripts
16021 should not rely on its existence on non-POSIX platforms.
16026 @node System context
16027 @chapter System context
16029 @cindex system context
16030 @cindex context, system
16031 @cindex commands for system context
16033 This section describes commands that print or change system-wide
16037 * date invocation:: Print or set system date and time.
16038 * arch invocation:: Print machine hardware name.
16039 * nproc invocation:: Print the number of processors.
16040 * uname invocation:: Print system information.
16041 * hostname invocation:: Print or set system name.
16042 * hostid invocation:: Print numeric host identifier.
16043 * uptime invocation:: Print system uptime and load.
16046 @node date invocation
16047 @section @command{date}: Print or set system date and time
16050 @cindex time, printing or setting
16051 @cindex printing the current time
16056 date [@var{option}]@dots{} [+@var{format}]
16057 date [-u|--utc|--universal] @c this avoids a newline in the output
16058 [ MMDDhhmm[[CC]YY][.ss] ]
16061 The @command{date} command displays the date and time.
16062 With the @option{--set} (@option{-s}) option, or with
16063 @samp{MMDDhhmm[[CC]YY][.ss]},
16064 it sets the date and time.
16067 Invoking @command{date} with no @var{format} argument is equivalent to invoking
16068 it with a default format that depends on the @env{LC_TIME} locale category.
16069 In the default C locale, this format is @samp{'+%a %b %e %H:%M:%S %Z %Y'},
16070 so the output looks like @samp{Thu Jul @ 9 17:00:00 EDT 2020}.
16073 Normally, @command{date} uses the time zone rules indicated by the
16074 @env{TZ} environment variable, or the system default rules if @env{TZ}
16075 is not set. @xref{TZ Variable,, Specifying the Time Zone with
16076 @env{TZ}, libc, The GNU C Library Reference Manual}.
16078 @findex strftime @r{and @command{date}}
16079 @cindex time formats
16080 @cindex formatting times
16081 If given an argument that starts with a @samp{+}, @command{date} prints the
16082 current date and time (or the date and time specified by the
16083 @option{--date} option, see below) in the format defined by that argument,
16084 which is similar to that of the @code{strftime} function. Except for
16085 conversion specifiers, which start with @samp{%}, characters in the
16086 format string are printed unchanged. The conversion specifiers are
16092 * Time conversion specifiers:: %[HIklMNpPrRsSTXzZ]
16093 * Date conversion specifiers:: %[aAbBcCdDeFgGhjmuUVwWxyY]
16094 * Literal conversion specifiers:: %[%nt]
16095 * Padding and other flags:: Pad with zeros, spaces, etc.
16096 * Setting the time:: Changing the system clock.
16097 * Options for date:: Instead of the current time.
16099 * Date input formats:: Specifying date strings.
16101 * Examples of date:: Examples.
16104 @node Time conversion specifiers
16105 @subsection Time conversion specifiers
16107 @cindex time conversion specifiers
16108 @cindex conversion specifiers, time
16110 @command{date} conversion specifiers related to times.
16114 hour (@samp{00}@dots{}@samp{23})
16116 hour (@samp{01}@dots{}@samp{12})
16118 hour, space padded (@samp{ 0}@dots{}@samp{23}); equivalent to @samp{%_H}@.
16119 This is a GNU extension.
16121 hour, space padded (@samp{ 1}@dots{}@samp{12}); equivalent to @samp{%_I}@.
16122 This is a GNU extension.
16124 minute (@samp{00}@dots{}@samp{59})
16126 nanoseconds (@samp{000000000}@dots{}@samp{999999999}).
16127 This is a GNU extension.
16129 locale's equivalent of either @samp{AM} or @samp{PM};
16130 blank in many locales.
16131 Noon is treated as @samp{PM} and midnight as @samp{AM}.
16133 like @samp{%p}, except lower case.
16134 This is a GNU extension.
16136 locale's 12-hour clock time (e.g., @samp{11:11:04 PM})
16138 24-hour hour and minute. Same as @samp{%H:%M}.
16140 @cindex Epoch, seconds since
16141 @cindex seconds since the Epoch
16142 @cindex beginning of time
16143 @cindex leap seconds
16144 seconds since the Epoch, i.e., since 1970-01-01 00:00 UTC@.
16145 Leap seconds are not counted unless leap second support is available.
16146 @xref{%s-examples}, for examples.
16147 This is a GNU extension.
16149 @cindex leap seconds
16150 second (@samp{00}@dots{}@samp{60}).
16151 This may be @samp{60} if leap seconds are supported.
16153 24-hour hour, minute, and second. Same as @samp{%H:%M:%S}.
16155 locale's time representation (e.g., @samp{23:13:48})
16157 Four-digit numeric time zone, e.g., @samp{-0600} or @samp{+0530}, or
16159 time zone is determinable. This value reflects the numeric time zone
16160 appropriate for the current time, using the time zone rules specified
16161 by the @env{TZ} environment variable. A time zone is not determinable if
16162 its numeric offset is zero and its abbreviation begins with @samp{-}.
16163 The time (and optionally, the time zone rules) can be overridden
16164 by the @option{--date} option.
16166 Numeric time zone with @samp{:}, e.g., @samp{-06:00} or
16167 @samp{+05:30}), or @samp{-00:00} if no time zone is determinable.
16168 This is a GNU extension.
16170 Numeric time zone to the nearest second with @samp{:} (e.g.,
16171 @samp{-06:00:00} or @samp{+05:30:00}), or @samp{-00:00:00} if no time zone is
16173 This is a GNU extension.
16175 Numeric time zone with @samp{:} using the minimum necessary precision
16176 (e.g., @samp{-06}, @samp{+05:30}, or @samp{-04:56:02}), or @samp{-00} if
16177 no time zone is determinable.
16178 This is a GNU extension.
16180 alphabetic time zone abbreviation (e.g., @samp{EDT}), or nothing if no
16181 time zone is determinable. See @samp{%z} for how it is determined.
16185 @node Date conversion specifiers
16186 @subsection Date conversion specifiers
16188 @cindex date conversion specifiers
16189 @cindex conversion specifiers, date
16191 @command{date} conversion specifiers related to dates.
16195 locale's abbreviated weekday name (e.g., @samp{Sun})
16197 locale's full weekday name, variable length (e.g., @samp{Sunday})
16199 locale's abbreviated month name (e.g., @samp{Jan})
16201 locale's full month name, variable length (e.g., @samp{January})
16203 locale's date and time (e.g., @samp{Thu Mar @ 3 23:05:25 2020})
16205 century. This is like @samp{%Y}, except the last two digits are omitted.
16206 For example, it is @samp{20} if @samp{%Y} is @samp{2019},
16207 and is @samp{-0} if @samp{%Y} is @samp{-001}.
16208 It is normally at least two characters, but it may be more.
16210 day of month (e.g., @samp{01})
16212 date; same as @samp{%m/%d/%y}
16214 day of month, space padded; same as @samp{%_d}
16216 full date in ISO 8601 format; like @samp{%+4Y-%m-%d}
16217 except that any flags or field width override the @samp{+}
16218 and (after subtracting 6) the @samp{4}.
16219 This is a good choice for a date format, as it is standard and
16220 is easy to sort in the usual case where years are in the range
16223 year corresponding to the ISO week number, but without the century
16224 (range @samp{00} through @samp{99}). This has the same format and value
16225 as @samp{%y}, except that if the ISO week number (see
16227 to the previous or next year, that year is used instead.
16229 year corresponding to the ISO week number. This has the
16230 same format and value as @samp{%Y}, except that if the ISO
16232 @samp{%V}) belongs to the previous or next year, that year is used
16234 It is normally useful only if @samp{%V} is also used;
16235 for example, the format @samp{%G-%m-%d} is probably a mistake,
16236 since it combines the ISO week number year with the conventional month and day.
16240 day of year (@samp{001}@dots{}@samp{366})
16242 month (@samp{01}@dots{}@samp{12})
16244 quarter of year (@samp{1}@dots{}@samp{4})
16246 day of week (@samp{1}@dots{}@samp{7}) with @samp{1} corresponding to Monday
16248 week number of year, with Sunday as the first day of the week
16249 (@samp{00}@dots{}@samp{53}).
16250 Days in a new year preceding the first Sunday are in week zero.
16252 ISO week number, that is, the
16253 week number of year, with Monday as the first day of the week
16254 (@samp{01}@dots{}@samp{53}).
16255 If the week containing January 1 has four or more days in
16256 the new year, then it is considered week 1; otherwise, it is week 53 of
16257 the previous year, and the next week is week 1. (See the ISO 8601
16260 day of week (@samp{0}@dots{}@samp{6}) with 0 corresponding to Sunday
16262 week number of year, with Monday as first day of week
16263 (@samp{00}@dots{}@samp{53}).
16264 Days in a new year preceding the first Monday are in week zero.
16266 locale's date representation (e.g., @samp{12/31/99})
16268 last two digits of year (@samp{00}@dots{}@samp{99})
16270 year. This is normally at least four characters, but it may be more.
16271 Year @samp{0000} precedes year @samp{0001}, and year @samp{-001}
16272 precedes year @samp{0000}.
16276 @node Literal conversion specifiers
16277 @subsection Literal conversion specifiers
16279 @cindex literal conversion specifiers
16280 @cindex conversion specifiers, literal
16282 @command{date} conversion specifiers that produce literal strings.
16294 @node Padding and other flags
16295 @subsection Padding and other flags
16297 @cindex numeric field padding
16298 @cindex padding of numeric fields
16299 @cindex fields, padding numeric
16301 Unless otherwise specified, @command{date} normally pads numeric fields
16302 with zeros, so that, for
16303 example, numeric months are always output as two digits.
16304 Most numeric fields are padded on the left.
16305 However, nanoseconds are padded on the right since they are commonly
16306 used after decimal points in formats like @samp{%s.%-N}.
16307 Also, seconds since the Epoch are not padded
16308 since there is no natural width for them.
16310 The following optional flags can appear after the @samp{%}:
16314 (hyphen) Do not pad the field; useful if the output is intended for
16316 This is a GNU extension.
16317 As a special case, @samp{%-N} outputs only enough trailing digits to
16318 not lose information, assuming that the timestamp's resolution is the
16319 same as the current hardware clock. For example, if the hardware
16320 clock resolution is 1 microsecond, @samp{%s.%-N} outputs something
16321 like @samp{1640890100.395710}.
16324 (underscore) Pad with spaces; useful if you need a fixed
16325 number of characters in the output, but zeros are too distracting.
16326 This is a GNU extension.
16328 (zero) Pad with zeros even if the conversion specifier
16329 would normally pad with spaces.
16331 Pad with zeros, like @samp{0}. In addition, precede any year number
16332 with @samp{+} if it exceeds 9999 or if its field width exceeds 4;
16333 similarly, precede any century number with @samp{+} if it exceeds 99
16334 or if its field width exceeds 2. This supports ISO 8601 formats
16335 for dates far in the future; for example, the command @code{date
16336 --date=12019-02-25 +%+13F} outputs the string @samp{+012019-02-25}.
16338 Use upper case characters if possible.
16339 This is a GNU extension.
16341 Use opposite case characters if possible.
16342 A field that is normally upper case becomes lower case, and vice versa.
16343 This is a GNU extension.
16347 Here are some examples of padding:
16350 date +%d/%m -d "Feb 1"
16352 date +%-d/%-m -d "Feb 1"
16354 date +%_d/%_m -d "Feb 1"
16358 You can optionally specify the field width
16359 (after any flag, if present) as a decimal number. If the natural size of the
16360 output of the field has less than the specified number of characters,
16361 the result is normally written right adjusted and padded to the given
16362 size. For example, @samp{%9B} prints the right adjusted month name in
16363 a field of width 9. Nanoseconds are left adjusted, and are truncated
16364 or padded to the field width.
16366 An optional modifier can follow the optional flag and width
16367 specification. The modifiers are:
16371 Use the locale's alternate representation for date and time. This
16372 modifier applies to the @samp{%c}, @samp{%C}, @samp{%x}, @samp{%X},
16373 @samp{%y} and @samp{%Y} conversion specifiers. In a Japanese locale, for
16374 example, @samp{%Ex} might yield a date format based on the Japanese
16378 Use the locale's alternate numeric symbols for numbers. This modifier
16379 applies only to numeric conversion specifiers.
16382 If the format supports the modifier but no alternate representation
16383 is available, it is ignored.
16385 POSIX specifies the behavior of flags and field widths only for
16386 @samp{%C}, @samp{%F}, @samp{%G}, and @samp{%Y} (all without
16387 modifiers), and requires a flag to be present if and only if a field
16388 width is also present. Other combinations of flags, field widths and
16389 modifiers are GNU extensions.
16392 @node Setting the time
16393 @subsection Setting the time
16395 @cindex setting the time
16396 @cindex time setting
16397 @cindex appropriate privileges
16399 You must have appropriate privileges to set the
16400 system clock. For changes to persist across a reboot, the
16401 hardware clock may need to be updated from the system clock, which
16402 might not happen automatically on your system.
16404 To set the clock, you can use the @option{--set} (@option{-s}) option
16405 (@pxref{Options for date}). To set the clock without using GNU
16406 extensions, you can give @command{date} an argument of the form
16407 @samp{MMDDhhmm[[CC]YY][.ss]} where each two-letter
16408 component stands for two digits with the following meanings:
16420 first two digits of year (optional)
16422 last two digits of year (optional)
16427 Note, the @option{--date} and @option{--set} options may not be used with an
16428 argument in the above format. The @option{--universal} option may be used
16429 with such an argument to indicate that the specified date and time are
16430 relative to Universal Time rather than to the local time zone.
16433 @node Options for date
16434 @subsection Options for @command{date}
16436 @cindex @command{date} options
16437 @cindex options for @command{date}
16439 The program accepts the following options. Also see @ref{Common options}.
16440 Except for @option{-u}, these options are all GNU extensions to POSIX.
16442 All options that specify the date to display are mutually exclusive.
16443 I.e.: @option{--date}, @option{--file}, @option{--reference},
16444 @option{--resolution}.
16448 @item -d @var{datestr}
16449 @itemx --date=@var{datestr}
16452 @cindex parsing date strings
16453 @cindex date strings, parsing
16454 @cindex arbitrary date strings, parsing
16457 @opindex next @var{day}
16458 @opindex last @var{day}
16459 Display the date and time specified in @var{datestr} instead of the
16460 current date and time. @var{datestr} can be in almost any common
16461 format. It can contain month names, time zones, @samp{am} and @samp{pm},
16462 @samp{yesterday}, etc. For example, @option{--date="2020-07-21
16463 14:19:13.489392193 +0530"} specifies the instant of time that is
16464 489,392,193 nanoseconds after July 21, 2020 at 2:19:13 PM in a
16465 time zone that is 5 hours and 30 minutes east of UTC.@*
16466 Note: input currently must be in locale independent format. E.g., the
16467 LC_TIME=C below is needed to print back the correct date in many locales:
16469 date -d "$(LC_TIME=C date)"
16471 @xref{Date input formats}.
16475 @cindex debugging date strings
16476 @cindex date strings, debugging
16477 @cindex arbitrary date strings, debugging
16478 Annotate the parsed date, display the effective time zone, and warn about
16481 @item -f @var{datefile}
16482 @itemx --file=@var{datefile}
16485 Parse each line in @var{datefile} as with @option{-d} and display the
16486 resulting date and time. If @var{datefile} is @samp{-}, use standard
16487 input. This is useful when you have many dates to process, because the
16488 system overhead of starting up the @command{date} executable many times can
16491 @item -I[@var{timespec}]
16492 @itemx --iso-8601[=@var{timespec}]
16493 @opindex -I[@var{timespec}]
16494 @opindex --iso-8601[=@var{timespec}]
16495 Display the date using an ISO 8601 format, @samp{%Y-%m-%d}.
16497 The argument @var{timespec} specifies the number of additional
16498 terms of the time to include. It can be one of the following:
16501 Print just the date. This is the default if @var{timespec} is omitted.
16504 Append the hour of the day to the date.
16507 Append the hours and minutes.
16510 Append the hours, minutes and seconds.
16513 Append the hours, minutes, seconds and nanoseconds.
16516 If showing any time terms, then include the time zone using the format
16518 @macro dateParseNote
16519 This format is always suitable as input
16520 for the @option{--date} (@option{-d}) and @option{--file}
16521 (@option{-f}) options, regardless of the current locale.
16525 @item -r @var{file}
16526 @itemx --reference=@var{file}
16528 @opindex --reference
16529 Display the date and time of the last modification of @var{file},
16530 instead of the current date and time.
16533 @opindex --resolution
16534 Display the timestamp resolution instead of the time.
16535 Current clock timestamps that are output by @command{date}
16536 are integer multiples of the timestamp resolution.
16537 With this option, the format defaults to @samp{%s.%N}.
16538 For example, if the clock resolution is 1 millsecond,
16548 @opindex --rfc-email
16549 Display the date and time using the format @samp{%a, %d %b %Y %H:%M:%S
16550 %z}, evaluated in the C locale so abbreviations are always in English.
16554 Mon, 09 Jul 2020 17:00:00 -0400
16558 @opindex --rfc-2822
16559 This format conforms to Internet RFCs
16560 @uref{https://tools.ietf.org/search/rfc5322, 5322},
16561 @uref{https://tools.ietf.org/search/rfc2822, 2822} and
16562 @uref{https://tools.ietf.org/search/rfc822, 822}, the
16563 current and previous standards for Internet email.
16564 For compatibility with older versions of @command{date},
16565 @option{--rfc-2822} and @option{--rfc-822} are aliases for
16566 @option{--rfc-email}.
16568 @item --rfc-3339=@var{timespec}
16569 @opindex --rfc-3339=@var{timespec}
16570 Display the date using a format specified by
16571 @uref{https://tools.ietf.org/search/rfc3339, Internet
16572 RFC 3339}. This is like @option{--iso-8601}, except that a space rather
16573 than a @samp{T} separates dates from times, and a period rather than
16574 a comma separates seconds from subseconds.
16577 The argument @var{timespec} specifies how much of the time to include.
16578 It can be one of the following:
16582 Print just the full-date, e.g., @samp{2020-07-21}.
16583 This is equivalent to the format @samp{%Y-%m-%d}.
16586 Print the full-date and full-time separated by a space, e.g.,
16587 @samp{2020-07-21 04:30:37+05:30}. The output ends with a numeric
16588 time-offset; here the @samp{+05:30} means that local time is five
16589 hours and thirty minutes east of UTC@. This is equivalent to
16590 the format @samp{%Y-%m-%d %H:%M:%S%:z}.
16593 Like @samp{seconds}, but also print nanoseconds, e.g.,
16594 @samp{2020-07-21 04:30:37.998458565+05:30}.
16595 This is equivalent to the format @samp{%Y-%m-%d %H:%M:%S.%N%:z}.
16599 @item -s @var{datestr}
16600 @itemx --set=@var{datestr}
16603 Set the date and time to @var{datestr}. See @option{-d} above.
16604 See also @ref{Setting the time}.
16611 @opindex --universal
16612 @cindex Coordinated Universal Time
16614 @cindex Greenwich Mean Time
16616 @cindex leap seconds
16618 @cindex Universal Time
16619 Use Universal Time by operating as if the
16620 @env{TZ} environment variable were set to the string @samp{UTC0}.
16621 UTC stands for Coordinated Universal Time, established in 1960.
16622 Universal Time is often called ``Greenwich Mean Time'' (GMT) for
16623 historical reasons.
16624 Typically, systems ignore leap seconds and thus implement an
16625 approximation to UTC rather than true UTC.
16629 @node Examples of date
16630 @subsection Examples of @command{date}
16632 @cindex examples of @command{date}
16634 Here are a few examples. Also see the documentation for the @option{-d}
16635 option in the previous section.
16640 To print the date of the day before yesterday:
16643 date --date='2 days ago'
16647 To print the date of the day three months and one day hence:
16650 date --date='3 months 1 day'
16654 To print the day of year of Christmas in the current year:
16657 date --date='25 Dec' +%j
16661 To print the current full month name and the day of the month:
16667 But this may not be what you want because for the first nine days of
16668 the month, the @samp{%d} expands to a zero-padded two-digit field,
16669 for example @samp{date -d 1may '+%B %d'} will print @samp{May 01}.
16672 To print a date without the leading zero for one-digit days
16673 of the month, you can use the (GNU extension)
16674 @samp{-} flag to suppress
16675 the padding altogether:
16678 date -d 1may '+%B %-d'
16682 To print the current date and time in the format required by many
16683 non-GNU versions of @command{date} when setting the system clock:
16686 date +%m%d%H%M%Y.%S
16690 To set the system clock forward by two minutes:
16693 date --set='+2 minutes'
16697 To print the date in Internet RFC 5322 format,
16698 use @samp{date --rfc-email}. Here is some example output:
16701 Tue, 09 Jul 2020 19:00:37 -0400
16704 @anchor{%s-examples}
16706 To convert a date string to the number of seconds since the Epoch
16707 (which is 1970-01-01 00:00 UTC), use the @option{--date} option with
16708 the @samp{%s} format. That can be useful in sorting and/or graphing
16709 and/or comparing data by date. The following command outputs the
16710 number of the seconds since the Epoch for the time two minutes after the
16714 date --date='1970-01-01 00:02:00 +0000' +%s
16718 If you do not specify time zone information in the date string,
16719 @command{date} uses your computer's idea of the time zone when
16720 interpreting the string. For example, if your computer's time zone is
16721 that of Cambridge, Massachusetts, which was then 5 hours (i.e., 18,000
16722 seconds) behind UTC:
16725 # local time zone used
16726 date --date='1970-01-01 00:02:00' +%s
16731 If you're sorting or graphing dated data, your raw date values may be
16732 represented as seconds since the Epoch. But few people can look at
16733 the date @samp{1577836800} and casually note ``Oh, that's the first
16734 second of the year 2020 in Greenwich, England.''
16737 date --date='2020-01-01 UTC' +%s
16741 An alternative is to use the @option{--utc} (@option{-u}) option.
16742 Then you may omit @samp{UTC} from the date string. Although this
16743 produces the same result for @samp{%s} and many other format sequences,
16744 with a time zone offset different from zero, it would give a different
16745 result for zone-dependent formats like @samp{%z}.
16748 date -u --date=2020-07-21 +%s
16752 To convert such an unwieldy number of seconds back to
16753 a more readable form, use a command like this:
16756 date -d @@1595289600 +"%F %T %z"
16757 2020-07-20 20:00:00 -0400
16760 Often it is better to output UTC-relative date and time:
16763 date -u -d @@1595289600 +"%F %T %z"
16764 2020-07-21 00:00:00 +0000
16768 @cindex leap seconds
16769 Typically the seconds count omits leap seconds, but some systems are
16770 exceptions. Because leap seconds are not predictable, the mapping
16771 between the seconds count and a future timestamp is not reliable on
16772 the atypical systems that include leap seconds in their counts.
16774 Here is how the two kinds of systems handle the leap second at
16775 the end of the year 2016:
16778 # Typical systems ignore leap seconds:
16779 date --date='2016-12-31 23:59:59 +0000' +%s
16781 date --date='2016-12-31 23:59:60 +0000' +%s
16782 date: invalid date '2016-12-31 23:59:60 +0000'
16783 date --date='2017-01-01 00:00:00 +0000' +%s
16788 # Atypical systems count leap seconds:
16789 date --date='2016-12-31 23:59:59 +0000' +%s
16791 date --date='2016-12-31 23:59:60 +0000' +%s
16793 date --date='2017-01-01 00:00:00 +0000' +%s
16800 @node arch invocation
16801 @section @command{arch}: Print machine hardware name
16804 @cindex print machine hardware name
16805 @cindex system information, printing
16807 @command{arch} prints the machine hardware name,
16808 and is equivalent to @samp{uname -m}.
16812 arch [@var{option}]
16815 The program accepts the @ref{Common options} only.
16817 @command{arch} is not installed by default, so portable scripts should
16818 not rely on its existence.
16823 @node nproc invocation
16824 @section @command{nproc}: Print the number of available processors
16827 @cindex Print the number of processors
16828 @cindex system information, printing
16830 Print the number of processing units available to the current process,
16831 which may be less than the number of online processors.
16832 If this information is not accessible, then print the number of
16833 processors installed. If the @env{OMP_NUM_THREADS} or @env{OMP_THREAD_LIMIT}
16834 environment variables are set, then they will determine the minimum
16835 and maximum returned value respectively. The result is guaranteed to be
16836 greater than zero. Synopsis:
16839 nproc [@var{option}]
16842 The program accepts the following options. Also see @ref{Common options}.
16848 Print the number of installed processors on the system, which may
16849 be greater than the number online or available to the current process.
16850 The @env{OMP_NUM_THREADS} or @env{OMP_THREAD_LIMIT} environment variables
16851 are not honored in this case.
16853 @item --ignore=@var{number}
16855 If possible, exclude this @var{number} of processing units.
16862 @node uname invocation
16863 @section @command{uname}: Print system information
16866 @cindex print system information
16867 @cindex system information, printing
16869 @command{uname} prints information about the machine and operating system
16870 it is run on. If no options are given, @command{uname} acts as if the
16871 @option{-s} option were given. Synopsis:
16874 uname [@var{option}]@dots{}
16877 If multiple options or @option{-a} are given, the selected information is
16878 printed in this order:
16881 @var{kernel-name} @var{nodename} @var{kernel-release} @var{kernel-version}
16882 @var{machine} @var{processor} @var{hardware-platform} @var{operating-system}
16885 The information may contain internal spaces, so such output cannot be
16886 parsed reliably. In the following example, @var{kernel-version} is
16887 @samp{#1 SMP Fri Jul 17 17:18:38 UTC 2020}:
16891 @result{} Linux dumdum.example.org 5.9.16-200.fc33.x86_64@c
16892 #1 SMP Mon Dec 21 14:08:22 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
16896 The program accepts the following options. Also see @ref{Common options}.
16904 Print all of the below information, except omit the processor type
16905 and the hardware platform name if they are unknown.
16908 @itemx --hardware-platform
16910 @opindex --hardware-platform
16911 @cindex implementation, hardware
16912 @cindex hardware platform
16913 @cindex platform, hardware
16914 Print the hardware platform name
16915 (sometimes called the hardware implementation).
16916 Print @samp{unknown} if this information is not available.
16917 Note this is non-portable (even across GNU/Linux distributions).
16923 @cindex machine type
16924 @cindex hardware class
16925 @cindex hardware type
16926 Print the machine hardware name (sometimes called the hardware class
16932 @opindex --nodename
16935 @cindex network node name
16936 Print the network node hostname.
16941 @opindex --processor
16942 @cindex host processor type
16943 Print the processor type (sometimes called the instruction set
16944 architecture or ISA).
16945 Print @samp{unknown} if this information is not available.
16946 Note this is non-portable (even across GNU/Linux distributions).
16949 @itemx --operating-system
16951 @opindex --operating-system
16952 @cindex operating system name
16953 Print the name of the operating system.
16956 @itemx --kernel-release
16958 @opindex --kernel-release
16959 @cindex kernel release
16960 @cindex release of kernel
16961 Print the kernel release.
16964 @itemx --kernel-name
16966 @opindex --kernel-name
16967 @cindex kernel name
16968 @cindex name of kernel
16969 Print the kernel name.
16970 POSIX 1003.1-2001 (@pxref{Standards conformance}) calls this
16971 ``the implementation of the operating system'', because the
16972 POSIX specification itself has no notion of ``kernel''.
16973 The kernel name might be the same as the operating system name printed
16974 by the @option{-o} or @option{--operating-system} option, but it might
16975 differ. Some operating systems (e.g., FreeBSD, HP-UX) have the same
16976 name as their underlying kernels; others (e.g., GNU/Linux, Solaris)
16980 @itemx --kernel-version
16982 @opindex --kernel-version
16983 @cindex kernel version
16984 @cindex version of kernel
16985 Print the kernel version.
16992 @node hostname invocation
16993 @section @command{hostname}: Print or set system name
16996 @cindex setting the hostname
16997 @cindex printing the hostname
16998 @cindex system name, printing
16999 @cindex appropriate privileges
17001 With no arguments, @command{hostname} prints the name of the current host
17002 system. With one argument, it sets the current host name to the
17003 specified string. You must have appropriate privileges to set the host
17007 hostname [@var{name}]
17010 The only options are @option{--help} and @option{--version}. @xref{Common
17013 @command{hostname} is not installed by default, and other packages
17014 also supply a @command{hostname} command, so portable scripts should
17015 not rely on its existence or on the exact behavior documented above.
17020 @node hostid invocation
17021 @section @command{hostid}: Print numeric host identifier
17024 @cindex printing the host identifier
17026 @command{hostid} prints the numeric identifier of the current host
17027 in hexadecimal. This command accepts no arguments.
17028 The only options are @option{--help} and @option{--version}.
17029 @xref{Common options}.
17031 For example, here's what it prints on one system I use:
17038 On that system, the 32-bit quantity happens to be closely
17039 related to the system's Internet address, but that isn't always
17042 @command{hostid} is installed only on systems that have the
17043 @code{gethostid} function, so portable scripts should not rely on its
17048 @node uptime invocation
17049 @section @command{uptime}: Print system uptime and load
17052 @cindex printing the system uptime and load
17054 @command{uptime} prints the current time, the system's uptime, the
17055 number of logged-in users and the current load average.
17057 If an argument is specified, it is used as the file to be read
17058 to discover how many users are logged in. If no argument is
17059 specified, a system default is used (@command{uptime --help} indicates
17060 the default setting).
17062 The only options are @option{--help} and @option{--version}.
17063 @xref{Common options}.
17065 For example, here's what it prints right now on one system I use:
17069 14:07 up 3:35, 3 users, load average: 1.39, 1.15, 1.04
17072 The precise method of calculation of load average varies somewhat
17073 between systems. Some systems calculate it as the average number of
17074 runnable processes over the last 1, 5 and 15 minutes, but some systems
17075 also include processes in the uninterruptible sleep state (that is,
17076 those processes which are waiting for device I/O). The Linux kernel
17077 includes uninterruptible processes.
17079 @command{uptime} is installed only on platforms with infrastructure
17080 for obtaining the boot time, and other packages also supply an
17081 @command{uptime} command, so portable scripts should not rely on its
17082 existence or on the exact behavior documented above.
17086 @node SELinux context
17087 @chapter SELinux context
17089 @cindex SELinux context
17090 @cindex SELinux, context
17091 @cindex commands for SELinux context
17093 This section describes commands for operations with SELinux
17097 * chcon invocation:: Change SELinux context of file
17098 * runcon invocation:: Run a command in specified SELinux context
17101 @node chcon invocation
17102 @section @command{chcon}: Change SELinux context of file
17105 @cindex changing security context
17106 @cindex change SELinux context
17108 @command{chcon} changes the SELinux security context of the selected files.
17112 chcon [@var{option}]@dots{} @var{context} @var{file}@dots{}
17113 chcon [@var{option}]@dots{} [-u @var{user}] [-r @var{role}] [-l @var{range}]@c
17114 [-t @var{type}] @var{file}@dots{}
17115 chcon [@var{option}]@dots{} --reference=@var{rfile} @var{file}@dots{}
17118 Change the SELinux security context of each @var{file} to @var{context}.
17119 With @option{--reference}, change the security context of each @var{file}
17120 to that of @var{rfile}.
17122 The program accepts the following options. Also see @ref{Common options}.
17126 @item --dereference
17127 @opindex --dereference
17128 Do not affect symbolic links but what they refer to; this is the default.
17131 @itemx --no-dereference
17133 @opindex --no-dereference
17134 @cindex no dereference
17135 Affect the symbolic links themselves instead of any referenced file.
17137 @item --reference=@var{rfile}
17138 @opindex --reference
17139 @cindex reference file
17140 Use @var{rfile}'s security context rather than specifying a @var{context} value.
17145 @opindex --recursive
17146 Operate on files and directories recursively.
17148 @item --preserve-root
17149 @opindex --preserve-root
17150 Refuse to operate recursively on the root directory, @file{/},
17151 when used together with the @option{--recursive} option.
17152 @xref{Treating / specially}.
17154 @item --no-preserve-root
17155 @opindex --no-preserve-root
17156 Do not treat the root directory, @file{/}, specially when operating
17157 recursively; this is the default.
17158 @xref{Treating / specially}.
17161 @xref{Traversing symlinks}.
17164 @xref{Traversing symlinks}.
17167 @xref{Traversing symlinks}.
17174 Output a diagnostic for every file processed.
17176 @item -u @var{user}
17177 @itemx --user=@var{user}
17180 Set user @var{user} in the target security context.
17182 @item -r @var{role}
17183 @itemx --role=@var{role}
17186 Set role @var{role} in the target security context.
17188 @item -t @var{type}
17189 @itemx --type=@var{type}
17192 Set type @var{type} in the target security context.
17194 @item -l @var{range}
17195 @itemx --range=@var{range}
17198 Set range @var{range} in the target security context.
17204 @node runcon invocation
17205 @section @command{runcon}: Run a command in specified SELinux context
17208 @cindex run with security context
17211 @command{runcon} runs file in specified SELinux security context.
17215 runcon @var{context} @var{command} [@var{args}]
17216 runcon [ -c ] [-u @var{user}] [-r @var{role}] [-t @var{type}]@c
17217 [-l @var{range}] @var{command} [@var{args}]
17220 Run @var{command} with completely-specified @var{context}, or with
17221 current or transitioned security context modified by one or more of @var{level},
17222 @var{role}, @var{type} and @var{user}.
17224 If none of @option{-c}, @option{-t}, @option{-u}, @option{-r}, or @option{-l}
17225 is specified, the first argument is used as the complete context.
17226 Any additional arguments after @var{command}
17227 are interpreted as arguments to the command.
17229 With neither @var{context} nor @var{command}, print the current
17232 @cindex restricted security context
17233 @cindex NO_NEW_PRIVS
17234 Note also the @command{setpriv} command which can be used to set the
17235 NO_NEW_PRIVS bit using @command{setpriv --no-new-privs runcon ...},
17236 thus disallowing usage of a security context with more privileges
17237 than the process would normally have.
17239 @command{runcon} accepts the following options. Also see @ref{Common options}.
17247 Compute process transition context before modifying.
17249 @item -u @var{user}
17250 @itemx --user=@var{user}
17253 Set user @var{user} in the target security context.
17255 @item -r @var{role}
17256 @itemx --role=@var{role}
17259 Set role @var{role} in the target security context.
17261 @item -t @var{type}
17262 @itemx --type=@var{type}
17265 Set type @var{type} in the target security context.
17267 @item -l @var{range}
17268 @itemx --range=@var{range}
17271 Set range @var{range} in the target security context.
17275 @cindex exit status of @command{runcon}
17279 126 if @var{command} is found but cannot be invoked
17280 127 if @command{runcon} itself fails or if @var{command} cannot be found
17281 the exit status of @var{command} otherwise
17284 @node Modified command invocation
17285 @chapter Modified command invocation
17287 @cindex modified command invocation
17288 @cindex invocation of commands, modified
17289 @cindex commands for invoking other commands
17291 This section describes commands that run other commands in some context
17292 different than the current one: a modified environment, as a different
17296 * chroot invocation:: Modify the root directory.
17297 * env invocation:: Modify environment variables.
17298 * nice invocation:: Modify niceness.
17299 * nohup invocation:: Immunize to hangups.
17300 * stdbuf invocation:: Modify buffering of standard streams.
17301 * timeout invocation:: Run with time limit.
17305 @node chroot invocation
17306 @section @command{chroot}: Run a command with a different root directory
17309 @cindex running a program in a specified root directory
17310 @cindex root directory, running a program in a specified
17312 @command{chroot} runs a command with a specified root directory.
17313 On many systems, only the super-user can do this.@footnote{However,
17314 some systems (e.g., FreeBSD) can be configured to allow certain regular
17315 users to use the @code{chroot} system call, and hence to run this program.
17316 Also, on Cygwin, anyone can run the @command{chroot} command, because the
17317 underlying function is non-privileged due to lack of support in MS-Windows.
17318 Furthermore, the @command{chroot} command avoids the @code{chroot} system call
17319 when @var{newroot} is identical to the old @file{/} directory for consistency
17320 with systems where this is allowed for non-privileged users.}.
17324 chroot @var{option} @var{newroot} [@var{command} [@var{args}]@dots{}]
17325 chroot @var{option}
17328 Ordinarily, file names are looked up starting at the root of the
17329 directory structure, i.e., @file{/}. @command{chroot} changes the root to
17330 the directory @var{newroot} (which must exist), then changes the working
17331 directory to @file{/}, and finally runs @var{command} with optional @var{args}.
17332 If @var{command} is not specified, the default is the value of the @env{SHELL}
17333 environment variable or @command{/bin/sh} if not set, invoked with the
17334 @option{-i} option.
17335 @var{command} must not be a special built-in utility
17336 (@pxref{Special built-in utilities}).
17338 The program accepts the following options. Also see @ref{Common options}.
17339 Options must precede operands.
17343 @item --groups=@var{groups}
17345 Use this option to override the supplementary @var{groups} to be
17346 used by the new process.
17347 The items in the list (names or numeric IDs) must be separated by commas.
17348 Use @samp{--groups=''} to disable the supplementary group look-up
17349 implicit in the @option{--userspec} option.
17351 @item --userspec=@var{user}[:@var{group}]
17352 @opindex --userspec
17353 By default, @var{command} is run with the same credentials
17354 as the invoking process.
17355 Use this option to run it as a different @var{user} and/or with a
17356 different primary @var{group}.
17357 If a @var{user} is specified then the supplementary groups
17358 are set according to the system defined list for that user,
17359 unless overridden with the @option{--groups} option.
17362 @opindex --skip-chdir
17363 Use this option to not change the working directory to @file{/} after changing
17364 the root directory to @var{newroot}, i.e., inside the chroot.
17365 This option is only permitted when @var{newroot} is the old @file{/} directory,
17366 and therefore is mostly useful together with the @option{--groups} and
17367 @option{--userspec} options to retain the previous working directory.
17371 The user and group name look-up performed by the @option{--userspec}
17372 and @option{--groups} options, is done both outside and inside
17373 the chroot, with successful look-ups inside the chroot taking precedence.
17374 If the specified user or group items are intended to represent a numeric ID,
17375 then a name to ID resolving step is avoided by specifying a leading @samp{+}.
17376 @xref{Disambiguating names and IDs}.
17378 Here are a few tips to help avoid common problems in using chroot.
17379 To start with a simple example, make @var{command} refer to a statically
17380 linked binary. If you were to use a dynamically linked executable, then
17381 you'd have to arrange to have the shared libraries in the right place under
17382 your new root directory.
17384 For example, if you create a statically linked @command{ls} executable,
17385 and put it in @file{/tmp/empty}, you can run this command as root:
17388 $ chroot /tmp/empty /ls -Rl /
17391 Then you'll see output like this:
17396 -rwxr-xr-x 1 0 0 1041745 Aug 16 11:17 ls
17399 If you want to use a dynamically linked executable, say @command{bash},
17400 then first run @samp{ldd bash} to see what shared objects it needs.
17401 Then, in addition to copying the actual binary, also copy the listed
17402 files to the required positions under your intended new root directory.
17403 Finally, if the executable requires any other files (e.g., data, state,
17404 device files), copy them into place, too.
17406 @command{chroot} is installed only on systems that have the
17407 @code{chroot} function, so portable scripts should not rely on its
17410 @cindex exit status of @command{chroot}
17414 125 if @command{chroot} itself fails
17415 126 if @var{command} is found but cannot be invoked
17416 127 if @var{command} cannot be found
17417 the exit status of @var{command} otherwise
17421 @node env invocation
17422 @section @command{env}: Run a command in a modified environment
17425 @cindex environment, running a program in a modified
17426 @cindex modified environment, running a program in a
17427 @cindex running a program in a modified environment
17429 @command{env} runs a command with a modified environment. Synopses:
17432 env [@var{option}]@dots{} [@var{name}=@var{value}]@dots{} @c
17433 [@var{command} [@var{args}]@dots{}]
17434 env -[v]S'[@var{option}]@dots{} [@var{name}=@var{value}]@dots{} @c
17435 [@var{command} [@var{args}]@dots{}]'
17439 @command{env} is commonly used on first line of scripts (shebang line):
17441 #!/usr/bin/env @var{command}
17442 #!/usr/bin/env -[v]S[@var{option}]@dots{} [@var{name}=@var{value}]@dots{} @c
17443 @var{command} [@var{args}]@dots{}
17446 Operands of the form @samp{@var{variable}=@var{value}} set
17447 the environment variable @var{variable} to value @var{value}.
17448 @var{value} may be empty (@samp{@var{variable}=}). Setting a variable
17449 to an empty value is different from unsetting it.
17450 These operands are evaluated left-to-right, so if two operands
17451 mention the same variable the earlier is ignored.
17453 Environment variable names can be empty, and can contain any
17454 characters other than @samp{=} and ASCII NUL.
17455 However, it is wise to limit yourself to names that
17456 consist solely of underscores, digits, and ASCII letters,
17457 and that begin with a non-digit, as applications like the shell do not
17458 work well with other names.
17461 The first operand that does not contain the character @samp{=}
17462 specifies the program to invoke; it is
17463 searched for according to the @env{PATH} environment variable. Any
17464 remaining arguments are passed as arguments to that program.
17465 The program should not be a special built-in utility
17466 (@pxref{Special built-in utilities}).
17468 Modifications to @env{PATH} take effect prior to searching for
17469 @var{command}. Use caution when reducing @env{PATH}; behavior is
17470 not portable when @env{PATH} is undefined or omits key directories
17471 such as @file{/bin}.
17473 In the rare case that a utility contains a @samp{=} in the name, the
17474 only way to disambiguate it from a variable assignment is to use an
17475 intermediate command for @var{command}, and pass the problematic
17476 program name via @var{args}. For example, if @file{./prog=} is an
17477 executable in the current @env{PATH}:
17480 env prog= true # runs 'true', with prog= in environment
17481 env ./prog= true # runs 'true', with ./prog= in environment
17482 env -- prog= true # runs 'true', with prog= in environment
17483 env sh -c '\prog= true' # runs 'prog=' with argument 'true'
17484 env sh -c 'exec "$@@"' sh prog= true # also runs 'prog='
17487 @cindex environment, printing
17489 If no command name is specified following the environment
17490 specifications, the resulting environment is printed. This is like
17491 specifying the @command{printenv} program.
17493 For some examples, suppose the environment passed to @command{env}
17494 contains @samp{LOGNAME=rms}, @samp{EDITOR=emacs}, and
17495 @samp{PATH=.:/gnubin:/hacks}:
17500 Output the current environment.
17502 $ env | LC_ALL=C sort
17505 PATH=.:/gnubin:/hacks
17509 Run @command{foo} with a reduced environment, preserving only the
17510 original @env{PATH} to avoid problems in locating @command{foo}.
17512 env - PATH="$PATH" foo
17516 Run @command{foo} with the environment containing @samp{LOGNAME=rms},
17517 @samp{EDITOR=emacs}, and @samp{PATH=.:/gnubin:/hacks}, and guarantees
17518 that @command{foo} was found in the file system rather than as a shell
17525 Run @command{nemacs} with the environment containing @samp{LOGNAME=foo},
17526 @samp{EDITOR=emacs}, @samp{PATH=.:/gnubin:/hacks}, and
17527 @samp{DISPLAY=gnu:0}.
17529 env DISPLAY=gnu:0 LOGNAME=foo nemacs
17533 Attempt to run the program @command{/energy/--} (as that is the only
17534 possible path search result); if the command exists, the environment
17535 will contain @samp{LOGNAME=rms} and @samp{PATH=/energy}, and the
17536 arguments will be @samp{e=mc2}, @samp{bar}, and @samp{baz}.
17538 env -u EDITOR PATH=/energy -- e=mc2 bar baz
17544 @subsection General options
17546 The program accepts the following options. Also see @ref{Common options}.
17547 Options must precede operands.
17553 @item -u @var{name}
17554 @itemx --unset=@var{name}
17557 Remove variable @var{name} from the environment, if it was in the
17562 @itemx --ignore-environment
17565 @opindex --ignore-environment
17566 Start with an empty environment, ignoring the inherited environment.
17569 @itemx --chdir=@var{dir}
17572 Change the working directory to @var{dir} before invoking @var{command}.
17573 This differs from the shell built-in @command{cd} in that it starts
17574 @var{command} as a subprocess rather than altering the shell's own working
17575 directory; this allows it to be chained with other commands that run commands
17576 in a different context. For example:
17579 # Run 'true' with /chroot as its root directory and /srv as its working
17581 chroot /chroot env --chdir=/srv true
17582 # Run 'true' with /build as its working directory, FOO=bar in its
17583 # environment, and a time limit of five seconds.
17584 env --chdir=/build FOO=bar timeout 5 true
17587 @item --default-signal[=@var{sig}]
17588 Unblock and reset signal @var{sig} to its default signal handler.
17589 Without @var{sig} all known signals are unblocked and reset to their defaults.
17590 Multiple signals can be comma-separated. An empty @var{sig} argument is a no-op.
17591 The following command runs @command{seq} with SIGINT and SIGPIPE set to their
17592 default (which is to terminate the program):
17595 env --default-signal=PIPE,INT seq 1000 | head -n1
17598 In the following example, we see how this is not
17599 possible to do with traditional shells.
17600 Here the first trap command sets SIGPIPE to ignore.
17601 The second trap command ostensibly sets it back to its default,
17602 but POSIX mandates that the shell must not change inherited
17603 state of the signal - so it is a no-op.
17606 trap '' PIPE && sh -c 'trap - PIPE ; seq inf | head -n1'
17609 Using @option{--default-signal=PIPE} we can
17610 ensure the signal handling is set to its default behavior:
17613 trap '' PIPE && sh -c 'env --default-signal=PIPE seq inf | head -n1'
17617 @item --ignore-signal[=@var{sig}]
17618 Ignore signal @var{sig} when running a program. Without @var{sig} all
17619 known signals are set to ignore. Multiple signals can be comma-separated.
17620 An empty @var{sig} argument is a no-op. The following command runs @command{seq}
17621 with SIGINT set to be ignored - pressing @kbd{Ctrl-C} will not terminate it:
17624 env --ignore-signal=INT seq inf > /dev/null
17627 @samp{SIGCHLD} is special, in that @option{--ignore-signal=CHLD} might have
17628 no effect (POSIX says it's unspecified).
17630 Most operating systems do not allow ignoring @samp{SIGKILL}, @samp{SIGSTOP}
17631 (and possibly other signals). Attempting to ignore these signals will fail.
17633 Multiple (and contradictory) @option{--default-signal=SIG} and
17634 @option{--ignore-signal=SIG} options are processed left-to-right,
17635 with the latter taking precedence. In the following example, @samp{SIGPIPE} is
17636 set to default while @samp{SIGINT} is ignored:
17639 env --default-signal=INT,PIPE --ignore-signal=INT
17642 @item --block-signal[=@var{sig}]
17643 Block signal(s) @var{sig} from being delivered. Without @var{sig} all
17644 known signals are set to blocked. Multiple signals can be comma-separated.
17645 An empty @var{sig} argument is a no-op.
17647 @item --list-signal-handling
17648 List blocked or ignored signals to standard error, before executing a command.
17654 Show verbose information for each processing step.
17657 $ env -v -uTERM A=B uname -s
17666 When combined with @option{-S} it is recommended to list @option{-v}
17667 first, e.g. @command{env -vS'string'}.
17669 @item -S @var{string}
17670 @itemx --split-string=@var{string}
17672 @opindex --split-string
17673 @cindex shebang arguments
17674 @cindex scripts arguments
17675 @cindex env in scripts
17676 process and split @var{string} into separate arguments used to pass
17677 multiple arguments on shebang lines. @command{env} supports FreeBSD's
17678 syntax of several escape sequences and environment variable
17679 expansions. See below for details and examples.
17683 @cindex exit status of @command{env}
17687 0 if no @var{command} is specified and the environment is output
17688 125 if @command{env} itself fails
17689 126 if @var{command} is found but cannot be invoked
17690 127 if @var{command} cannot be found
17691 the exit status of @var{command} otherwise
17694 @subsection @option{-S}/@option{--split-string} usage in scripts
17696 The @option{-S}/@option{--split-string} option enables use of multiple
17697 arguments on the first line of scripts (the shebang line, @samp{#!}).
17699 When a script's interpreter is in a known location, scripts typically
17700 contain the absolute file name in their first line:
17702 @multitable {Python Script:} {#!/usr/bin/python3}
17703 @item Shell script:
17717 @item Python script:
17726 When a script's interpreter is in a non-standard location
17727 in the @env{PATH} environment variable, it is recommended
17728 to use @command{env} on the first line of the script to
17729 find the executable and run it:
17731 @multitable {Python Script:} {#!/usr/bin/env python3}
17732 @item Shell script:
17735 #!/usr/bin/env bash
17742 #!/usr/bin/env perl
17746 @item Python script:
17749 #!/usr/bin/env python3
17755 Most operating systems (e.g. GNU/Linux, BSDs) treat all text after the
17756 first space as a single argument. When using @command{env} in a script
17757 it is thus not possible to specify multiple arguments.
17759 In the following example:
17761 #!/usr/bin/env perl -T -w
17765 The operating system treats @samp{perl -T -w} as one argument (the
17766 program's name), and executing the script fails with:
17769 /usr/bin/env: 'perl -T -w': No such file or directory
17772 The @option{-S} option instructs @command{env} to split the single string
17773 into multiple arguments. The following example works as expected:
17777 #!/usr/bin/env -S perl -T -w
17780 $ chmod a+x hello.pl
17785 And is equivalent to running @command{perl -T -w hello.pl} on the command line
17788 @unnumberedsubsubsec Testing and troubleshooting
17790 @cindex single quotes, and @command{env -S}
17791 @cindex @command{env -S}, and single quotes
17792 @cindex @option{-S}, env and single quotes
17793 To test @command{env -S} on the command line, use single quotes for the
17794 @option{-S} string to emulate a single paramter. Single quotes are not
17795 needed when using @command{env -S} in a shebang line on the first line of a
17796 script (the operating system already treats it as one argument).
17798 The following command is equivalent to the @file{hello.pl} script above:
17801 $ env -S'perl -T -w' hello.pl
17804 @cindex @command{env -S}, debugging
17805 @cindex debugging, @command{env -S}
17807 To troubleshoot @option{-S} usage add the @option{-v} as the first
17808 argument (before @option{-S}).
17810 Using @option{-vS} on a shebang line in a script:
17813 $ cat hello-debug.pl
17814 #!/usr/bin/env -vS perl -T -w
17817 $ chmod a+x hello-debug.pl
17819 split -S: 'perl -T -w'
17827 arg[3]= './hello-debug.pl'
17831 Using @option{-vS} on the command line prompt (adding single quotes):
17834 $ env -vS'perl -T -w' hello-debug.pl
17835 split -S: 'perl -T -w'
17843 arg[3]= 'hello-debug.pl'
17847 @subsection @option{-S}/@option{--split-string} syntax
17849 @unnumberedsubsubsec Splitting arguments by whitespace
17851 Running @command{env -Sstring} splits the @var{string} into
17852 arguments based on unquoted spaces or tab characters.
17853 (Newlines, carriage returns, vertical tabs and form feeds are treated
17854 like spaces and tabs.)
17856 In the following contrived example the @command{awk} variable
17857 @samp{OFS} will be @code{<space>xyz<space>} as these spaces are inside
17858 double quotes. The other space characters are used as argument separators:
17862 #!/usr/bin/env -S awk -v OFS=" xyz " -f
17863 BEGIN @{print 1,2,3@}
17865 $ chmod a+x one.awk
17870 When using @option{-S} on the command line prompt, remember to add
17871 single quotes around the entire string:
17874 $ env -S'awk -v OFS=" xyz " -f' one.awk
17878 @unnumberedsubsubsec Escape sequences
17880 @command{env} supports several escape sequences. These sequences
17881 are processed when unquoted or inside double quotes (unless otherwise noted).
17882 Single quotes disable escape sequences except @samp{\'} and @samp{\\}.
17884 @multitable @columnfractions .10 .90
17887 @tab Ignore the remaining characters in the string.
17888 Cannot be used inside double quotes.
17891 @tab form-feed character (ASCII 0x0C)
17894 @tab new-line character (ASCII 0x0A)
17897 @tab carriage-return character (ASCII 0x0D)
17900 @tab tab character (ASCII 0x09)
17903 @tab vertical tab character (ASCII 0x0B)
17906 @tab A hash @samp{#} character. Used when a @samp{#} character
17907 is needed as the first character of an argument (see 'comments' section
17911 @tab A dollar-sign character @samp{$}. Unescaped @samp{$} characters
17912 are used to expand environment variables (see 'variables' section below).
17915 @tab Inside double-quotes, replaced with a single space character.
17916 Outside quotes, treated as an argument separator. @samp{\_} can be used
17917 to avoid space characters in a shebang line (see examples below).
17920 @tab A double-quote character.
17923 @tab A single-quote character.
17924 This escape sequence works inside single-quoted strings.
17927 @tab A backslash character.
17928 This escape sequence works inside single-quoted strings.
17932 The following @command{awk} script will use tab character as input and output
17933 field separator (instead of spaces and tabs):
17937 #!/usr/bin/env -S awk -v FS="\t" -v OFS="\t" -f
17941 @unnumberedsubsubsec Comments
17943 The escape sequence @samp{\c} (used outside single/double quotes)
17944 causes @command{env} to ignore the rest of the string.
17946 The @samp{#} character causes @command{env} to ignore the rest of
17947 the string when it appears as the first character of an argument.
17948 Use @samp{\#} to reverse this behavior.
17951 $ env -S'printf %s\n A B C'
17956 $ env -S'printf %s\n A# B C'
17961 $ env -S'printf %s\n A #B C'
17964 $ env -S'printf %s\n A \#B C'
17969 $ env -S'printf %s\n A\cB C'
17973 NOTE: The above examples use single quotes as they are executed
17974 on the command-line.
17978 @unnumberedsubsubsec Environment variable expansion
17980 The pattern @samp{$@{VARNAME@}} is used to substitute a value from
17981 the environment variable. The pattern must include the curly braces
17982 (@samp{@{},@samp{@}}). Without them @command{env} will reject the string.
17983 Special shell variables (such as @samp{$@@}, @samp{$*}, @samp{$$}) are
17986 If the environment variable is empty or not set, the pattern will be replaced
17987 by an empty string. The value of @samp{$@{VARNAME@}} will be that of
17988 the executed @command{env}, before any modifications using
17989 @option{-i}/@option{--ignore-environment}/@option{-u}/@option{--unset} or
17990 setting new values using @samp{VAR=VALUE}.
17992 The following python script prepends @file{/opt/custom/modules} to the python
17993 module search path environment variable (@samp{PYTHONPATH}):
17997 #!/usr/bin/env -S PYTHONPATH=/opt/custom/modules/:$@{PYTHONPATH@} python
18002 The expansion of @samp{$@{PYTHONPATH@}} is performed by @command{env},
18003 not by a shell. If the curly braces are omitted, @command{env} will fail:
18007 #!/usr/bin/env -S PYTHONPATH=/opt/custom/modules/:$PYTHONPATH python
18011 $ chmod a+x custom.py
18013 /usr/bin/env: only $@{VARNAME@} expansion is supported, error at: $PYTHONPATH @c
18017 Environment variable expansion happens before clearing the environment
18018 (with @option{-i}) or unsetting specific variables (with @option{-u}):
18021 $ env -S'-i OLDUSER=$@{USER@} env'
18025 Use @option{-v} to diagnose the operations step-by-step:
18028 $ env -vS'-i OLDUSER=$@{USER@} env'
18029 expanding $@{USER@} into 'gordon'
18030 split -S: '-i OLDUSER=$@{USER@} env'
18035 setenv: OLDUSER=gordon
18043 @node nice invocation
18044 @section @command{nice}: Run a command with modified niceness
18048 @cindex scheduling, affecting
18049 @cindex appropriate privileges
18051 @command{nice} prints a process's @dfn{niceness}, or runs
18052 a command with modified niceness. @dfn{niceness} affects how
18053 favorably the process is scheduled in the system.
18057 nice [@var{option}]@dots{} [@var{command} [@var{arg}]@dots{}]
18060 If no arguments are given, @command{nice} prints the current niceness.
18061 Otherwise, @command{nice} runs the given @var{command} with its
18062 niceness adjusted. By default, its niceness is incremented by 10.
18064 Niceness values range at least from @minus{}20 (process has high priority
18065 and gets more resources, thus slowing down other processes) through 19
18066 (process has lower priority and runs slowly itself, but has less impact
18067 on the speed of other running processes). Some systems
18068 may have a wider range of niceness values; conversely, other systems may
18069 enforce more restrictive limits. An attempt to set the niceness
18070 outside the supported range is treated as an attempt to use the
18071 minimum or maximum supported value.
18073 A niceness should not be confused with a scheduling priority, which
18074 lets applications determine the order in which threads are scheduled
18075 to run. Unlike a priority, a niceness is merely advice to the
18076 scheduler, which the scheduler is free to ignore. Also, as a point of
18077 terminology, POSIX defines the behavior of @command{nice} in
18078 terms of a @dfn{nice value}, which is the non-negative difference
18079 between a niceness and the minimum niceness. Though @command{nice}
18080 conforms to POSIX, its documentation and diagnostics use the
18081 term ``niceness'' for compatibility with historical practice.
18083 @var{command} must not be a special built-in utility (@pxref{Special
18084 built-in utilities}).
18086 @mayConflictWithShellBuiltIn{nice}
18088 Note to change the @dfn{niceness} of an existing process,
18089 one needs to use the @command{renice} command.
18091 The program accepts the following option. Also see @ref{Common options}.
18092 Options must precede operands.
18095 @item -n @var{adjustment}
18096 @itemx --adjustment=@var{adjustment}
18098 @opindex --adjustment
18099 Add @var{adjustment} instead of 10 to the command's niceness. If
18100 @var{adjustment} is negative and you lack appropriate privileges,
18101 @command{nice} issues a warning but otherwise acts as if you specified
18104 For compatibility @command{nice} also supports an obsolete
18105 option syntax @option{-@var{adjustment}}. New scripts should use
18106 @option{-n @var{adjustment}} instead.
18110 @command{nice} is installed only on systems that have the POSIX
18111 @code{setpriority} function, so portable scripts should not rely on
18112 its existence on non-POSIX platforms.
18114 @cindex exit status of @command{nice}
18118 0 if no @var{command} is specified and the niceness is output
18119 125 if @command{nice} itself fails
18120 126 if @var{command} is found but cannot be invoked
18121 127 if @var{command} cannot be found
18122 the exit status of @var{command} otherwise
18125 It is sometimes useful to run a non-interactive program with reduced niceness.
18128 $ nice factor 4611686018427387903
18131 Since @command{nice} prints the current niceness,
18132 you can invoke it through itself to demonstrate how it works.
18134 The default behavior is to increase the niceness by @samp{10}:
18145 The @var{adjustment} is relative to the current niceness. In the
18146 next example, the first @command{nice} invocation runs the second one
18147 with niceness 10, and it in turn runs the final one with a niceness
18151 $ nice nice -n 3 nice
18155 Specifying a niceness larger than the supported range
18156 is the same as specifying the maximum supported value:
18159 $ nice -n 10000000000 nice
18163 Only a privileged user may run a process with lower niceness:
18167 nice: cannot set niceness: Permission denied
18169 $ sudo nice -n -1 nice
18174 @node nohup invocation
18175 @section @command{nohup}: Run a command immune to hangups
18178 @cindex hangups, immunity to
18179 @cindex immunity to hangups
18180 @cindex logging out and continuing to run
18183 @command{nohup} runs the given @var{command} with hangup signals ignored,
18184 so that the command can continue running in the background after you log
18188 nohup @var{command} [@var{arg}]@dots{}
18191 If standard input is a terminal, redirect it so that terminal sessions
18192 do not mistakenly consider the terminal to be used by the command.
18193 Make the substitute file descriptor unreadable, so that commands that
18194 mistakenly attempt to read from standard input can report an error.
18195 This redirection is a GNU extension; programs intended to be portable
18196 to non-GNU hosts can use @samp{nohup @var{command} [@var{arg}]@dots{}
18197 0>/dev/null} instead.
18200 If standard output is a terminal, the command's standard output is appended
18201 to the file @file{nohup.out}; if that cannot be written to, it is appended
18202 to the file @file{$HOME/nohup.out}; and if that cannot be written to, the
18203 command is not run.
18204 Any @file{nohup.out} or @file{$HOME/nohup.out} file created by
18205 @command{nohup} is made readable and writable only to the user,
18206 regardless of the current umask settings.
18208 If standard error is a terminal, it is normally redirected to the same file
18209 descriptor as the (possibly-redirected) standard output.
18210 However, if standard output is closed, standard error terminal output
18211 is instead appended to the file @file{nohup.out} or
18212 @file{$HOME/nohup.out} as above.
18214 To capture the command's output to a file other than @file{nohup.out}
18215 you can redirect it. For example, to capture the output of
18219 nohup make > make.log
18222 @command{nohup} does not automatically put the command it runs in the
18223 background; you must do that explicitly, by ending the command line
18224 with an @samp{&}. Also, @command{nohup} does not alter the
18225 niceness of @var{command}; use @command{nice} for that,
18226 e.g., @samp{nohup nice @var{command}}.
18228 @var{command} must not be a special built-in utility (@pxref{Special
18229 built-in utilities}).
18231 The only options are @option{--help} and @option{--version}. @xref{Common
18232 options}. Options must precede operands.
18234 @cindex exit status of @command{nohup}
18238 125 if @command{nohup} itself fails, and @env{POSIXLY_CORRECT} is not set
18239 126 if @var{command} is found but cannot be invoked
18240 127 if @var{command} cannot be found
18241 the exit status of @var{command} otherwise
18244 If @env{POSIXLY_CORRECT} is set, internal failures give status 127
18248 @node stdbuf invocation
18249 @section @command{stdbuf}: Run a command with modified I/O stream buffering
18252 @cindex standard streams, buffering
18253 @cindex line buffered
18255 @command{stdbuf} allows one to modify the buffering operations of the
18256 three standard I/O streams associated with a program. Synopsis:
18259 stdbuf @var{option}@dots{} @var{command}
18262 @var{command} must start with the name of a program that
18265 uses the ISO C @code{FILE} streams for input/output (note the
18266 programs @command{dd} and @command{cat} don't do that),
18269 does not adjust the buffering of its standard streams (note the
18270 program @command{tee} is not in this category).
18273 Any additional @var{arg}s are passed as additional arguments to the
18276 The program accepts the following options. Also see @ref{Common options}.
18280 @item -i @var{mode}
18281 @itemx --input=@var{mode}
18284 Adjust the standard input stream buffering.
18286 @item -o @var{mode}
18287 @itemx --output=@var{mode}
18290 Adjust the standard output stream buffering.
18292 @item -e @var{mode}
18293 @itemx --error=@var{mode}
18296 Adjust the standard error stream buffering.
18300 The @var{mode} can be specified as follows:
18305 Set the stream to line buffered mode.
18306 In this mode data is coalesced until a newline is output or
18307 input is read from any stream attached to a terminal device.
18308 This option is invalid with standard input.
18311 Disable buffering of the selected stream.
18312 In this mode, data is output immediately and only the
18313 amount of data requested is read from input.
18314 Note the difference in function for input and output.
18315 Disabling buffering for input will not influence the responsiveness
18316 or blocking behavior of the stream input functions.
18317 For example @code{fread} will still block until @code{EOF} or error,
18318 even if the underlying @code{read} returns less data than requested.
18321 Specify the size of the buffer to use in fully buffered mode.
18322 @multiplierSuffixesNoBlocks{size}
18326 @command{stdbuf} is installed only on platforms that use the
18327 Executable and Linkable Format (ELF) and support the
18328 @code{constructor} attribute, so portable scripts should not rely on
18331 @cindex exit status of @command{stdbuf}
18335 125 if @command{stdbuf} itself fails
18336 126 if @var{command} is found but cannot be invoked
18337 127 if @var{command} cannot be found
18338 the exit status of @var{command} otherwise
18342 @node timeout invocation
18343 @section @command{timeout}: Run a command with a time limit
18347 @cindex run commands with bounded time
18349 @command{timeout} runs the given @var{command} and kills it if it is
18350 still running after the specified time interval. Synopsis:
18353 timeout [@var{option}] @var{duration} @var{command} [@var{arg}]@dots{}
18356 @var{command} must not be a special built-in utility (@pxref{Special
18357 built-in utilities}).
18359 The program accepts the following options. Also see @ref{Common options}.
18360 Options must precede operands.
18363 @item --preserve-status
18364 @opindex --preserve-status
18365 Return the exit status of the managed @var{command} on timeout, rather than
18366 a specific exit status indicating a timeout. This is useful if the
18367 managed @var{command} supports running for an indeterminate amount of time.
18370 @opindex --foreground
18371 Don't create a separate background program group, so that
18372 the managed @var{command} can use the foreground TTY normally.
18373 This is needed to support two situations when timing out commands,
18374 when not invoking @command{timeout} from an interactive shell.
18377 @var{command} is interactive and needs to read from the terminal for example
18379 the user wants to support sending signals directly to @var{command}
18380 from the terminal (like Ctrl-C for example)
18383 Note in this mode of operation, any children of @var{command}
18384 will not be timed out. Also SIGCONT will not be sent to @var{command},
18385 as it's generally not needed with foreground processes, and can
18386 cause intermittent signal delivery issues with programs that are monitors
18387 themselves (like GDB for example).
18389 @item -k @var{duration}
18390 @itemx --kill-after=@var{duration}
18392 @opindex --kill-after
18393 Ensure the monitored @var{command} is killed by also sending a @samp{KILL}
18396 The specified @var{duration} starts from the point in time when
18397 @command{timeout} sends the initial signal to @var{command}, i.e.,
18398 not from the beginning when the @var{command} is started.
18400 This option has no effect if either the main @var{duration}
18401 of the @command{timeout} command, or the @var{duration} specified
18402 to this option, is 0.
18404 This option may be useful if the selected signal did not kill the @var{command},
18405 either because the signal was blocked or ignored, or if the @var{command} takes
18406 too long (e.g. for cleanup work) to terminate itself within a certain amount
18409 @item -s @var{signal}
18410 @itemx --signal=@var{signal}
18413 Send this @var{signal} to @var{command} on timeout, rather than the
18414 default @samp{TERM} signal. @var{signal} may be a name like @samp{HUP}
18415 or a number. @xref{Signal specifications}.
18421 Diagnose to standard error, any signal sent upon timeout.
18425 @var{duration} is a floating point number in either the current or the
18426 C locale (@pxref{Floating point}) followed by an optional unit:
18428 @samp{s} for seconds (the default)
18429 @samp{m} for minutes
18433 A duration of 0 disables the associated timeout.
18434 Note that the actual timeout duration is dependent on system conditions,
18435 which should be especially considered when specifying sub-second timeouts.
18437 @cindex exit status of @command{timeout}
18441 124 if @var{command} times out, and @option{--preserve-status} is not specified
18442 125 if @command{timeout} itself fails
18443 126 if @var{command} is found but cannot be invoked
18444 127 if @var{command} cannot be found
18445 137 if @var{command} or @command{timeout} is sent the KILL(9) signal (128+9)
18446 the exit status of @var{command} otherwise
18449 In the case of the @samp{KILL(9)} signal, @command{timeout} returns with
18450 exit status 137, regardless of whether that signal is sent to @var{command}
18451 or to @command{timeout} itself, i.e., these cases cannot be distinguished.
18452 In the latter case, the @var{command} process may still be alive after
18453 @command{timeout} has forcefully been terminated.
18458 # Send the default TERM signal after 20s to a short-living 'sleep 1'.
18459 # As that terminates long before the given duration, 'timeout' returns
18460 # with the same exit status as the command, 0 in this case.
18463 # Send the INT signal after 5s to the 'sleep' command. Returns after
18464 # 5 seconds with exit status 124 to indicate the sending of the signal.
18465 timeout -s INT 5 sleep 20
18467 # Likewise, but the command ignoring the INT signal due to being started
18468 # via 'env --ignore-signal'. Thus, 'sleep' terminates regularly after
18469 # the full 20 seconds, still 'timeout' returns with exit status 124.
18470 timeout -s INT 5s env --ignore-signal=INT sleep 20
18472 # Likewise, but sending the KILL signal 3 seconds after the initial
18473 # INT signal. Hence, 'sleep' is forcefully terminated after about
18474 # 8 seconds (5+3), and 'timeout' returns with an exit status of 137.
18475 timeout -s INT -k 3s 5s env --ignore-signal=INT sleep 20
18478 @node Process control
18479 @chapter Process control
18481 @cindex processes, commands for controlling
18482 @cindex commands for controlling processes
18485 * kill invocation:: Sending a signal to processes.
18489 @node kill invocation
18490 @section @command{kill}: Send a signal to processes
18493 @cindex send a signal to processes
18495 The @command{kill} command sends a signal to processes, causing them
18496 to terminate or otherwise act upon receiving the signal in some way.
18497 Alternatively, it lists information about signals. Synopses:
18500 kill [-s @var{signal} | --signal @var{signal} | -@var{signal}] @var{pid}@dots{}
18501 kill [-l | --list | -t | --table] [@var{signal}]@dots{}
18504 @mayConflictWithShellBuiltIn{kill}
18506 The first form of the @command{kill} command sends a signal to all
18507 @var{pid} arguments. The default signal to send if none is specified
18508 is @samp{TERM}@. The special signal number @samp{0} does not denote a
18509 valid signal, but can be used to test whether the @var{pid} arguments
18510 specify processes to which a signal could be sent.
18512 If @var{pid} is positive, the signal is sent to the process with the
18513 process ID @var{pid}. If @var{pid} is zero, the signal is sent to all
18514 processes in the process group of the current process. If @var{pid}
18515 is @minus{}1, the signal is sent to all processes for which the user has
18516 permission to send a signal. If @var{pid} is less than @minus{}1, the signal
18517 is sent to all processes in the process group that equals the absolute
18518 value of @var{pid}.
18520 If @var{pid} is not positive, a system-dependent set of system
18521 processes is excluded from the list of processes to which the signal
18524 If a negative @var{pid} argument is desired as the first one, it
18525 should be preceded by @option{--}. However, as a common extension to
18526 POSIX, @option{--} is not required with @samp{kill
18527 -@var{signal} -@var{pid}}. The following commands are equivalent:
18536 The first form of the @command{kill} command succeeds if every @var{pid}
18537 argument specifies at least one process that the signal was sent to.
18539 The second form of the @command{kill} command lists signal information.
18540 Either the @option{-l} or @option{--list} option, or the @option{-t}
18541 or @option{--table} option must be specified. Without any
18542 @var{signal} argument, all supported signals are listed. The output
18543 of @option{-l} or @option{--list} is a list of the signal names, one
18544 per line; if @var{signal} is already a name, the signal number is
18545 printed instead. The output of @option{-t} or @option{--table} is a
18546 table of signal numbers, names, and descriptions. This form of the
18547 @command{kill} command succeeds if all @var{signal} arguments are valid
18548 and if there is no output error.
18550 The @command{kill} command also supports the @option{--help} and
18551 @option{--version} options. @xref{Common options}.
18553 A @var{signal} may be a signal name like @samp{HUP}, or a signal
18554 number like @samp{1}, or an exit status of a process terminated by the
18555 signal. A signal name can be given in canonical form or prefixed by
18556 @samp{SIG}@. The case of the letters is ignored, except for the
18557 @option{-@var{signal}} option which must use upper case to avoid
18558 ambiguity with lower case option letters.
18559 @xref{Signal specifications}, for a list of supported
18560 signal names and numbers.
18565 @cindex delaying commands
18566 @cindex commands for delaying
18568 @c Perhaps @command{wait} or other commands should be described here also?
18571 * sleep invocation:: Delay for a specified time.
18575 @node sleep invocation
18576 @section @command{sleep}: Delay for a specified time
18579 @cindex delay for a specified time
18581 @command{sleep} pauses for an amount of time specified by the sum of
18582 the values of the command line arguments.
18586 sleep @var{number}[smhd]@dots{}
18590 Each argument is a non-negative number followed by an optional unit; the default
18591 is seconds. The units are:
18604 Although portable POSIX scripts must give @command{sleep} a single
18605 non-negative integer argument without a suffix, GNU @command{sleep}
18606 also accepts two or more arguments, unit suffixes, and floating-point
18607 numbers in either the current or the C locale. @xref{Floating point}.
18609 For instance, the following could be used to @command{sleep} for
18610 1 second, 234 milli-, 567 micro- and 890 nanoseconds:
18613 sleep 1234e-3 567.89e-6
18616 Also one could sleep indefinitely like:
18622 The only options are @option{--help} and @option{--version}. @xref{Common
18625 @c sleep is a shell built-in at least with Solaris 11's /bin/sh
18626 @mayConflictWithShellBuiltIn{sleep}
18631 @node Numeric operations
18632 @chapter Numeric operations
18634 @cindex numeric operations
18635 These programs do numerically-related operations.
18638 * factor invocation:: Show factors of numbers.
18639 * numfmt invocation:: Reformat numbers.
18640 * seq invocation:: Print sequences of numbers.
18644 @node factor invocation
18645 @section @command{factor}: Print prime factors
18648 @cindex prime factors
18650 @command{factor} prints prime factors. Synopsis:
18653 factor [@var{option}]@dots{} [@var{number}]@dots{}
18656 If no @var{number} is specified on the command line, @command{factor} reads
18657 numbers from standard input, delimited by newlines, tabs, or spaces.
18659 The program accepts the following options. Also see @ref{Common options}.
18665 @opindex --exponents
18666 print factors in the form @math{p^e}, rather than repeating
18667 the prime @samp{p}, @samp{e} times. If the exponent @samp{e} is 1,
18668 then it is omitted.
18671 $ factor --exponents 3000
18676 If the number to be factored is small (less than @math{2^{127}} on
18677 typical machines), @command{factor} uses a faster algorithm.
18678 For example, on a circa-2017 Intel Xeon Silver 4116, factoring the
18679 product of the eighth and ninth Mersenne primes (approximately
18680 @math{2^{92}}) takes about 4 ms of CPU time:
18683 $ M8=$(echo 2^31-1 | bc)
18684 $ M9=$(echo 2^61-1 | bc)
18685 $ n=$(echo "$M8 * $M9" | bc)
18686 $ bash -c "time factor $n"
18687 4951760154835678088235319297: 2147483647 2305843009213693951
18694 For larger numbers, @command{factor} uses a slower algorithm. On the
18695 same platform, factoring the eighth Fermat number @math{2^{256} + 1}
18696 takes about 14 seconds, and the slower algorithm would have taken
18697 about 750 ms to factor @math{2^{127} - 3} instead of the 50 ms needed by
18698 the faster algorithm.
18700 Factoring large numbers is, in general, hard. The Pollard-Brent rho
18701 algorithm used by @command{factor} is particularly effective for
18702 numbers with relatively small factors. If you wish to factor large
18703 numbers which do not have small factors (for example, numbers which
18704 are the product of two large primes), other methods are far better.
18709 @node numfmt invocation
18710 @section @command{numfmt}: Reformat numbers
18714 @command{numfmt} reads numbers in various representations and reformats them
18715 as requested. The most common usage is converting numbers to/from @emph{human}
18716 representation (e.g. @samp{4G} @expansion{} @samp{4,000,000,000}).
18719 numfmt [@var{option}]@dots{} [@var{number}]
18722 @command{numfmt} converts each @var{number} on the command-line according to the
18723 specified options (see below). If no @var{number}s are given, it reads numbers
18724 from standard input. @command{numfmt} can optionally extract numbers from
18725 specific columns, maintaining proper line padding and alignment.
18729 See @option{--invalid} for additional information regarding exit status.
18731 @subsection General options
18733 The program accepts the following options. Also see @ref{Common options}.
18739 Print (to standard error) warning messages about possible erroneous usage.
18742 @itemx --delimiter=@var{d}
18744 @opindex --delimiter
18745 Use the character @var{d} as input field separator (default: whitespace).
18746 @emph{Note}: Using non-default delimiter turns off automatic padding.
18748 @item --field=@var{fields}
18750 Convert the number in input field @var{fields} (default: 1).
18751 @var{fields} supports @command{cut} style field ranges:
18754 N N'th field, counted from 1
18755 N- from N'th field, to end of line
18756 N-M from N'th to M'th field (inclusive)
18757 -M from first to M'th field (inclusive)
18762 @item --format=@var{format}
18764 Use printf-style floating FORMAT string. The @var{format} string must contain
18765 one @samp{%f} directive, optionally with @samp{'}, @samp{-}, @samp{0}, width
18766 or precision modifiers. The @samp{'} modifier will enable @option{--grouping},
18767 the @samp{-} modifier will enable left-aligned @option{--padding} and the width
18768 modifier will enable right-aligned @option{--padding}. The @samp{0} width
18769 modifier (without the @samp{-} modifier) will generate leading zeros on the
18770 number, up to the specified width. A precision specification like @samp{%.1f}
18771 will override the precision determined from the input data or set due to
18772 @option{--to} option auto scaling.
18774 @item --from=@var{unit}
18776 Auto-scales input numbers according to @var{unit}. See UNITS below.
18777 The default is no scaling, meaning suffixes (e.g. @samp{M}, @samp{G}) will
18780 @item --from-unit=@var{n}
18781 @opindex --from-unit
18782 Specify the input unit size (instead of the default 1). Use this option when
18783 the input numbers represent other units (e.g. if the input number @samp{10}
18784 represents 10 units of 512 bytes, use @samp{--from-unit=512}).
18785 Suffixes are handled as with @samp{--from=auto}.
18788 @opindex --grouping
18789 Group digits in output numbers according to the current locale's grouping rules
18790 (e.g @emph{Thousands Separator} character, commonly @samp{.} (dot) or @samp{,}
18791 comma). This option has no effect in @samp{POSIX/C} locale.
18793 @item --header[=@var{n}]
18795 @opindex --header=N
18796 Print the first @var{n} (default: 1) lines without any conversion.
18798 @item --invalid=@var{mode}
18800 The default action on input errors is to exit immediately with status code 2.
18801 @option{--invalid=@samp{abort}} explicitly specifies this default mode.
18802 With a @var{mode} of @samp{fail}, print a warning for @emph{each} conversion
18803 error, and exit with status 2. With a @var{mode} of @samp{warn}, exit with
18804 status 0, even in the presence of conversion errors, and with a @var{mode} of
18805 @samp{ignore} do not even print diagnostics.
18807 @item --padding=@var{n}
18809 Pad the output numbers to @var{n} characters, by adding spaces. If @var{n} is
18810 a positive number, numbers will be right-aligned. If @var{n} is a negative
18811 number, numbers will be left-aligned. By default, numbers are automatically
18812 aligned based on the input line's width (only with the default delimiter).
18814 @item --round=@var{method}
18816 @opindex --round=up
18817 @opindex --round=down
18818 @opindex --round=from-zero
18819 @opindex --round=towards-zero
18820 @opindex --round=nearest
18821 When converting number representations, round the number according to
18822 @var{method}, which can be @samp{up}, @samp{down},
18823 @samp{from-zero} (the default), @samp{towards-zero}, @samp{nearest}.
18825 @item --suffix=@var{suffix}
18827 Add @samp{SUFFIX} to the output numbers, and accept optional @samp{SUFFIX} in
18830 @item --to=@var{unit}
18832 Auto-scales output numbers according to @var{unit}. See @emph{Units} below.
18833 The default is no scaling, meaning all the digits of the number are printed.
18835 @item --to-unit=@var{n}
18837 Specify the output unit size (instead of the default 1). Use this option when
18838 the output numbers represent other units (e.g. to represent @samp{4,000,000}
18839 bytes in blocks of 1KB, use @samp{--to=si --to-unit=1000}).
18840 Suffixes are handled as with @samp{--from=auto}.
18843 @newlineFieldSeparator
18847 @subsection Possible @var{unit}s:
18849 The following are the possible @var{unit} options with @option{--from=UNITS} and
18850 @option{--to=UNITS}:
18855 No scaling is performed. For input numbers, no suffixes are accepted, and any
18856 trailing characters following the number will trigger an error. For output
18857 numbers, all digits of the numbers will be printed.
18860 Auto-scale numbers according to the @emph{International System of Units (SI)}
18862 For input numbers, accept one of the following suffixes.
18863 For output numbers, values larger than 1000 will be rounded, and printed with
18864 one of the following suffixes:
18867 @samp{K} => @math{1000^1 = 10^3} (Kilo)
18868 @samp{M} => @math{1000^2 = 10^6} (Mega)
18869 @samp{G} => @math{1000^3 = 10^9} (Giga)
18870 @samp{T} => @math{1000^4 = 10^{12}} (Tera)
18871 @samp{P} => @math{1000^5 = 10^{15}} (Peta)
18872 @samp{E} => @math{1000^6 = 10^{18}} (Exa)
18873 @samp{Z} => @math{1000^7 = 10^{21}} (Zetta)
18874 @samp{Y} => @math{1000^8 = 10^{24}} (Yotta)
18878 Auto-scale numbers according to the @emph{International Electrotechnical
18879 Commission (IEC)} standard.
18880 For input numbers, accept one of the following suffixes.
18881 For output numbers, values larger than 1024 will be rounded, and printed with
18882 one of the following suffixes:
18885 @samp{K} => @math{1024^1 = 2^{10}} (Kibi)
18886 @samp{M} => @math{1024^2 = 2^{20}} (Mebi)
18887 @samp{G} => @math{1024^3 = 2^{30}} (Gibi)
18888 @samp{T} => @math{1024^4 = 2^{40}} (Tebi)
18889 @samp{P} => @math{1024^5 = 2^{50}} (Pebi)
18890 @samp{E} => @math{1024^6 = 2^{60}} (Exbi)
18891 @samp{Z} => @math{1024^7 = 2^{70}} (Zebi)
18892 @samp{Y} => @math{1024^8 = 2^{80}} (Yobi)
18895 The @option{iec} option uses a single letter suffix (e.g. @samp{G}), which is
18896 not fully standard, as the @emph{iec} standard recommends a two-letter symbol
18897 (e.g @samp{Gi}) - but in practice, this method common. Compare with
18898 the @option{iec-i} option.
18901 Auto-scale numbers according to the @emph{International Electrotechnical
18902 Commission (IEC)} standard.
18903 For input numbers, accept one of the following suffixes.
18904 For output numbers, values larger than 1024 will be rounded, and printed with
18905 one of the following suffixes:
18908 @samp{Ki} => @math{1024^1 = 2^{10}} (Kibi)
18909 @samp{Mi} => @math{1024^2 = 2^{20}} (Mebi)
18910 @samp{Gi} => @math{1024^3 = 2^{30}} (Gibi)
18911 @samp{Ti} => @math{1024^4 = 2^{40}} (Tebi)
18912 @samp{Pi} => @math{1024^5 = 2^{50}} (Pebi)
18913 @samp{Ei} => @math{1024^6 = 2^{60}} (Exbi)
18914 @samp{Zi} => @math{1024^7 = 2^{70}} (Zebi)
18915 @samp{Yi} => @math{1024^8 = 2^{80}} (Yobi)
18918 The @option{iec-i} option uses a two-letter suffix symbol (e.g. @samp{Gi}),
18919 as the @emph{iec} standard recommends, but this is not always common in
18920 practice. Compare with the @option{iec} option.
18923 @samp{auto} can only be used with @option{--from}. With this method, numbers
18924 with @samp{K},@samp{M},@samp{G},@samp{T},@samp{P},@samp{E},@samp{Z},@samp{Y}
18925 suffixes are interpreted as @emph{SI} values, and numbers with @samp{Ki},
18926 @samp{Mi},@samp{Gi},@samp{Ti},@samp{Pi},@samp{Ei},@samp{Zi},@samp{Yi} suffixes
18927 are interpreted as @emph{IEC} values.
18931 @subsection Examples of using @command{numfmt}
18933 Converting a single number from/to @emph{human} representation:
18935 $ numfmt --to=si 500000
18938 $ numfmt --to=iec 500000
18941 $ numfmt --to=iec-i 500000
18944 $ numfmt --from=si 1M
18947 $ numfmt --from=iec 1M
18950 # with '--from=auto', M=Mega, Mi=Mebi
18951 $ numfmt --from=auto 1M
18953 $ numfmt --from=auto 1Mi
18957 Converting from @samp{SI} to @samp{IEC} scales (e.g. when a drive's capacity is
18958 advertised as @samp{1TB}, while checking the drive's capacity gives lower
18962 $ numfmt --from=si --to=iec 1T
18967 Converting a single field from an input file / piped input (these contrived
18968 examples are for demonstration purposes only, as both @command{ls} and
18969 @command{df} support the @option{--human-readable} option to
18970 output sizes in human-readable format):
18973 # Third field (file size) will be shown in SI representation
18974 $ ls -log | numfmt --field 3 --header --to=si | head -n4
18975 -rw-r--r-- 1 94K Aug 23 2011 ABOUT-NLS
18976 -rw-r--r-- 1 3.7K Jan 7 16:15 AUTHORS
18977 -rw-r--r-- 1 36K Jun 1 2011 COPYING
18978 -rw-r--r-- 1 0 Jan 7 15:15 ChangeLog
18980 # Second field (size) will be shown in IEC representation
18981 $ df --block-size=1 | numfmt --field 2 --header --to=iec | head -n4
18982 File system 1B-blocks Used Available Use% Mounted on
18983 rootfs 132G 104741408 26554036 80% /
18984 tmpfs 794M 7580 804960 1% /run/shm
18985 /dev/sdb1 694G 651424756 46074696 94% /home
18989 Output can be tweaked using @option{--padding} or @option{--format}:
18992 # Pad to 10 characters, right-aligned
18993 $ du -s * | numfmt --to=si --padding=10
18999 # Pad to 10 characters, left-aligned
19000 $ du -s * | numfmt --to=si --padding=-10
19006 # Pad to 10 characters, left-aligned, using 'format'
19007 $ du -s * | numfmt --to=si --format="%10f"
19013 # Pad to 10 characters, left-aligned, using 'format'
19014 $ du -s * | numfmt --to=si --padding="%-10f"
19021 With locales that support grouping digits, using @option{--grouping} or
19022 @option{--format} enables grouping. In @samp{POSIX} locale, grouping is
19026 $ LC_ALL=C numfmt --from=iec --grouping 2G
19029 $ LC_ALL=en_US.utf8 numfmt --from=iec --grouping 2G
19032 $ LC_ALL=ta_IN numfmt --from=iec --grouping 2G
19035 $ LC_ALL=C numfmt --from=iec --format="==%'15f==" 2G
19038 $ LC_ALL=en_US.utf8 numfmt --from=iec --format="==%'15f==" 2G
19041 $ LC_ALL=en_US.utf8 numfmt --from=iec --format="==%'-15f==" 2G
19044 $ LC_ALL=ta_IN numfmt --from=iec --format="==%'15f==" 2G
19045 == 2,14,74,83,648==
19049 @node seq invocation
19050 @section @command{seq}: Print numeric sequences
19053 @cindex numeric sequences
19054 @cindex sequence of numbers
19056 @command{seq} prints a sequence of numbers to standard output. Synopses:
19059 seq [@var{option}]@dots{} @var{last}
19060 seq [@var{option}]@dots{} @var{first} @var{last}
19061 seq [@var{option}]@dots{} @var{first} @var{increment} @var{last}
19064 @command{seq} prints the numbers from @var{first} to @var{last} by
19065 @var{increment}. By default, each number is printed on a separate line.
19066 When @var{increment} is not specified, it defaults to @samp{1},
19067 even when @var{first} is larger than @var{last}.
19068 @var{first} also defaults to @samp{1}. So @code{seq 1} prints
19069 @samp{1}, but @code{seq 0} and @code{seq 10 5} produce no output.
19070 The sequence of numbers ends when the sum of the current number and
19071 @var{increment} would become greater than @var{last},
19072 so @code{seq 1 10 10} only produces @samp{1}.
19073 @var{increment} must not be @samp{0}; use the tool @command{yes} to get
19074 repeated output of a constant number.
19075 @var{first}, @var{increment} and @var{last} must not be @code{NaN},
19076 but @code{inf} is supported.
19077 Floating-point numbers may be specified in either the current or
19078 the C locale. @xref{Floating point}.
19080 The program accepts the following options. Also see @ref{Common options}.
19081 Options must precede operands.
19084 @item -f @var{format}
19085 @itemx --format=@var{format}
19088 @cindex formatting of numbers in @command{seq}
19089 Print all numbers using @var{format}.
19090 @var{format} must contain exactly one of the @samp{printf}-style
19091 floating point conversion specifications @samp{%a}, @samp{%e},
19092 @samp{%f}, @samp{%g}, @samp{%A}, @samp{%E}, @samp{%F}, @samp{%G}@.
19093 The @samp{%} may be followed by zero or more flags taken from the set
19094 @samp{-+#0 '}, then an optional width containing one or more digits,
19095 then an optional precision consisting of a @samp{.} followed by zero
19096 or more digits. @var{format} may also contain any number of @samp{%%}
19097 conversion specifications. All conversion specifications have the
19098 same meaning as with @samp{printf}.
19100 The default format is derived from @var{first}, @var{step}, and
19101 @var{last}. If these all use a fixed point decimal representation,
19102 the default format is @samp{%.@var{p}f}, where @var{p} is the minimum
19103 precision that can represent the output numbers exactly. Otherwise,
19104 the default format is @samp{%g}.
19106 @item -s @var{string}
19107 @itemx --separator=@var{string}
19109 @opindex --separator
19110 @cindex separator for numbers in @command{seq}
19111 Separate numbers with @var{string}; default is a newline.
19112 The output always terminates with a newline.
19115 @itemx --equal-width
19117 @opindex --equal-width
19118 Print all numbers with the same width, by padding with leading zeros.
19119 @var{first}, @var{step}, and @var{last} should all use a fixed point
19120 decimal representation.
19121 (To have other kinds of padding, use @option{--format}).
19125 You can get finer-grained control over output with @option{-f}:
19128 $ seq -f '(%9.2E)' -9e5 1.1e6 1.3e6
19134 If you want hexadecimal integer output, you can use @command{printf}
19135 to perform the conversion:
19138 $ printf '%x\n' $(seq 1048575 1024 1050623)
19144 For very long lists of numbers, use xargs to avoid
19145 system limitations on the length of an argument list:
19148 $ seq 1000000 | xargs printf '%x\n' | tail -n 3
19154 To generate octal output, use the printf @code{%o} format instead
19157 On most systems, seq can produce whole-number output for values up to
19158 at least @math{2^{53}}. Larger integers are approximated. The details
19159 differ depending on your floating-point implementation.
19160 @xref{Floating point}. A common
19161 case is that @command{seq} works with integers through @math{2^{64}},
19162 and larger integers may not be numerically correct:
19165 $ seq 50000000000000000000 2 50000000000000000004
19166 50000000000000000000
19167 50000000000000000000
19168 50000000000000000004
19171 However, note that when limited to non-negative whole numbers,
19172 an increment of less than 200, and no format-specifying option,
19173 seq can print arbitrarily large numbers.
19174 Therefore @command{seq inf} can be used to
19175 generate an infinite sequence of numbers.
19177 Be careful when using @command{seq} with outlandish values: otherwise
19178 you may see surprising results, as @command{seq} uses floating point
19179 internally. For example, on the x86 platform, where the internal
19180 representation uses a 64-bit fraction, the command:
19183 seq 1 0.0000000000000000001 1.0000000000000000009
19186 outputs 1.0000000000000000007 twice and skips 1.0000000000000000008.
19191 @node File permissions
19192 @chapter File permissions
19196 @node File timestamps
19197 @chapter File timestamps
19203 Standard POSIX files have three timestamps: the access timestamp
19204 (atime) of the last read, the modification timestamp (mtime) of the
19205 last write, and the status change timestamp (ctime) of the last change
19206 to the file's meta-information. Some file systems support a
19207 fourth time: the birth timestamp (birthtime) of when the file was
19208 created; by definition, birthtime never changes.
19210 One common example of a ctime change is when the permissions of a file
19211 change. Changing the permissions doesn't access the file, so atime
19212 doesn't change, nor does it modify the file, so the mtime doesn't
19213 change. Yet, something about the file itself has changed, and this
19214 must be noted somewhere. This is the job of the ctime field. This is
19215 necessary, so that, for example, a backup program can make a fresh
19216 copy of the file, including the new permissions value. Another
19217 operation that modifies a file's ctime without affecting the others is
19220 Naively, a file's atime, mtime, and ctime are set to the current time
19221 whenever you read, write, or change the attributes of the file
19222 respectively, and searching a directory counts as reading it. A
19223 file's atime and mtime can also be set directly, via the
19224 @command{touch} command (@pxref{touch invocation}). In practice,
19225 though, timestamps are not updated quite that way.
19227 For efficiency reasons, many systems are lazy about updating atimes:
19228 when a program accesses a file, they may delay updating the file's
19229 atime, or may not update the file's atime if the file has been
19230 accessed recently, or may not update the atime at all. Similar
19231 laziness, though typically not quite so extreme, applies to mtimes and
19234 Some systems emulate timestamps instead of supporting them directly,
19235 and these emulations may disagree with the naive interpretation. For
19236 example, a system may fake an atime or ctime by using the mtime.
19239 The determination of what time is ``current'' depends on the
19240 platform. Platforms with network file systems often use different
19241 clocks for the operating system and for file systems; because
19242 updates typically uses file systems' clocks by default, clock
19243 skew can cause the resulting file timestamps to appear to be in a
19244 program's ``future'' or ``past''.
19246 @cindex file timestamp resolution
19247 When the system updates a file timestamp to a desired time @var{t}
19248 (which is either the current time, or a time specified via the
19249 @command{touch} command), there are several reasons the file's
19250 timestamp may be set to a value that differs from @var{t}. First,
19251 @var{t} may have a higher resolution than supported. Second, a file
19252 system may use different resolutions for different types of times.
19253 Third, file timestamps may use a different resolution than operating
19254 system timestamps. Fourth, the operating system primitives used to
19255 update timestamps may employ yet a different resolution. For example,
19256 in theory a file system might use 10-microsecond resolution for access
19257 timestamp and 100-nanosecond resolution for modification timestamp, and the
19258 operating system might use nanosecond resolution for the current time
19259 and microsecond resolution for the primitive that @command{touch} uses
19260 to set a file's timestamp to an arbitrary value.
19263 @include parse-datetime.texi
19265 @include sort-version.texi
19269 @node Opening the software toolbox
19270 @chapter Opening the Software Toolbox
19272 An earlier version of this chapter appeared in
19273 @uref{https://www.linuxjournal.com/article.php?sid=2762, the
19274 @cite{What's GNU@?} column of the June 1994 @cite{Linux Journal}}.
19275 It was written by Arnold Robbins.
19278 * Toolbox introduction:: Toolbox introduction
19279 * I/O redirection:: I/O redirection
19280 * The who command:: The @command{who} command
19281 * The cut command:: The @command{cut} command
19282 * The sort command:: The @command{sort} command
19283 * The uniq command:: The @command{uniq} command
19284 * Putting the tools together:: Putting the tools together
19288 @node Toolbox introduction
19289 @unnumberedsec Toolbox Introduction
19291 This month's column is only peripherally related to the GNU Project, in
19292 that it describes a number of the GNU tools on your GNU/Linux system
19294 might be used. What it's really about is the ``Software Tools'' philosophy
19295 of program development and usage.
19297 The software tools philosophy was an important and integral concept
19298 in the initial design and development of Unix (of which GNU/Linux and GNU are
19299 essentially clones). Unfortunately, in the modern day press of
19300 Internetworking and flashy GUIs, it seems to have fallen by the
19301 wayside. This is a shame, since it provides a powerful mental model
19302 for solving many kinds of problems.
19304 Many people carry a Swiss Army knife around in their pants pockets (or
19305 purse). A Swiss Army knife is a handy tool to have: it has several knife
19306 blades, a screwdriver, tweezers, toothpick, nail file, corkscrew, and perhaps
19307 a number of other things on it. For the everyday, small miscellaneous jobs
19308 where you need a simple, general purpose tool, it's just the thing.
19310 On the other hand, an experienced carpenter doesn't build a house using
19311 a Swiss Army knife. Instead, he has a toolbox chock full of specialized
19312 tools---a saw, a hammer, a screwdriver, a plane, and so on. And he knows
19313 exactly when and where to use each tool; you won't catch him hammering nails
19314 with the handle of his screwdriver.
19316 The Unix developers at Bell Labs were all professional programmers and trained
19317 computer scientists. They had found that while a one-size-fits-all program
19318 might appeal to a user because there's only one program to use, in practice
19323 difficult to write,
19326 difficult to maintain and
19330 difficult to extend to meet new situations.
19333 Instead, they felt that programs should be specialized tools. In short, each
19334 program ``should do one thing well.'' No more and no less. Such programs are
19335 simpler to design, write, and get right---they only do one thing.
19337 Furthermore, they found that with the right machinery for hooking programs
19338 together, that the whole was greater than the sum of the parts. By combining
19339 several special purpose programs, you could accomplish a specific task
19340 that none of the programs was designed for, and accomplish it much more
19341 quickly and easily than if you had to write a special purpose program.
19342 We will see some (classic) examples of this further on in the column.
19343 (An important additional point was that, if necessary, take a detour
19344 and build any software tools you may need first, if you don't already
19345 have something appropriate in the toolbox.)
19347 @node I/O redirection
19348 @unnumberedsec I/O Redirection
19350 Hopefully, you are familiar with the basics of I/O redirection in the
19351 shell, in particular the concepts of ``standard input,'' ``standard output,''
19352 and ``standard error''. Briefly, ``standard input'' is a data source, where
19353 data comes from. A program should not need to either know or care if the
19354 data source is a regular file, a keyboard, a magnetic tape, or even a punched
19355 card reader. Similarly, ``standard output'' is a data sink, where data goes
19356 to. The program should neither know nor care where this might be.
19357 Programs that only read their standard input, do something to the data,
19358 and then send it on, are called @dfn{filters}, by analogy to filters in a
19361 With the Unix shell, it's very easy to set up data pipelines:
19364 program_to_create_data | filter1 | ... | filterN > final.pretty.data
19367 We start out by creating the raw data; each filter applies some successive
19368 transformation to the data, until by the time it comes out of the pipeline,
19369 it is in the desired form.
19371 This is fine and good for standard input and standard output. Where does the
19372 standard error come in to play? Well, think about @command{filter1} in
19373 the pipeline above. What happens if it encounters an error in the data it
19374 sees? If it writes an error message to standard output, it will just
19375 disappear down the pipeline into @command{filter2}'s input, and the
19376 user will probably never see it. So programs need a place where they can send
19377 error messages so that the user will notice them. This is standard error,
19378 and it is usually connected to your console or window, even if you have
19379 redirected standard output of your program away from your screen.
19381 For filter programs to work together, the format of the data has to be
19382 agreed upon. The most straightforward and easiest format to use is simply
19383 lines of text. Unix data files are generally just streams of bytes, with
19384 lines delimited by the ASCII LF (Line Feed) character,
19385 conventionally called a ``newline'' in the Unix literature. (This is
19386 @code{'\n'} if you're a C programmer.) This is the format used by all
19387 the traditional filtering programs. (Many earlier operating systems
19388 had elaborate facilities and special purpose programs for managing
19389 binary data. Unix has always shied away from such things, under the
19390 philosophy that it's easiest to simply be able to view and edit your
19391 data with a text editor.)
19393 OK, enough introduction. Let's take a look at some of the tools, and then
19394 we'll see how to hook them together in interesting ways. In the following
19395 discussion, we will only present those command line options that interest
19396 us. As you should always do, double check your system documentation
19397 for the full story.
19399 @node The who command
19400 @unnumberedsec The @command{who} Command
19402 The first program is the @command{who} command. By itself, it generates a
19403 list of the users who are currently logged in. Although I'm writing
19404 this on a single-user system, we'll pretend that several people are
19409 @print{} arnold console Jan 22 19:57
19410 @print{} miriam ttyp0 Jan 23 14:19(:0.0)
19411 @print{} bill ttyp1 Jan 21 09:32(:0.0)
19412 @print{} arnold ttyp2 Jan 23 20:48(:0.0)
19415 Here, the @samp{$} is the usual shell prompt, at which I typed @samp{who}.
19416 There are three people logged in, and I am logged in twice. On traditional
19417 Unix systems, user names are never more than eight characters long. This
19418 little bit of trivia will be useful later. The output of @command{who} is nice,
19419 but the data is not all that exciting.
19421 @node The cut command
19422 @unnumberedsec The @command{cut} Command
19424 The next program we'll look at is the @command{cut} command. This program
19425 cuts out columns or fields of input data. For example, we can tell it
19426 to print just the login name and full name from the @file{/etc/passwd}
19427 file. The @file{/etc/passwd} file has seven fields, separated by
19431 arnold:xyzzy:2076:10:Arnold D. Robbins:/home/arnold:/bin/bash
19434 To get the first and fifth fields, we would use @command{cut} like this:
19437 $ cut -d: -f1,5 /etc/passwd
19438 @print{} root:Operator
19440 @print{} arnold:Arnold D. Robbins
19441 @print{} miriam:Miriam A. Robbins
19445 With the @option{-c} option, @command{cut} will cut out specific characters
19446 (i.e., columns) in the input lines. This is useful for input data
19447 that has fixed width fields, and does not have a field separator. For
19448 example, list the Monday dates for the current month:
19450 @c Is using cal ok? Looked at gcal, but I don't like it.
19461 @node The sort command
19462 @unnumberedsec The @command{sort} Command
19464 Next we'll look at the @command{sort} command. This is one of the most
19465 powerful commands on a Unix-style system; one that you will often find
19466 yourself using when setting up fancy data plumbing.
19469 command reads and sorts each file named on the command line. It then
19470 merges the sorted data and writes it to standard output. It will read
19471 standard input if no files are given on the command line (thus
19472 making it into a filter). The sort is based on the character collating
19473 sequence or based on user-supplied ordering criteria.
19476 @node The uniq command
19477 @unnumberedsec The @command{uniq} Command
19479 Finally (at least for now), we'll look at the @command{uniq} program. When
19480 sorting data, you will often end up with duplicate lines, lines that
19481 are identical. Usually, all you need is one instance of each line.
19482 This is where @command{uniq} comes in. The @command{uniq} program reads its
19483 standard input. It prints only one
19484 copy of each repeated line. It does have several options. Later on,
19485 we'll use the @option{-c} option, which prints each unique line, preceded
19486 by a count of the number of times that line occurred in the input.
19489 @node Putting the tools together
19490 @unnumberedsec Putting the Tools Together
19492 Now, let's suppose this is a large ISP server system with dozens of users
19493 logged in. The management wants the system administrator to write a
19495 generate a sorted list of logged in users. Furthermore, even if a user
19496 is logged in multiple times, his or her name should only show up in the
19499 The administrator could sit down with the system documentation and write a C
19500 program that did this. It would take perhaps a couple of hundred lines
19501 of code and about two hours to write it, test it, and debug it.
19502 However, knowing the software toolbox, the administrator can instead start out
19503 by generating just a list of logged on users:
19513 Next, sort the list:
19516 $ who | cut -c1-8 | sort
19523 Finally, run the sorted list through @command{uniq}, to weed out duplicates:
19526 $ who | cut -c1-8 | sort | uniq
19532 The @command{sort} command actually has a @option{-u} option that does what
19533 @command{uniq} does. However, @command{uniq} has other uses for which one
19534 cannot substitute @samp{sort -u}.
19536 The administrator puts this pipeline into a shell script, and makes it
19538 all the users on the system (@samp{#} is the system administrator,
19539 or @code{root}, prompt):
19542 # cat > /usr/local/bin/listusers
19543 who | cut -c1-8 | sort | uniq
19545 # chmod +x /usr/local/bin/listusers
19548 There are four major points to note here. First, with just four
19549 programs, on one command line, the administrator was able to save about two
19550 hours worth of work. Furthermore, the shell pipeline is just about as
19551 efficient as the C program would be, and it is much more efficient in
19552 terms of programmer time. People time is much more expensive than
19553 computer time, and in our modern ``there's never enough time to do
19554 everything'' society, saving two hours of programmer time is no mean
19557 Second, it is also important to emphasize that with the
19558 @emph{combination} of the tools, it is possible to do a special
19559 purpose job never imagined by the authors of the individual programs.
19561 Third, it is also valuable to build up your pipeline in stages, as we did here.
19562 This allows you to view the data at each stage in the pipeline, which helps
19563 you acquire the confidence that you are indeed using these tools correctly.
19565 Finally, by bundling the pipeline in a shell script, other users can use
19566 your command, without having to remember the fancy plumbing you set up for
19567 them. In terms of how you run them, shell scripts and compiled programs are
19570 After the previous warm-up exercise, we'll look at two additional, more
19571 complicated pipelines. For them, we need to introduce two more tools.
19573 The first is the @command{tr} command, which stands for ``transliterate.''
19574 The @command{tr} command works on a character-by-character basis, changing
19575 characters. Normally it is used for things like mapping upper case to
19579 $ echo ThIs ExAmPlE HaS MIXED case! | tr '[:upper:]' '[:lower:]'
19580 @print{} this example has mixed case!
19583 There are several options of interest:
19587 work on the complement of the listed characters, i.e.,
19588 operations apply to characters not in the given set
19591 delete characters in the first set from the output
19594 squeeze repeated characters in the output into just one character.
19597 We will be using all three options in a moment.
19599 The other command we'll look at is @command{comm}. The @command{comm}
19600 command takes two sorted input files as input data, and prints out the
19601 files' lines in three columns. The output columns are the data lines
19602 unique to the first file, the data lines unique to the second file, and
19603 the data lines that are common to both. The @option{-1}, @option{-2}, and
19604 @option{-3} command line options @emph{omit} the respective columns. (This is
19605 non-intuitive and takes a little getting used to.) For example:
19627 The file name @file{-} tells @command{comm} to read standard input
19628 instead of a regular file.
19630 Now we're ready to build a fancy pipeline. The first application is a word
19631 frequency counter. This helps an author determine if he or she is over-using
19634 The first step is to change the case of all the letters in our input file
19635 to one case. ``The'' and ``the'' are the same word when doing counting.
19638 $ tr '[:upper:]' '[:lower:]' < whats.gnu | ...
19641 The next step is to get rid of punctuation. Quoted words and unquoted words
19642 should be treated identically; it's easiest to just get the punctuation out of
19646 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' | ...
19649 The second @command{tr} command operates on the complement of the listed
19650 characters, which are all the letters, the digits, the underscore, and
19651 the blank. The @samp{\n} represents the newline character; it has to
19652 be left alone. (The ASCII tab character should also be included for
19653 good measure in a production script.)
19655 At this point, we have data consisting of words separated by blank space.
19656 The words only contain alphanumeric characters (and the underscore). The
19657 next step is break the data apart so that we have one word per line. This
19658 makes the counting operation much easier, as we will see shortly.
19661 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
19662 > tr -s ' ' '\n' | ...
19665 This command turns blanks into newlines. The @option{-s} option squeezes
19666 multiple newline characters in the output into just one, removing
19667 blank lines. (The @samp{>} is the shell's ``secondary prompt.''
19668 This is what the shell prints when it notices you haven't finished
19669 typing in all of a command.)
19671 We now have data consisting of one word per line, no punctuation, all one
19672 case. We're ready to count each word:
19675 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
19676 > tr -s ' ' '\n' | sort | uniq -c | ...
19679 At this point, the data might look something like this:
19692 The output is sorted by word, not by count! What we want is the most
19693 frequently used words first. Fortunately, this is easy to accomplish,
19694 with the help of two more @command{sort} options:
19698 do a numeric sort, not a textual one
19701 reverse the order of the sort
19704 The final pipeline looks like this:
19707 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
19708 > tr -s ' ' '\n' | sort | uniq -c | sort -n -r
19717 Whew! That's a lot to digest. Yet, the same principles apply. With six
19718 commands, on two lines (really one long one split for convenience), we've
19719 created a program that does something interesting and useful, in much
19720 less time than we could have written a C program to do the same thing.
19722 A minor modification to the above pipeline can give us a simple spelling
19723 checker! To determine if you've spelled a word correctly, all you have to
19724 do is look it up in a dictionary. If it is not there, then chances are
19725 that your spelling is incorrect. So, we need a dictionary.
19726 The conventional location for a dictionary is @file{/usr/share/dict/words}.
19728 Now, how to compare our file with the dictionary? As before, we generate
19729 a sorted list of words, one per line:
19732 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
19733 > tr -s ' ' '\n' | sort -u | ...
19736 Now, all we need is a list of words that are @emph{not} in the
19737 dictionary. Here is where the @command{comm} command comes in.
19738 Unfortunately @command{comm} operates on sorted input and
19739 @file{/usr/share/dict/words} is not sorted the way that @command{sort}
19740 and @command{comm} normally use, so we first create a properly-sorted
19741 copy of the dictionary and then run a pipeline that uses the copy.
19744 $ sort /usr/share/dict/words > sorted-words
19745 $ tr '[:upper:]' '[:lower:]' < whats.gnu | tr -cd '[:alnum:]_ \n' |
19746 > tr -s ' ' '\n' | sort -u |
19747 > comm -23 - sorted-words
19750 The @option{-2} and @option{-3} options eliminate lines that are only in the
19751 dictionary (the second file), and lines that are in both files. Lines
19752 only in the first file (standard input, our stream of words), are
19753 words that are not in the dictionary. These are likely candidates for
19754 spelling errors. This pipeline was the first cut at a production
19755 spelling checker on Unix.
19757 There are some other tools that deserve brief mention.
19761 search files for text that matches a regular expression
19764 count lines, words, characters
19767 a T-fitting for data pipes, copies data to files and to standard output
19770 the stream editor, an advanced tool
19773 a data manipulation language, another advanced tool
19776 The software tools philosophy also espoused the following bit of
19777 advice: ``Let someone else do the hard part.'' This means, take
19778 something that gives you most of what you need, and then massage it the
19779 rest of the way until it's in the form that you want.
19785 Each program should do one thing well. No more, no less.
19788 Combining programs with appropriate plumbing leads to results where
19789 the whole is greater than the sum of the parts. It also leads to novel
19790 uses of programs that the authors might never have imagined.
19793 Programs should never print extraneous header or trailer data, since these
19794 could get sent on down a pipeline. (A point we didn't mention earlier.)
19797 Let someone else do the hard part.
19800 Know your toolbox! Use each program appropriately. If you don't have an
19801 appropriate tool, build one.
19804 All the programs discussed are available as described in
19805 @uref{https://www.gnu.org/software/coreutils/coreutils.html,
19806 GNU core utilities}.
19808 None of what I have presented in this column is new. The Software Tools
19809 philosophy was first introduced in the book @cite{Software Tools}, by
19810 Brian Kernighan and P.J. Plauger (Addison-Wesley, ISBN 0-201-03669-X).
19811 This book showed how to write and use software tools. It was written in
19812 1976, using a preprocessor for FORTRAN named @command{ratfor} (RATional
19813 FORtran). At the time, C was not as ubiquitous as it is now; FORTRAN
19814 was. The last chapter presented a @command{ratfor} to FORTRAN
19815 processor, written in @command{ratfor}. @command{ratfor} looks an awful
19816 lot like C; if you know C, you won't have any problem following the
19819 In 1981, the book was updated and made available as @cite{Software Tools
19820 in Pascal} (Addison-Wesley, ISBN 0-201-10342-7). Both books are
19821 still in print and are well worth
19822 reading if you're a programmer. They certainly made a major change in
19823 how I view programming.
19825 The programs in both books are available from
19826 @uref{https://www.cs.princeton.edu/~bwk/, Brian Kernighan's home page}.
19827 For a number of years, there was an active
19828 Software Tools Users Group, whose members had ported the original
19829 @command{ratfor} programs to essentially every computer system with a
19830 FORTRAN compiler. The popularity of the group waned in the middle 1980s
19831 as Unix began to spread beyond universities.
19833 With the current proliferation of GNU code and other clones of Unix programs,
19834 these programs now receive little attention; modern C versions are
19835 much more efficient and do more than these programs do. Nevertheless, as
19836 exposition of good programming style, and evangelism for a still-valuable
19837 philosophy, these books are unparalleled, and I recommend them highly.
19839 Acknowledgment: I would like to express my gratitude to Brian Kernighan
19840 of Bell Labs, the original Software Toolsmith, for reviewing this column.
19842 @node GNU Free Documentation License
19843 @appendix GNU Free Documentation License
19847 @node Concept index
19854 @c Local variables:
19855 @c texinfo-column-for-description: 32