1ZSHMISC(1) General Commands Manual ZSHMISC(1)
2
3
4
6 zshmisc - everything and then some
7
9 A simple command is a sequence of optional parameter assignments fol‐
10 lowed by blank-separated words, with optional redirections inter‐
11 spersed. For a description of assignment, see the beginning of zsh‐
12 param(1).
13
14 The first word is the command to be executed, and the remaining words,
15 if any, are arguments to the command. If a command name is given, the
16 parameter assignments modify the environment of the command when it is
17 executed. The value of a simple command is its exit status, or 128
18 plus the signal number if terminated by a signal. For example,
19
20 echo foo
21
22 is a simple command with arguments.
23
24 A pipeline is either a simple command, or a sequence of two or more
25 simple commands where each command is separated from the next by `|' or
26 `|&'. Where commands are separated by `|', the standard output of the
27 first command is connected to the standard input of the next. `|&' is
28 shorthand for `2>&1 |', which connects both the standard output and the
29 standard error of the command to the standard input of the next. The
30 value of a pipeline is the value of the last command, unless the pipe‐
31 line is preceded by `!' in which case the value is the logical inverse
32 of the value of the last command. For example,
33
34 echo foo | sed 's/foo/bar/'
35
36 is a pipeline, where the output (`foo' plus a newline) of the first
37 command will be passed to the input of the second.
38
39 If a pipeline is preceded by `coproc', it is executed as a coprocess; a
40 two-way pipe is established between it and the parent shell. The shell
41 can read from or write to the coprocess by means of the `>&p' and `<&p'
42 redirection operators or with `print -p' and `read -p'. A pipeline
43 cannot be preceded by both `coproc' and `!'. If job control is active,
44 the coprocess can be treated in other than input and output as an ordi‐
45 nary background job.
46
47 A sublist is either a single pipeline, or a sequence of two or more
48 pipelines separated by `&&' or `||'. If two pipelines are separated by
49 `&&', the second pipeline is executed only if the first succeeds
50 (returns a zero status). If two pipelines are separated by `||', the
51 second is executed only if the first fails (returns a nonzero status).
52 Both operators have equal precedence and are left associative. The
53 value of the sublist is the value of the last pipeline executed. For
54 example,
55
56 dmesg | grep panic && print yes
57
58 is a sublist consisting of two pipelines, the second just a simple com‐
59 mand which will be executed if and only if the grep command returns a
60 zero status. If it does not, the value of the sublist is that return
61 status, else it is the status returned by the print (almost certainly
62 zero).
63
64 A list is a sequence of zero or more sublists, in which each sublist is
65 terminated by `;', `&', `&|', `&!', or a newline. This terminator may
66 optionally be omitted from the last sublist in the list when the list
67 appears as a complex command inside `(...)' or `{...}'. When a sublist
68 is terminated by `;' or newline, the shell waits for it to finish
69 before executing the next sublist. If a sublist is terminated by a
70 `&', `&|', or `&!', the shell executes the last pipeline in it in the
71 background, and does not wait for it to finish (note the difference
72 from other shells which execute the whole sublist in the background).
73 A backgrounded pipeline returns a status of zero.
74
75 More generally, a list can be seen as a set of any shell commands what‐
76 soever, including the complex commands below; this is implied wherever
77 the word `list' appears in later descriptions. For example, the com‐
78 mands in a shell function form a special sort of list.
79
81 A simple command may be preceded by a precommand modifier, which will
82 alter how the command is interpreted. These modifiers are shell
83 builtin commands with the exception of nocorrect which is a reserved
84 word.
85
86 - The command is executed with a `-' prepended to its argv[0]
87 string.
88
89 builtin
90 The command word is taken to be the name of a builtin command,
91 rather than a shell function or external command.
92
93 command [ -pvV ]
94 The command word is taken to be the name of an external command,
95 rather than a shell function or builtin. If the POSIX_BUILTINS
96 option is set, builtins will also be executed but certain spe‐
97 cial properties of them are suppressed. The -p flag causes a
98 default path to be searched instead of that in $path. With the
99 -v flag, command is similar to whence and with -V, it is equiva‐
100 lent to whence -v.
101
102 exec [ -cl ] [ -a argv0 ]
103 The following command together with any arguments is run in
104 place of the current process, rather than as a sub-process. The
105 shell does not fork and is replaced. The shell does not invoke
106 TRAPEXIT, nor does it source zlogout files. The options are
107 provided for compatibility with other shells.
108
109 The -c option clears the environment.
110
111 The -l option is equivalent to the - precommand modifier, to
112 treat the replacement command as a login shell; the command is
113 executed with a - prepended to its argv[0] string. This flag
114 has no effect if used together with the -a option.
115
116 The -a option is used to specify explicitly the argv[0] string
117 (the name of the command as seen by the process itself) to be
118 used by the replacement command and is directly equivalent to
119 setting a value for the ARGV0 environment variable.
120
121 nocorrect
122 Spelling correction is not done on any of the words. This must
123 appear before any other precommand modifier, as it is inter‐
124 preted immediately, before any parsing is done. It has no
125 effect in non-interactive shells.
126
127 noglob Filename generation (globbing) is not performed on any of the
128 words.
129
131 A complex command in zsh is one of the following:
132
133 if list then list [ elif list then list ] ... [ else list ] fi
134 The if list is executed, and if it returns a zero exit status,
135 the then list is executed. Otherwise, the elif list is executed
136 and if its status is zero, the then list is executed. If each
137 elif list returns nonzero status, the else list is executed.
138
139 for name ... [ in word ... ] term do list done
140 Expand the list of words, and set the parameter name to each of
141 them in turn, executing list each time. If the `in word' is
142 omitted, use the positional parameters instead of the words.
143
144 The term consists of one or more newline or ; which terminate
145 the words, and are optional when the `in word' is omitted.
146
147 More than one parameter name can appear before the list of
148 words. If N names are given, then on each execution of the loop
149 the next N words are assigned to the corresponding parameters.
150 If there are more names than remaining words, the remaining
151 parameters are each set to the empty string. Execution of the
152 loop ends when there is no remaining word to assign to the first
153 name. It is only possible for in to appear as the first name in
154 the list, else it will be treated as marking the end of the
155 list.
156
157 for (( [expr1] ; [expr2] ; [expr3] )) do list done
158 The arithmetic expression expr1 is evaluated first (see the sec‐
159 tion `Arithmetic Evaluation'). The arithmetic expression expr2
160 is repeatedly evaluated until it evaluates to zero and when
161 non-zero, list is executed and the arithmetic expression expr3
162 evaluated. If any expression is omitted, then it behaves as if
163 it evaluated to 1.
164
165 while list do list done
166 Execute the do list as long as the while list returns a zero
167 exit status.
168
169 until list do list done
170 Execute the do list as long as until list returns a nonzero exit
171 status.
172
173 repeat word do list done
174 word is expanded and treated as an arithmetic expression, which
175 must evaluate to a number n. list is then executed n times.
176
177 The repeat syntax is disabled by default when the shell starts
178 in a mode emulating another shell. It can be enabled with the
179 command `enable -r repeat'
180
181 case word in [ [(] pattern [ | pattern ] ... ) list (;;|;&|;|) ] ...
182 esac
183 Execute the list associated with the first pattern that matches
184 word, if any. The form of the patterns is the same as that used
185 for filename generation. See the section `Filename Generation'.
186
187 Note further that, unless the SH_GLOB option is set, the whole
188 pattern with alternatives is treated by the shell as equivalent
189 to a group of patterns within parentheses, although white space
190 may appear about the parentheses and the vertical bar and will
191 be stripped from the pattern at those points. White space may
192 appear elsewhere in the pattern; this is not stripped. If the
193 SH_GLOB option is set, so that an opening parenthesis can be
194 unambiguously treated as part of the case syntax, the expression
195 is parsed into separate words and these are treated as strict
196 alternatives (as in other shells).
197
198 If the list that is executed is terminated with ;& rather than
199 ;;, the following list is also executed. The rule for the ter‐
200 minator of the following list ;;, ;& or ;| is applied unless the
201 esac is reached.
202
203 If the list that is executed is terminated with ;| the shell
204 continues to scan the patterns looking for the next match, exe‐
205 cuting the corresponding list, and applying the rule for the
206 corresponding terminator ;;, ;& or ;|. Note that word is not
207 re-expanded; all applicable patterns are tested with the same
208 word.
209
210 select name [ in word ... term ] do list done
211 where term is one or more newline or ; to terminate the words.
212 Print the set of words, each preceded by a number. If the in
213 word is omitted, use the positional parameters. The PROMPT3
214 prompt is printed and a line is read from the line editor if the
215 shell is interactive and that is active, or else standard input.
216 If this line consists of the number of one of the listed words,
217 then the parameter name is set to the word corresponding to this
218 number. If this line is empty, the selection list is printed
219 again. Otherwise, the value of the parameter name is set to
220 null. The contents of the line read from standard input is
221 saved in the parameter REPLY. list is executed for each selec‐
222 tion until a break or end-of-file is encountered.
223
224 ( list )
225 Execute list in a subshell. Traps set by the trap builtin are
226 reset to their default values while executing list.
227
228 { list }
229 Execute list.
230
231 { try-list } always { always-list }
232 First execute try-list. Regardless of errors, or break, con‐
233 tinue, or return commands encountered within try-list, execute
234 always-list. Execution then continues from the result of the
235 execution of try-list; in other words, any error, or break, con‐
236 tinue, or return command is treated in the normal way, as if
237 always-list were not present. The two chunks of code are
238 referred to as the `try block' and the `always block'.
239
240 Optional newlines or semicolons may appear after the always;
241 note, however, that they may not appear between the preceding
242 closing brace and the always.
243
244 An `error' in this context is a condition such as a syntax error
245 which causes the shell to abort execution of the current func‐
246 tion, script, or list. Syntax errors encountered while the
247 shell is parsing the code do not cause the always-list to be
248 executed. For example, an erroneously constructed if block in
249 try-list would cause the shell to abort during parsing, so that
250 always-list would not be executed, while an erroneous substitu‐
251 tion such as ${*foo*} would cause a run-time error, after which
252 always-list would be executed.
253
254 An error condition can be tested and reset with the special
255 integer variable TRY_BLOCK_ERROR. Outside an always-list the
256 value is irrelevant, but it is initialised to -1. Inside
257 always-list, the value is 1 if an error occurred in the
258 try-list, else 0. If TRY_BLOCK_ERROR is set to 0 during the
259 always-list, the error condition caused by the try-list is
260 reset, and shell execution continues normally after the end of
261 always-list. Altering the value during the try-list is not use‐
262 ful (unless this forms part of an enclosing always block).
263
264 Regardless of TRY_BLOCK_ERROR, after the end of always-list the
265 normal shell status $? is the value returned from try-list.
266 This will be non-zero if there was an error, even if
267 TRY_BLOCK_ERROR was set to zero.
268
269 The following executes the given code, ignoring any errors it
270 causes. This is an alternative to the usual convention of pro‐
271 tecting code by executing it in a subshell.
272
273 {
274 # code which may cause an error
275 } always {
276 # This code is executed regardless of the error.
277 (( TRY_BLOCK_ERROR = 0 ))
278 }
279 # The error condition has been reset.
280
281 An exit command (or a return command executed at the outermost
282 function level of a script) encountered in try-list does not
283 cause the execution of always-list. Instead, the shell exits
284 immediately after any EXIT trap has been executed.
285
286 function word ... [ () ] [ term ] { list }
287 word ... () [ term ] { list }
288 word ... () [ term ] command
289 where term is one or more newline or ;. Define a function which
290 is referenced by any one of word. Normally, only one word is
291 provided; multiple words are usually only useful for setting
292 traps. The body of the function is the list between the { and
293 }. See the section `Functions'.
294
295 If the option SH_GLOB is set for compatibility with other
296 shells, then whitespace may appear between the left and right
297 parentheses when there is a single word; otherwise, the paren‐
298 theses will be treated as forming a globbing pattern in that
299 case.
300
301 In any of the forms above, a redirection may appear outside the
302 function body, for example
303
304 func() { ... } 2>&1
305
306 The redirection is stored with the function and applied whenever
307 the function is executed. Any variables in the redirection are
308 expanded at the point the function is executed, but outside the
309 function scope.
310
311 time [ pipeline ]
312 The pipeline is executed, and timing statistics are reported on
313 the standard error in the form specified by the TIMEFMT parame‐
314 ter. If pipeline is omitted, print statistics about the shell
315 process and its children.
316
317 [[ exp ]]
318 Evaluates the conditional expression exp and return a zero exit
319 status if it is true. See the section `Conditional Expressions'
320 for a description of exp.
321
323 Many of zsh's complex commands have alternate forms. These are
324 non-standard and are likely not to be obvious even to seasoned shell
325 programmers; they should not be used anywhere that portability of shell
326 code is a concern.
327
328 The short versions below only work if sublist is of the form `{ list }'
329 or if the SHORT_LOOPS option is set. For the if, while and until com‐
330 mands, in both these cases the test part of the loop must also be suit‐
331 ably delimited, such as by `[[ ... ]]' or `(( ... ))', else the end of
332 the test will not be recognized. For the for, repeat, case and select
333 commands no such special form for the arguments is necessary, but the
334 other condition (the special form of sublist or use of the SHORT_LOOPS
335 option) still applies.
336
337 if list { list } [ elif list { list } ] ... [ else { list } ]
338 An alternate form of if. The rules mean that
339
340 if [[ -o ignorebraces ]] {
341 print yes
342 }
343
344 works, but
345
346 if true { # Does not work!
347 print yes
348 }
349
350 does not, since the test is not suitably delimited.
351
352 if list sublist
353 A short form of the alternate if. The same limitations on the
354 form of list apply as for the previous form.
355
356 for name ... ( word ... ) sublist
357 A short form of for.
358
359 for name ... [ in word ... ] term sublist
360 where term is at least one newline or ;. Another short form of
361 for.
362
363 for (( [expr1] ; [expr2] ; [expr3] )) sublist
364 A short form of the arithmetic for command.
365
366 foreach name ... ( word ... ) list end
367 Another form of for.
368
369 while list { list }
370 An alternative form of while. Note the limitations on the form
371 of list mentioned above.
372
373 until list { list }
374 An alternative form of until. Note the limitations on the form
375 of list mentioned above.
376
377 repeat word sublist
378 This is a short form of repeat.
379
380 case word { [ [(] pattern [ | pattern ] ... ) list (;;|;&|;|) ] ... }
381 An alternative form of case.
382
383 select name [ in word ... term ] sublist
384 where term is at least one newline or ;. A short form of
385 select.
386
387 function word ... [ () ] [ term ] sublist
388 This is a short form of function.
389
391 The following words are recognized as reserved words when used as the
392 first word of a command unless quoted or disabled using disable -r:
393
394 do done esac then elif else fi for case if while function repeat time
395 until select coproc nocorrect foreach end ! [[ { } declare export float
396 integer local readonly typeset
397
398 Additionally, `}' is recognized in any position if neither the
399 IGNORE_BRACES option nor the IGNORE_CLOSE_BRACES option is set.
400
402 Certain errors are treated as fatal by the shell: in an interactive
403 shell, they cause control to return to the command line, and in a
404 non-interactive shell they cause the shell to be aborted. In older
405 versions of zsh, a non-interactive shell running a script would not
406 abort completely, but would resume execution at the next command to be
407 read from the script, skipping the remainder of any functions or shell
408 constructs such as loops or conditions; this somewhat illogical behav‐
409 iour can be recovered by setting the option CONTINUE_ON_ERROR.
410
411 Fatal errors found in non-interactive shells include:
412
413 · Failure to parse shell options passed when invoking the shell
414
415 · Failure to change options with the set builtin
416
417 · Parse errors of all sorts, including failures to parse mathemat‐
418 ical expressions
419
420 · Failures to set or modify variable behaviour with typeset,
421 local, declare, export, integer, float
422
423 · Execution of incorrectly positioned loop control structures
424 (continue, break)
425
426 · Attempts to use regular expression with no regular expression
427 module available
428
429 · Disallowed operations when the RESTRICTED options is set
430
431 · Failure to create a pipe needed for a pipeline
432
433 · Failure to create a multio
434
435 · Failure to autoload a module needed for a declared shell feature
436
437 · Errors creating command or process substitutions
438
439 · Syntax errors in glob qualifiers
440
441 · File generation errors where not caught by the option BAD_PAT‐
442 TERN
443
444 · All bad patterns used for matching within case statements
445
446 · File generation failures where not caused by NO_MATCH or similar
447 options
448
449 · All file generation errors where the pattern was used to create
450 a multio
451
452 · Memory errors where detected by the shell
453
454 · Invalid subscripts to shell variables
455
456 · Attempts to assign read-only variables
457
458 · Logical errors with variables such as assignment to the wrong
459 type
460
461 · Use of invalid variable names
462
463 · Errors in variable substitution syntax
464
465 · Failure to convert characters in $'...' expressions
466
467 If the POSIX_BUILTINS option is set, more errors associated with shell
468 builtin commands are treated as fatal, as specified by the POSIX stan‐
469 dard.
470
472 In non-interactive shells, or in interactive shells with the INTERAC‐
473 TIVE_COMMENTS option set, a word beginning with the third character of
474 the histchars parameter (`#' by default) causes that word and all the
475 following characters up to a newline to be ignored.
476
478 Every eligible word in the shell input is checked to see if there is an
479 alias defined for it. If so, it is replaced by the text of the alias
480 if it is in command position (if it could be the first word of a simple
481 command), or if the alias is global. If the replacement text ends with
482 a space, the next word in the shell input is always eligible for pur‐
483 poses of alias expansion. An alias is defined using the alias builtin;
484 global aliases may be defined using the -g option to that builtin.
485
486 A word is defined as:
487
488 · Any plain string or glob pattern
489
490 · Any quoted string, using any quoting method (note that the
491 quotes must be part of the alias definition for this to be eli‐
492 gible)
493
494 · Any parameter reference or command substitution
495
496 · Any series of the foregoing, concatenated without whitespace or
497 other tokens between them
498
499 · Any reserved word (case, do, else, etc.)
500
501 · With global aliasing, any command separator, any redirection
502 operator, and `(' or `)' when not part of a glob pattern
503
504 Alias expansion is done on the shell input before any other expansion
505 except history expansion. Therefore, if an alias is defined for the
506 word foo, alias expansion may be avoided by quoting part of the word,
507 e.g. \foo. Any form of quoting works, although there is nothing to
508 prevent an alias being defined for the quoted form such as \foo as
509 well.
510
511 When POSIX_ALIASES is set, only plain unquoted strings are eligible for
512 aliasing. The alias builtin does not reject ineligible aliases, but
513 they are not expanded.
514
515 For use with completion, which would remove an initial backslash fol‐
516 lowed by a character that isn't special, it may be more convenient to
517 quote the word by starting with a single quote, i.e. 'foo; completion
518 will automatically add the trailing single quote.
519
520 Alias difficulties
521 Although aliases can be used in ways that bend normal shell syntax, not
522 every string of non-white-space characters can be used as an alias.
523
524 Any set of characters not listed as a word above is not a word, hence
525 no attempt is made to expand it as an alias, no matter how it is
526 defined (i.e. via the builtin or the special parameter aliases
527 described in the section THE ZSH/PARAMETER MODULE in zshmodules(1)).
528 However, as noted in the case of POSIX_ALIASES above, the shell does
529 not attempt to deduce whether the string corresponds to a word at the
530 time the alias is created.
531
532 For example, an expression containing an = at the start of a command
533 line is an assignment and cannot be expanded as an alias; a lone = is
534 not an assignment but can only be set as an alias using the parameter,
535 as otherwise the = is taken part of the syntax of the builtin command.
536
537 It is not presently possible to alias the `((' token that introduces
538 arithmetic expressions, because until a full statement has been parsed,
539 it cannot be distinguished from two consecutive `(' tokens introducing
540 nested subshells. Also, if a separator such as && is aliased, \&&
541 turns into the two tokens \& and &, each of which may have been aliased
542 separately. Similarly for \<<, \>|, etc.
543
544 There is a commonly encountered problem with aliases illustrated by the
545 following code:
546
547 alias echobar='echo bar'; echobar
548
549 This prints a message that the command echobar could not be found.
550 This happens because aliases are expanded when the code is read in; the
551 entire line is read in one go, so that when echobar is executed it is
552 too late to expand the newly defined alias. This is often a problem in
553 shell scripts, functions, and code executed with `source' or `.'. Con‐
554 sequently, use of functions rather than aliases is recommended in
555 non-interactive code.
556
557 Note also the unhelpful interaction of aliases and function defini‐
558 tions:
559
560 alias func='noglob func'
561 func() {
562 echo Do something with $*
563 }
564
565 Because aliases are expanded in function definitions, this causes the
566 following command to be executed:
567
568 noglob func() {
569 echo Do something with $*
570 }
571
572 which defines noglob as well as func as functions with the body given.
573 To avoid this, either quote the name func or use the alternative func‐
574 tion definition form `function func'. Ensuring the alias is defined
575 after the function works but is problematic if the code fragment might
576 be re-executed.
577
579 A character may be quoted (that is, made to stand for itself) by pre‐
580 ceding it with a `\'. `\' followed by a newline is ignored.
581
582 A string enclosed between `$'' and `'' is processed the same way as the
583 string arguments of the print builtin, and the resulting string is con‐
584 sidered to be entirely quoted. A literal `'' character can be included
585 in the string by using the `\'' escape.
586
587 All characters enclosed between a pair of single quotes ('') that is
588 not preceded by a `$' are quoted. A single quote cannot appear within
589 single quotes unless the option RC_QUOTES is set, in which case a pair
590 of single quotes are turned into a single quote. For example,
591
592 print ''''
593
594 outputs nothing apart from a newline if RC_QUOTES is not set, but one
595 single quote if it is set.
596
597 Inside double quotes (""), parameter and command substitution occur,
598 and `\' quotes the characters `\', ``', `"', `$', and the first charac‐
599 ter of $histchars (default `!').
600
602 If a command is followed by & and job control is not active, then the
603 default standard input for the command is the empty file /dev/null.
604 Otherwise, the environment for the execution of a command contains the
605 file descriptors of the invoking shell as modified by input/output
606 specifications.
607
608 The following may appear anywhere in a simple command or may precede or
609 follow a complex command. Expansion occurs before word or digit is
610 used except as noted below. If the result of substitution on word pro‐
611 duces more than one filename, redirection occurs for each separate
612 filename in turn.
613
614 < word Open file word for reading as standard input. It is an error to
615 open a file in this fashion if it does not exist.
616
617 <> word
618 Open file word for reading and writing as standard input. If
619 the file does not exist then it is created.
620
621 > word Open file word for writing as standard output. If the file does
622 not exist then it is created. If the file exists, and the CLOB‐
623 BER option is unset, this causes an error; otherwise, it is
624 truncated to zero length.
625
626 >| word
627 >! word
628 Same as >, except that the file is truncated to zero length if
629 it exists, even if CLOBBER is unset.
630
631 >> word
632 Open file word for writing in append mode as standard output.
633 If the file does not exist, and the CLOBBER option is unset,
634 this causes an error; otherwise, the file is created.
635
636 >>| word
637 >>! word
638 Same as >>, except that the file is created if it does not
639 exist, even if CLOBBER is unset.
640
641 <<[-] word
642 The shell input is read up to a line that is the same as word,
643 or to an end-of-file. No parameter expansion, command substitu‐
644 tion or filename generation is performed on word. The resulting
645 document, called a here-document, becomes the standard input.
646
647 If any character of word is quoted with single or double quotes
648 or a `\', no interpretation is placed upon the characters of the
649 document. Otherwise, parameter and command substitution occurs,
650 `\' followed by a newline is removed, and `\' must be used to
651 quote the characters `\', `$', ``' and the first character of
652 word.
653
654 Note that word itself does not undergo shell expansion. Back‐
655 quotes in word do not have their usual effect; instead they
656 behave similarly to double quotes, except that the backquotes
657 themselves are passed through unchanged. (This information is
658 given for completeness and it is not recommended that backquotes
659 be used.) Quotes in the form $'...' have their standard effect
660 of expanding backslashed references to special characters.
661
662 If <<- is used, then all leading tabs are stripped from word and
663 from the document.
664
665 <<< word
666 Perform shell expansion on word and pass the result to standard
667 input. This is known as a here-string. Compare the use of word
668 in here-documents above, where word does not undergo shell
669 expansion.
670
671 <& number
672 >& number
673 The standard input/output is duplicated from file descriptor
674 number (see dup2(2)).
675
676 <& -
677 >& - Close the standard input/output.
678
679 <& p
680 >& p The input/output from/to the coprocess is moved to the standard
681 input/output.
682
683 >& word
684 &> word
685 (Except where `>& word' matches one of the above syntaxes; `&>'
686 can always be used to avoid this ambiguity.) Redirects both
687 standard output and standard error (file descriptor 2) in the
688 manner of `> word'. Note that this does not have the same
689 effect as `> word 2>&1' in the presence of multios (see the sec‐
690 tion below).
691
692 >&| word
693 >&! word
694 &>| word
695 &>! word
696 Redirects both standard output and standard error (file descrip‐
697 tor 2) in the manner of `>| word'.
698
699 >>& word
700 &>> word
701 Redirects both standard output and standard error (file descrip‐
702 tor 2) in the manner of `>> word'.
703
704 >>&| word
705 >>&! word
706 &>>| word
707 &>>! word
708 Redirects both standard output and standard error (file descrip‐
709 tor 2) in the manner of `>>| word'.
710
711 If one of the above is preceded by a digit, then the file descriptor
712 referred to is that specified by the digit instead of the default 0 or
713 1. The order in which redirections are specified is significant. The
714 shell evaluates each redirection in terms of the (file descriptor,
715 file) association at the time of evaluation. For example:
716
717 ... 1>fname 2>&1
718
719 first associates file descriptor 1 with file fname. It then associates
720 file descriptor 2 with the file associated with file descriptor 1 (that
721 is, fname). If the order of redirections were reversed, file descrip‐
722 tor 2 would be associated with the terminal (assuming file descriptor 1
723 had been) and then file descriptor 1 would be associated with file
724 fname.
725
726 The `|&' command separator described in Simple Commands & Pipelines in
727 zshmisc(1) is a shorthand for `2>&1 |'.
728
729 The various forms of process substitution, `<(list)', and `=(list)' for
730 input and `>(list)' for output, are often used together with redirect‐
731 ion. For example, if word in an output redirection is of the form
732 `>(list)' then the output is piped to the command represented by list.
733 See Process Substitution in zshexpn(1).
734
736 When the shell is parsing arguments to a command, and the shell option
737 IGNORE_BRACES is not set, a different form of redirection is allowed:
738 instead of a digit before the operator there is a valid shell identi‐
739 fier enclosed in braces. The shell will open a new file descriptor
740 that is guaranteed to be at least 10 and set the parameter named by the
741 identifier to the file descriptor opened. No whitespace is allowed
742 between the closing brace and the redirection character. For example:
743
744 ... {myfd}>&1
745
746 This opens a new file descriptor that is a duplicate of file descriptor
747 1 and sets the parameter myfd to the number of the file descriptor,
748 which will be at least 10. The new file descriptor can be written to
749 using the syntax >&$myfd.
750
751 The syntax {varid}>&-, for example {myfd}>&-, may be used to close a
752 file descriptor opened in this fashion. Note that the parameter given
753 by varid must previously be set to a file descriptor in this case.
754
755 It is an error to open or close a file descriptor in this fashion when
756 the parameter is readonly. However, it is not an error to read or
757 write a file descriptor using <&$param or >&$param if param is read‐
758 only.
759
760 If the option CLOBBER is unset, it is an error to open a file descrip‐
761 tor using a parameter that is already set to an open file descriptor
762 previously allocated by this mechanism. Unsetting the parameter before
763 using it for allocating a file descriptor avoids the error.
764
765 Note that this mechanism merely allocates or closes a file descriptor;
766 it does not perform any redirections from or to it. It is usually con‐
767 venient to allocate a file descriptor prior to use as an argument to
768 exec. The syntax does not in any case work when used around complex
769 commands such as parenthesised subshells or loops, where the opening
770 brace is interpreted as part of a command list to be executed in the
771 current shell.
772
773 The following shows a typical sequence of allocation, use, and closing
774 of a file descriptor:
775
776 integer myfd
777 exec {myfd}>~/logs/mylogfile.txt
778 print This is a log message. >&$myfd
779 exec {myfd}>&-
780
781 Note that the expansion of the variable in the expression >&$myfd
782 occurs at the point the redirection is opened. This is after the
783 expansion of command arguments and after any redirections to the left
784 on the command line have been processed.
785
787 If the user tries to open a file descriptor for writing more than once,
788 the shell opens the file descriptor as a pipe to a process that copies
789 its input to all the specified outputs, similar to tee, provided the
790 MULTIOS option is set, as it is by default. Thus:
791
792 date >foo >bar
793
794 writes the date to two files, named `foo' and `bar'. Note that a pipe
795 is an implicit redirection; thus
796
797 date >foo | cat
798
799 writes the date to the file `foo', and also pipes it to cat.
800
801 Note that the shell opens all the files to be used in the multio
802 process immediately, not at the point they are about to be written.
803
804 Note also that redirections are always expanded in order. This happens
805 regardless of the setting of the MULTIOS option, but with the option in
806 effect there are additional consequences. For example, the meaning of
807 the expression >&1 will change after a previous redirection:
808
809 date >&1 >output
810
811 In the case above, the >&1 refers to the standard output at the start
812 of the line; the result is similar to the tee command. However, con‐
813 sider:
814
815 date >output >&1
816
817 As redirections are evaluated in order, when the >&1 is encountered the
818 standard output is set to the file output and another copy of the out‐
819 put is therefore sent to that file. This is unlikely to be what is
820 intended.
821
822 If the MULTIOS option is set, the word after a redirection operator is
823 also subjected to filename generation (globbing). Thus
824
825 : > *
826
827 will truncate all files in the current directory, assuming there's at
828 least one. (Without the MULTIOS option, it would create an empty file
829 called `*'.) Similarly, you can do
830
831 echo exit 0 >> *.sh
832
833 If the user tries to open a file descriptor for reading more than once,
834 the shell opens the file descriptor as a pipe to a process that copies
835 all the specified inputs to its output in the order specified, provided
836 the MULTIOS option is set. It should be noted that each file is opened
837 immediately, not at the point where it is about to be read: this behav‐
838 iour differs from cat, so if strictly standard behaviour is needed, cat
839 should be used instead.
840
841 Thus
842
843 sort <foo <fubar
844
845 or even
846
847 sort <f{oo,ubar}
848
849 is equivalent to `cat foo fubar | sort'.
850
851 Expansion of the redirection argument occurs at the point the redirect‐
852 ion is opened, at the point described above for the expansion of the
853 variable in >&$myfd.
854
855 Note that a pipe is an implicit redirection; thus
856
857 cat bar | sort <foo
858
859 is equivalent to `cat bar foo | sort' (note the order of the inputs).
860
861 If the MULTIOS option is unset, each redirection replaces the previous
862 redirection for that file descriptor. However, all files redirected to
863 are actually opened, so
864
865 echo Hello > bar > baz
866
867 when MULTIOS is unset will truncate `bar', and write `Hello' into
868 `baz'.
869
870 There is a problem when an output multio is attached to an external
871 program. A simple example shows this:
872
873 cat file >file1 >file2
874 cat file1 file2
875
876 Here, it is possible that the second `cat' will not display the full
877 contents of file1 and file2 (i.e. the original contents of file
878 repeated twice).
879
880 The reason for this is that the multios are spawned after the cat
881 process is forked from the parent shell, so the parent shell does not
882 wait for the multios to finish writing data. This means the command as
883 shown can exit before file1 and file2 are completely written. As a
884 workaround, it is possible to run the cat process as part of a job in
885 the current shell:
886
887 { cat file } >file >file2
888
889 Here, the {...} job will pause to wait for both files to be written.
890
892 When a simple command consists of one or more redirection operators and
893 zero or more parameter assignments, but no command name, zsh can behave
894 in several ways.
895
896 If the parameter NULLCMD is not set or the option CSH_NULLCMD is set,
897 an error is caused. This is the csh behavior and CSH_NULLCMD is set by
898 default when emulating csh.
899
900 If the option SH_NULLCMD is set, the builtin `:' is inserted as a com‐
901 mand with the given redirections. This is the default when emulating
902 sh or ksh.
903
904 Otherwise, if the parameter NULLCMD is set, its value will be used as a
905 command with the given redirections. If both NULLCMD and READNULLCMD
906 are set, then the value of the latter will be used instead of that of
907 the former when the redirection is an input. The default for NULLCMD
908 is `cat' and for READNULLCMD is `more'. Thus
909
910 < file
911
912 shows the contents of file on standard output, with paging if that is a
913 terminal. NULLCMD and READNULLCMD may refer to shell functions.
914
916 If a command name contains no slashes, the shell attempts to locate it.
917 If there exists a shell function by that name, the function is invoked
918 as described in the section `Functions'. If there exists a shell
919 builtin by that name, the builtin is invoked.
920
921 Otherwise, the shell searches each element of $path for a directory
922 containing an executable file by that name. If the search is unsuc‐
923 cessful, the shell prints an error message and returns a nonzero exit
924 status.
925
926 If execution fails because the file is not in executable format, and
927 the file is not a directory, it is assumed to be a shell script.
928 /bin/sh is spawned to execute it. If the program is a file beginning
929 with `#!', the remainder of the first line specifies an interpreter for
930 the program. The shell will execute the specified interpreter on oper‐
931 ating systems that do not handle this executable format in the kernel.
932
933 If no external command is found but a function command_not_found_han‐
934 dler exists the shell executes this function with all command line
935 arguments. The return status of the function becomes the status of the
936 command. If the function wishes to mimic the behaviour of the shell
937 when the command is not found, it should print the message `command not
938 found: cmd' to standard error and return status 127. Note that the
939 handler is executed in a subshell forked to execute an external com‐
940 mand, hence changes to directories, shell parameters, etc. have no
941 effect on the main shell.
942
944 Shell functions are defined with the function reserved word or the spe‐
945 cial syntax `funcname ()'. Shell functions are read in and stored
946 internally. Alias names are resolved when the function is read. Func‐
947 tions are executed like commands with the arguments passed as posi‐
948 tional parameters. (See the section `Command Execution'.)
949
950 Functions execute in the same process as the caller and share all files
951 and present working directory with the caller. A trap on EXIT set
952 inside a function is executed after the function completes in the envi‐
953 ronment of the caller.
954
955 The return builtin is used to return from function calls.
956
957 Function identifiers can be listed with the functions builtin. Func‐
958 tions can be undefined with the unfunction builtin.
959
961 A function can be marked as undefined using the autoload builtin (or
962 `functions -u' or `typeset -fu'). Such a function has no body. When
963 the function is first executed, the shell searches for its definition
964 using the elements of the fpath variable. Thus to define functions for
965 autoloading, a typical sequence is:
966
967 fpath=(~/myfuncs $fpath)
968 autoload myfunc1 myfunc2 ...
969
970 The usual alias expansion during reading will be suppressed if the
971 autoload builtin or its equivalent is given the option -U. This is rec‐
972 ommended for the use of functions supplied with the zsh distribution.
973 Note that for functions precompiled with the zcompile builtin command
974 the flag -U must be provided when the .zwc file is created, as the cor‐
975 responding information is compiled into the latter.
976
977 For each element in fpath, the shell looks for three possible files,
978 the newest of which is used to load the definition for the function:
979
980 element.zwc
981 A file created with the zcompile builtin command, which is
982 expected to contain the definitions for all functions in the
983 directory named element. The file is treated in the same manner
984 as a directory containing files for functions and is searched
985 for the definition of the function. If the definition is not
986 found, the search for a definition proceeds with the other two
987 possibilities described below.
988
989 If element already includes a .zwc extension (i.e. the extension
990 was explicitly given by the user), element is searched for the
991 definition of the function without comparing its age to that of
992 other files; in fact, there does not need to be any directory
993 named element without the suffix. Thus including an element
994 such as `/usr/local/funcs.zwc' in fpath will speed up the search
995 for functions, with the disadvantage that functions included
996 must be explicitly recompiled by hand before the shell notices
997 any changes.
998
999 element/function.zwc
1000 A file created with zcompile, which is expected to contain the
1001 definition for function. It may include other function defini‐
1002 tions as well, but those are neither loaded nor executed; a file
1003 found in this way is searched only for the definition of func‐
1004 tion.
1005
1006 element/function
1007 A file of zsh command text, taken to be the definition for func‐
1008 tion.
1009
1010 In summary, the order of searching is, first, in the parents of direc‐
1011 tories in fpath for the newer of either a compiled directory or a
1012 directory in fpath; second, if more than one of these contains a defi‐
1013 nition for the function that is sought, the leftmost in the fpath is
1014 chosen; and third, within a directory, the newer of either a compiled
1015 function or an ordinary function definition is used.
1016
1017 If the KSH_AUTOLOAD option is set, or the file contains only a simple
1018 definition of the function, the file's contents will be executed. This
1019 will normally define the function in question, but may also perform
1020 initialization, which is executed in the context of the function execu‐
1021 tion, and may therefore define local parameters. It is an error if the
1022 function is not defined by loading the file.
1023
1024 Otherwise, the function body (with no surrounding `funcname() {...}')
1025 is taken to be the complete contents of the file. This form allows the
1026 file to be used directly as an executable shell script. If processing
1027 of the file results in the function being re-defined, the function
1028 itself is not re-executed. To force the shell to perform initializa‐
1029 tion and then call the function defined, the file should contain ini‐
1030 tialization code (which will be executed then discarded) in addition to
1031 a complete function definition (which will be retained for subsequent
1032 calls to the function), and a call to the shell function, including any
1033 arguments, at the end.
1034
1035 For example, suppose the autoload file func contains
1036
1037 func() { print This is func; }
1038 print func is initialized
1039
1040 then `func; func' with KSH_AUTOLOAD set will produce both messages on
1041 the first call, but only the message `This is func' on the second and
1042 subsequent calls. Without KSH_AUTOLOAD set, it will produce the ini‐
1043 tialization message on the first call, and the other message on the
1044 second and subsequent calls.
1045
1046 It is also possible to create a function that is not marked as
1047 autoloaded, but which loads its own definition by searching fpath, by
1048 using `autoload -X' within a shell function. For example, the follow‐
1049 ing are equivalent:
1050
1051 myfunc() {
1052 autoload -X
1053 }
1054 myfunc args...
1055
1056 and
1057
1058 unfunction myfunc # if myfunc was defined
1059 autoload myfunc
1060 myfunc args...
1061
1062 In fact, the functions command outputs `builtin autoload -X' as the
1063 body of an autoloaded function. This is done so that
1064
1065 eval "$(functions)"
1066
1067 produces a reasonable result. A true autoloaded function can be iden‐
1068 tified by the presence of the comment `# undefined' in the body,
1069 because all comments are discarded from defined functions.
1070
1071 To load the definition of an autoloaded function myfunc without execut‐
1072 ing myfunc, use:
1073
1074 autoload +X myfunc
1075
1077 If no name is given for a function, it is `anonymous' and is handled
1078 specially. Either form of function definition may be used: a `()' with
1079 no preceding name, or a `function' with an immediately following open
1080 brace. The function is executed immediately at the point of definition
1081 and is not stored for future use. The function name is set to
1082 `(anon)'.
1083
1084 Arguments to the function may be specified as words following the clos‐
1085 ing brace defining the function, hence if there are none no arguments
1086 (other than $0) are set. This is a difference from the way other func‐
1087 tions are parsed: normal function definitions may be followed by cer‐
1088 tain keywords such as `else' or `fi', which will be treated as argu‐
1089 ments to anonymous functions, so that a newline or semicolon is needed
1090 to force keyword interpretation.
1091
1092 Note also that the argument list of any enclosing script or function is
1093 hidden (as would be the case for any other function called at this
1094 point).
1095
1096 Redirections may be applied to the anonymous function in the same man‐
1097 ner as to a current-shell structure enclosed in braces. The main use
1098 of anonymous functions is to provide a scope for local variables. This
1099 is particularly convenient in start-up files as these do not provide
1100 their own local variable scope.
1101
1102 For example,
1103
1104 variable=outside
1105 function {
1106 local variable=inside
1107 print "I am $variable with arguments $*"
1108 } this and that
1109 print "I am $variable"
1110
1111 outputs the following:
1112
1113 I am inside with arguments this and that
1114 I am outside
1115
1116 Note that function definitions with arguments that expand to nothing,
1117 for example `name=; function $name { ... }', are not treated as anony‐
1118 mous functions. Instead, they are treated as normal function defini‐
1119 tions where the definition is silently discarded.
1120
1122 Certain functions, if defined, have special meaning to the shell.
1123
1124 Hook Functions
1125 For the functions below, it is possible to define an array that has the
1126 same name as the function with `_functions' appended. Any element in
1127 such an array is taken as the name of a function to execute; it is exe‐
1128 cuted in the same context and with the same arguments as the basic
1129 function. For example, if $chpwd_functions is an array containing the
1130 values `mychpwd', `chpwd_save_dirstack', then the shell attempts to
1131 execute the functions `chpwd', `mychpwd' and `chpwd_save_dirstack', in
1132 that order. Any function that does not exist is silently ignored. A
1133 function found by this mechanism is referred to elsewhere as a `hook
1134 function'. An error in any function causes subsequent functions not to
1135 be run. Note further that an error in a precmd hook causes an immedi‐
1136 ately following periodic function not to run (though it may run at the
1137 next opportunity).
1138
1139 chpwd Executed whenever the current working directory is changed.
1140
1141 periodic
1142 If the parameter PERIOD is set, this function is executed every
1143 $PERIOD seconds, just before a prompt. Note that if multiple
1144 functions are defined using the array periodic_functions only
1145 one period is applied to the complete set of functions, and the
1146 scheduled time is not reset if the list of functions is altered.
1147 Hence the set of functions is always called together.
1148
1149 precmd Executed before each prompt. Note that precommand functions are
1150 not re-executed simply because the command line is redrawn, as
1151 happens, for example, when a notification about an exiting job
1152 is displayed.
1153
1154 preexec
1155 Executed just after a command has been read and is about to be
1156 executed. If the history mechanism is active (regardless of
1157 whether the line was discarded from the history buffer), the
1158 string that the user typed is passed as the first argument, oth‐
1159 erwise it is an empty string. The actual command that will be
1160 executed (including expanded aliases) is passed in two different
1161 forms: the second argument is a single-line, size-limited ver‐
1162 sion of the command (with things like function bodies elided);
1163 the third argument contains the full text that is being exe‐
1164 cuted.
1165
1166 zshaddhistory
1167 Executed when a history line has been read interactively, but
1168 before it is executed. The sole argument is the complete his‐
1169 tory line (so that any terminating newline will still be
1170 present).
1171
1172 If any of the hook functions returns status 1 (or any non-zero
1173 value other than 2, though this is not guaranteed for future
1174 versions of the shell) the history line will not be saved,
1175 although it lingers in the history until the next line is exe‐
1176 cuted, allowing you to reuse or edit it immediately.
1177
1178 If any of the hook functions returns status 2 the history line
1179 will be saved on the internal history list, but not written to
1180 the history file. In case of a conflict, the first non-zero
1181 status value is taken.
1182
1183 A hook function may call `fc -p ...' to switch the history con‐
1184 text so that the history is saved in a different file from the
1185 that in the global HISTFILE parameter. This is handled spe‐
1186 cially: the history context is automatically restored after the
1187 processing of the history line is finished.
1188
1189 The following example function works with one of the options
1190 INC_APPEND_HISTORY or SHARE_HISTORY set, in order that the line
1191 is written out immediately after the history entry is added. It
1192 first adds the history line to the normal history with the new‐
1193 line stripped, which is usually the correct behaviour. Then it
1194 switches the history context so that the line will be written to
1195 a history file in the current directory.
1196
1197 zshaddhistory() {
1198 print -sr -- ${1%%$'\n'}
1199 fc -p .zsh_local_history
1200 }
1201
1202 zshexit
1203 Executed at the point where the main shell is about to exit nor‐
1204 mally. This is not called by exiting subshells, nor when the
1205 exec precommand modifier is used before an external command.
1206 Also, unlike TRAPEXIT, it is not called when functions exit.
1207
1208 Trap Functions
1209 The functions below are treated specially but do not have corresponding
1210 hook arrays.
1211
1212 TRAPNAL
1213 If defined and non-null, this function will be executed whenever
1214 the shell catches a signal SIGNAL, where NAL is a signal name as
1215 specified for the kill builtin. The signal number will be
1216 passed as the first parameter to the function.
1217
1218 If a function of this form is defined and null, the shell and
1219 processes spawned by it will ignore SIGNAL.
1220
1221 The return status from the function is handled specially. If it
1222 is zero, the signal is assumed to have been handled, and execu‐
1223 tion continues normally. Otherwise, the shell will behave as
1224 interrupted except that the return status of the trap is
1225 retained.
1226
1227 Programs terminated by uncaught signals typically return the
1228 status 128 plus the signal number. Hence the following causes
1229 the handler for SIGINT to print a message, then mimic the usual
1230 effect of the signal.
1231
1232 TRAPINT() {
1233 print "Caught SIGINT, aborting."
1234 return $(( 128 + $1 ))
1235 }
1236
1237 The functions TRAPZERR, TRAPDEBUG and TRAPEXIT are never exe‐
1238 cuted inside other traps.
1239
1240 TRAPDEBUG
1241 If the option DEBUG_BEFORE_CMD is set (as it is by default),
1242 executed before each command; otherwise executed after each com‐
1243 mand. See the description of the trap builtin in zshbuiltins(1)
1244 for details of additional features provided in debug traps.
1245
1246 TRAPEXIT
1247 Executed when the shell exits, or when the current function
1248 exits if defined inside a function. The value of $? at the
1249 start of execution is the exit status of the shell or the return
1250 status of the function exiting.
1251
1252 TRAPZERR
1253 Executed whenever a command has a non-zero exit status. How‐
1254 ever, the function is not executed if the command occurred in a
1255 sublist followed by `&&' or `||'; only the final command in a
1256 sublist of this type causes the trap to be executed. The func‐
1257 tion TRAPERR acts the same as TRAPZERR on systems where there is
1258 no SIGERR (this is the usual case).
1259
1260 The functions beginning `TRAP' may alternatively be defined with the
1261 trap builtin: this may be preferable for some uses. Setting a trap
1262 with one form removes any trap of the other form for the same signal;
1263 removing a trap in either form removes all traps for the same signal.
1264 The forms
1265
1266 TRAPNAL() {
1267 # code
1268 }
1269
1270 ('function traps') and
1271
1272 trap '
1273 # code
1274 ' NAL
1275
1276 ('list traps') are equivalent in most ways, the exceptions being the
1277 following:
1278
1279 · Function traps have all the properties of normal functions,
1280 appearing in the list of functions and being called with their
1281 own function context rather than the context where the trap was
1282 triggered.
1283
1284 · The return status from function traps is special, whereas a
1285 return from a list trap causes the surrounding context to return
1286 with the given status.
1287
1288 · Function traps are not reset within subshells, in accordance
1289 with zsh behaviour; list traps are reset, in accordance with
1290 POSIX behaviour.
1291
1293 If the MONITOR option is set, an interactive shell associates a job
1294 with each pipeline. It keeps a table of current jobs, printed by the
1295 jobs command, and assigns them small integer numbers. When a job is
1296 started asynchronously with `&', the shell prints a line to standard
1297 error which looks like:
1298
1299 [1] 1234
1300
1301 indicating that the job which was started asynchronously was job number
1302 1 and had one (top-level) process, whose process ID was 1234.
1303
1304 If a job is started with `&|' or `&!', then that job is immediately
1305 disowned. After startup, it does not have a place in the job table,
1306 and is not subject to the job control features described here.
1307
1308 If you are running a job and wish to do something else you may hit the
1309 key ^Z (control-Z) which sends a TSTP signal to the current job: this
1310 key may be redefined by the susp option of the external stty command.
1311 The shell will then normally indicate that the job has been `sus‐
1312 pended', and print another prompt. You can then manipulate the state
1313 of this job, putting it in the background with the bg command, or run
1314 some other commands and then eventually bring the job back into the
1315 foreground with the foreground command fg. A ^Z takes effect immedi‐
1316 ately and is like an interrupt in that pending output and unread input
1317 are discarded when it is typed.
1318
1319 A job being run in the background will suspend if it tries to read from
1320 the terminal.
1321
1322 Note that if the job running in the foreground is a shell function,
1323 then suspending it will have the effect of causing the shell to fork.
1324 This is necessary to separate the function's state from that of the
1325 parent shell performing the job control, so that the latter can return
1326 to the command line prompt. As a result, even if fg is used to con‐
1327 tinue the job the function will no longer be part of the parent shell,
1328 and any variables set by the function will not be visible in the parent
1329 shell. Thus the behaviour is different from the case where the func‐
1330 tion was never suspended. Zsh is different from many other shells in
1331 this regard.
1332
1333 One additional side effect is that use of disown with a job created by
1334 suspending shell code in this fashion is delayed: the job can only be
1335 disowned once any process started from the parent shell has terminated.
1336 At that point, the disowned job disappears silently from the job list.
1337
1338 The same behaviour is found when the shell is executing code as the
1339 right hand side of a pipeline or any complex shell construct such as
1340 if, for, etc., in order that the entire block of code can be managed as
1341 a single job. Background jobs are normally allowed to produce output,
1342 but this can be disabled by giving the command `stty tostop'. If you
1343 set this tty option, then background jobs will suspend when they try to
1344 produce output like they do when they try to read input.
1345
1346 When a command is suspended and continued later with the fg or wait
1347 builtins, zsh restores tty modes that were in effect when it was sus‐
1348 pended. This (intentionally) does not apply if the command is contin‐
1349 ued via `kill -CONT', nor when it is continued with bg.
1350
1351 There are several ways to refer to jobs in the shell. A job can be
1352 referred to by the process ID of any process of the job or by one of
1353 the following:
1354
1355 %number
1356 The job with the given number.
1357 %string
1358 The last job whose command line begins with string.
1359 %?string
1360 The last job whose command line contains string.
1361 %% Current job.
1362 %+ Equivalent to `%%'.
1363 %- Previous job.
1364
1365 The shell learns immediately whenever a process changes state. It nor‐
1366 mally informs you whenever a job becomes blocked so that no further
1367 progress is possible. If the NOTIFY option is not set, it waits until
1368 just before it prints a prompt before it informs you. All such notifi‐
1369 cations are sent directly to the terminal, not to the standard output
1370 or standard error.
1371
1372 When the monitor mode is on, each background job that completes trig‐
1373 gers any trap set for CHLD.
1374
1375 When you try to leave the shell while jobs are running or suspended,
1376 you will be warned that `You have suspended (running) jobs'. You may
1377 use the jobs command to see what they are. If you do this or immedi‐
1378 ately try to exit again, the shell will not warn you a second time; the
1379 suspended jobs will be terminated, and the running jobs will be sent a
1380 SIGHUP signal, if the HUP option is set.
1381
1382 To avoid having the shell terminate the running jobs, either use the
1383 nohup command (see nohup(1)) or the disown builtin.
1384
1386 The INT and QUIT signals for an invoked command are ignored if the com‐
1387 mand is followed by `&' and the MONITOR option is not active. The
1388 shell itself always ignores the QUIT signal. Otherwise, signals have
1389 the values inherited by the shell from its parent (but see the TRAPNAL
1390 special functions in the section `Functions').
1391
1392 Certain jobs are run asynchronously by the shell other than those
1393 explicitly put into the background; even in cases where the shell would
1394 usually wait for such jobs, an explicit exit command or exit due to the
1395 option ERR_EXIT will cause the shell to exit without waiting. Examples
1396 of such asynchronous jobs are process substitution, see the section
1397 PROCESS SUBSTITUTION in the zshexpn(1) manual page, and the handler
1398 processes for multios, see the section MULTIOS in the zshmisc(1) manual
1399 page.
1400
1402 The shell can perform integer and floating point arithmetic, either
1403 using the builtin let, or via a substitution of the form $((...)). For
1404 integers, the shell is usually compiled to use 8-byte precision where
1405 this is available, otherwise precision is 4 bytes. This can be tested,
1406 for example, by giving the command `print - $(( 12345678901 ))'; if the
1407 number appears unchanged, the precision is at least 8 bytes. Floating
1408 point arithmetic always uses the `double' type with whatever corre‐
1409 sponding precision is provided by the compiler and the library.
1410
1411 The let builtin command takes arithmetic expressions as arguments; each
1412 is evaluated separately. Since many of the arithmetic operators, as
1413 well as spaces, require quoting, an alternative form is provided: for
1414 any command which begins with a `((', all the characters until a match‐
1415 ing `))' are treated as a quoted expression and arithmetic expansion
1416 performed as for an argument of let. More precisely, `((...))' is
1417 equivalent to `let "..."'. The return status is 0 if the arithmetic
1418 value of the expression is non-zero, 1 if it is zero, and 2 if an error
1419 occurred.
1420
1421 For example, the following statement
1422
1423 (( val = 2 + 1 ))
1424
1425 is equivalent to
1426
1427 let "val = 2 + 1"
1428
1429 both assigning the value 3 to the shell variable val and returning a
1430 zero status.
1431
1432 Integers can be in bases other than 10. A leading `0x' or `0X' denotes
1433 hexadecimal and a leading `0b' or `0B' binary. Integers may also be of
1434 the form `base#n', where base is a decimal number between two and
1435 thirty-six representing the arithmetic base and n is a number in that
1436 base (for example, `16#ff' is 255 in hexadecimal). The base# may also
1437 be omitted, in which case base 10 is used. For backwards compatibility
1438 the form `[base]n' is also accepted.
1439
1440 An integer expression or a base given in the form `base#n' may contain
1441 underscores (`_') after the leading digit for visual guidance; these
1442 are ignored in computation. Examples are 1_000_000 or 0xffff_ffff
1443 which are equivalent to 1000000 and 0xffffffff respectively.
1444
1445 It is also possible to specify a base to be used for output in the form
1446 `[#base]', for example `[#16]'. This is used when outputting arith‐
1447 metical substitutions or when assigning to scalar parameters, but an
1448 explicitly defined integer or floating point parameter will not be
1449 affected. If an integer variable is implicitly defined by an arith‐
1450 metic expression, any base specified in this way will be set as the
1451 variable's output arithmetic base as if the option `-i base' to the
1452 typeset builtin had been used. The expression has no precedence and if
1453 it occurs more than once in a mathematical expression, the last encoun‐
1454 tered is used. For clarity it is recommended that it appear at the
1455 beginning of an expression. As an example:
1456
1457 typeset -i 16 y
1458 print $(( [#8] x = 32, y = 32 ))
1459 print $x $y
1460
1461 outputs first `8#40', the rightmost value in the given output base, and
1462 then `8#40 16#20', because y has been explicitly declared to have out‐
1463 put base 16, while x (assuming it does not already exist) is implicitly
1464 typed by the arithmetic evaluation, where it acquires the output base
1465 8.
1466
1467 The base may be replaced or followed by an underscore, which may itself
1468 be followed by a positive integer (if it is missing the value 3 is
1469 used). This indicates that underscores should be inserted into the
1470 output string, grouping the number for visual clarity. The following
1471 integer specifies the number of digits to group together. For example:
1472
1473 setopt cbases
1474 print $(( [#16_4] 65536 ** 2 ))
1475
1476 outputs `0x1_0000_0000'.
1477
1478 The feature can be used with floating point numbers, in which case the
1479 base must be omitted; grouping is away from the decimal point. For
1480 example,
1481
1482 zmodload zsh/mathfunc
1483 print $(( [#_] sqrt(1e7) ))
1484
1485 outputs `3_162.277_660_168_379_5' (the number of decimal places shown
1486 may vary).
1487
1488 If the C_BASES option is set, hexadecimal numbers are output in the
1489 standard C format, for example `0xFF' instead of the usual `16#FF'. If
1490 the option OCTAL_ZEROES is also set (it is not by default), octal num‐
1491 bers will be treated similarly and hence appear as `077' instead of
1492 `8#77'. This option has no effect on the output of bases other than
1493 hexadecimal and octal, and these formats are always understood on
1494 input.
1495
1496 When an output base is specified using the `[#base]' syntax, an appro‐
1497 priate base prefix will be output if necessary, so that the value out‐
1498 put is valid syntax for input. If the # is doubled, for example
1499 `[##16]', then no base prefix is output.
1500
1501 Floating point constants are recognized by the presence of a decimal
1502 point or an exponent. The decimal point may be the first character of
1503 the constant, but the exponent character e or E may not, as it will be
1504 taken for a parameter name. All numeric parts (before and after the
1505 decimal point and in the exponent) may contain underscores after the
1506 leading digit for visual guidance; these are ignored in computation.
1507
1508 An arithmetic expression uses nearly the same syntax and associativity
1509 of expressions as in C.
1510
1511 In the native mode of operation, the following operators are supported
1512 (listed in decreasing order of precedence):
1513
1514 + - ! ~ ++ --
1515 unary plus/minus, logical NOT, complement, {pre,post}{in,de}cre‐
1516 ment
1517 << >> bitwise shift left, right
1518 & bitwise AND
1519 ^ bitwise XOR
1520 | bitwise OR
1521 ** exponentiation
1522 * / % multiplication, division, modulus (remainder)
1523 + - addition, subtraction
1524 < > <= >=
1525 comparison
1526 == != equality and inequality
1527 && logical AND
1528 || ^^ logical OR, XOR
1529 ? : ternary operator
1530 = += -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **=
1531 assignment
1532 , comma operator
1533
1534 The operators `&&', `||', `&&=', and `||=' are short-circuiting, and
1535 only one of the latter two expressions in a ternary operator is evalu‐
1536 ated. Note the precedence of the bitwise AND, OR, and XOR operators.
1537
1538 With the option C_PRECEDENCES the precedences (but no other properties)
1539 of the operators are altered to be the same as those in most other lan‐
1540 guages that support the relevant operators:
1541
1542 + - ! ~ ++ --
1543 unary plus/minus, logical NOT, complement, {pre,post}{in,de}cre‐
1544 ment
1545 ** exponentiation
1546 * / % multiplication, division, modulus (remainder)
1547 + - addition, subtraction
1548 << >> bitwise shift left, right
1549 < > <= >=
1550 comparison
1551 == != equality and inequality
1552 & bitwise AND
1553 ^ bitwise XOR
1554 | bitwise OR
1555 && logical AND
1556 ^^ logical XOR
1557 || logical OR
1558 ? : ternary operator
1559 = += -= *= /= %= &= ^= |= <<= >>= &&= ||= ^^= **=
1560 assignment
1561 , comma operator
1562
1563 Note the precedence of exponentiation in both cases is below that of
1564 unary operators, hence `-3**2' evaluates as `9', not `-9'. Use paren‐
1565 theses where necessary: `-(3**2)'. This is for compatibility with
1566 other shells.
1567
1568 Mathematical functions can be called with the syntax `func(args)',
1569 where the function decides if the args is used as a string or a
1570 comma-separated list of arithmetic expressions. The shell currently
1571 defines no mathematical functions by default, but the module zsh/math‐
1572 func may be loaded with the zmodload builtin to provide standard float‐
1573 ing point mathematical functions.
1574
1575 An expression of the form `##x' where x is any character sequence such
1576 as `a', `^A', or `\M-\C-x' gives the value of this character and an
1577 expression of the form `#name' gives the value of the first character
1578 of the contents of the parameter name. Character values are according
1579 to the character set used in the current locale; for multibyte charac‐
1580 ter handling the option MULTIBYTE must be set. Note that this form is
1581 different from `$#name', a standard parameter substitution which gives
1582 the length of the parameter name. `#\' is accepted instead of `##',
1583 but its use is deprecated.
1584
1585 Named parameters and subscripted arrays can be referenced by name
1586 within an arithmetic expression without using the parameter expansion
1587 syntax. For example,
1588
1589 ((val2 = val1 * 2))
1590
1591 assigns twice the value of $val1 to the parameter named val2.
1592
1593 An internal integer representation of a named parameter can be speci‐
1594 fied with the integer builtin. Arithmetic evaluation is performed on
1595 the value of each assignment to a named parameter declared integer in
1596 this manner. Assigning a floating point number to an integer results
1597 in rounding towards zero.
1598
1599 Likewise, floating point numbers can be declared with the float
1600 builtin; there are two types, differing only in their output format, as
1601 described for the typeset builtin. The output format can be bypassed
1602 by using arithmetic substitution instead of the parameter substitution,
1603 i.e. `${float}' uses the defined format, but `$((float))' uses a
1604 generic floating point format.
1605
1606 Promotion of integer to floating point values is performed where neces‐
1607 sary. In addition, if any operator which requires an integer (`&',
1608 `|', `^', `<<', `>>' and their equivalents with assignment) is given a
1609 floating point argument, it will be silently rounded towards zero
1610 except for `~' which rounds down.
1611
1612 Users should beware that, in common with many other programming lan‐
1613 guages but not software designed for calculation, the evaluation of an
1614 expression in zsh is taken a term at a time and promotion of integers
1615 to floating point does not occur in terms only containing integers. A
1616 typical result of this is that a division such as 6/8 is truncated, in
1617 this being rounded towards 0. The FORCE_FLOAT shell option can be used
1618 in scripts or functions where floating point evaluation is required
1619 throughout.
1620
1621 Scalar variables can hold integer or floating point values at different
1622 times; there is no memory of the numeric type in this case.
1623
1624 If a variable is first assigned in a numeric context without previously
1625 being declared, it will be implicitly typed as integer or float and
1626 retain that type either until the type is explicitly changed or until
1627 the end of the scope. This can have unforeseen consequences. For
1628 example, in the loop
1629
1630 for (( f = 0; f < 1; f += 0.1 )); do
1631 # use $f
1632 done
1633
1634 if f has not already been declared, the first assignment will cause it
1635 to be created as an integer, and consequently the operation `f += 0.1'
1636 will always cause the result to be truncated to zero, so that the loop
1637 will fail. A simple fix would be to turn the initialization into `f =
1638 0.0'. It is therefore best to declare numeric variables with explicit
1639 types.
1640
1642 A conditional expression is used with the [[ compound command to test
1643 attributes of files and to compare strings. Each expression can be
1644 constructed from one or more of the following unary or binary expres‐
1645 sions:
1646
1647 -a file
1648 true if file exists.
1649
1650 -b file
1651 true if file exists and is a block special file.
1652
1653 -c file
1654 true if file exists and is a character special file.
1655
1656 -d file
1657 true if file exists and is a directory.
1658
1659 -e file
1660 true if file exists.
1661
1662 -f file
1663 true if file exists and is a regular file.
1664
1665 -g file
1666 true if file exists and has its setgid bit set.
1667
1668 -h file
1669 true if file exists and is a symbolic link.
1670
1671 -k file
1672 true if file exists and has its sticky bit set.
1673
1674 -n string
1675 true if length of string is non-zero.
1676
1677 -o option
1678 true if option named option is on. option may be a single char‐
1679 acter, in which case it is a single letter option name. (See
1680 the section `Specifying Options'.)
1681
1682 When no option named option exists, and the POSIX_BUILTINS
1683 option hasn't been set, return 3 with a warning. If that option
1684 is set, return 1 with no warning.
1685
1686 -p file
1687 true if file exists and is a FIFO special file (named pipe).
1688
1689 -r file
1690 true if file exists and is readable by current process.
1691
1692 -s file
1693 true if file exists and has size greater than zero.
1694
1695 -t fd true if file descriptor number fd is open and associated with a
1696 terminal device. (note: fd is not optional)
1697
1698 -u file
1699 true if file exists and has its setuid bit set.
1700
1701 -v varname
1702 true if shell variable varname is set.
1703
1704 -w file
1705 true if file exists and is writable by current process.
1706
1707 -x file
1708 true if file exists and is executable by current process. If
1709 file exists and is a directory, then the current process has
1710 permission to search in the directory.
1711
1712 -z string
1713 true if length of string is zero.
1714
1715 -L file
1716 true if file exists and is a symbolic link.
1717
1718 -O file
1719 true if file exists and is owned by the effective user ID of
1720 this process.
1721
1722 -G file
1723 true if file exists and its group matches the effective group ID
1724 of this process.
1725
1726 -S file
1727 true if file exists and is a socket.
1728
1729 -N file
1730 true if file exists and its access time is not newer than its
1731 modification time.
1732
1733 file1 -nt file2
1734 true if file1 exists and is newer than file2.
1735
1736 file1 -ot file2
1737 true if file1 exists and is older than file2.
1738
1739 file1 -ef file2
1740 true if file1 and file2 exist and refer to the same file.
1741
1742 string = pattern
1743 string == pattern
1744 true if string matches pattern. The two forms are exactly
1745 equivalent. The `=' form is the traditional shell syntax (and
1746 hence the only one generally used with the test and [ builtins);
1747 the `==' form provides compatibility with other sorts of com‐
1748 puter language.
1749
1750 string != pattern
1751 true if string does not match pattern.
1752
1753 string =~ regexp
1754 true if string matches the regular expression regexp. If the
1755 option RE_MATCH_PCRE is set regexp is tested as a PCRE regular
1756 expression using the zsh/pcre module, else it is tested as a
1757 POSIX extended regular expression using the zsh/regex module.
1758 Upon successful match, some variables will be updated; no vari‐
1759 ables are changed if the matching fails.
1760
1761 If the option BASH_REMATCH is not set the scalar parameter MATCH
1762 is set to the substring that matched the pattern and the integer
1763 parameters MBEGIN and MEND to the index of the start and end,
1764 respectively, of the match in string, such that if string is
1765 contained in variable var the expression `${var[$MBEGIN,$MEND]}'
1766 is identical to `$MATCH'. The setting of the option KSH_ARRAYS
1767 is respected. Likewise, the array match is set to the sub‐
1768 strings that matched parenthesised subexpressions and the arrays
1769 mbegin and mend to the indices of the start and end positions,
1770 respectively, of the substrings within string. The arrays are
1771 not set if there were no parenthesised subexpresssions. For
1772 example, if the string `a short string' is matched against the
1773 regular expression `s(...)t', then (assuming the option
1774 KSH_ARRAYS is not set) MATCH, MBEGIN and MEND are `short', 3 and
1775 7, respectively, while match, mbegin and mend are single entry
1776 arrays containing the strings `hor', `4' and `6', respectively.
1777
1778 If the option BASH_REMATCH is set the array BASH_REMATCH is set
1779 to the substring that matched the pattern followed by the sub‐
1780 strings that matched parenthesised subexpressions within the
1781 pattern.
1782
1783 string1 < string2
1784 true if string1 comes before string2 based on ASCII value of
1785 their characters.
1786
1787 string1 > string2
1788 true if string1 comes after string2 based on ASCII value of
1789 their characters.
1790
1791 exp1 -eq exp2
1792 true if exp1 is numerically equal to exp2. Note that for purely
1793 numeric comparisons use of the ((...)) builtin described in the
1794 section `ARITHMETIC EVALUATION' is more convenient than condi‐
1795 tional expressions.
1796
1797 exp1 -ne exp2
1798 true if exp1 is numerically not equal to exp2.
1799
1800 exp1 -lt exp2
1801 true if exp1 is numerically less than exp2.
1802
1803 exp1 -gt exp2
1804 true if exp1 is numerically greater than exp2.
1805
1806 exp1 -le exp2
1807 true if exp1 is numerically less than or equal to exp2.
1808
1809 exp1 -ge exp2
1810 true if exp1 is numerically greater than or equal to exp2.
1811
1812 ( exp )
1813 true if exp is true.
1814
1815 ! exp true if exp is false.
1816
1817 exp1 && exp2
1818 true if exp1 and exp2 are both true.
1819
1820 exp1 || exp2
1821 true if either exp1 or exp2 is true.
1822
1823 For compatibility, if there is a single argument that is not syntacti‐
1824 cally significant, typically a variable, the condition is treated as a
1825 test for whether the expression expands as a string of non-zero length.
1826 In other words, [[ $var ]] is the same as [[ -n $var ]]. It is recom‐
1827 mended that the second, explicit, form be used where possible.
1828
1829 Normal shell expansion is performed on the file, string and pattern
1830 arguments, but the result of each expansion is constrained to be a sin‐
1831 gle word, similar to the effect of double quotes.
1832
1833 Filename generation is not performed on any form of argument to condi‐
1834 tions. However, it can be forced in any case where normal shell expan‐
1835 sion is valid and when the option EXTENDED_GLOB is in effect by using
1836 an explicit glob qualifier of the form (#q) at the end of the string.
1837 A normal glob qualifier expression may appear between the `q' and the
1838 closing parenthesis; if none appears the expression has no effect
1839 beyond causing filename generation. The results of filename generation
1840 are joined together to form a single word, as with the results of other
1841 forms of expansion.
1842
1843 This special use of filename generation is only available with the [[
1844 syntax. If the condition occurs within the [ or test builtin commands
1845 then globbing occurs instead as part of normal command line expansion
1846 before the condition is evaluated. In this case it may generate multi‐
1847 ple words which are likely to confuse the syntax of the test command.
1848
1849 For example,
1850
1851 [[ -n file*(#qN) ]]
1852
1853 produces status zero if and only if there is at least one file in the
1854 current directory beginning with the string `file'. The globbing qual‐
1855 ifier N ensures that the expression is empty if there is no matching
1856 file.
1857
1858 Pattern metacharacters are active for the pattern arguments; the pat‐
1859 terns are the same as those used for filename generation, see zsh‐
1860 expn(1), but there is no special behaviour of `/' nor initial dots, and
1861 no glob qualifiers are allowed.
1862
1863 In each of the above expressions, if file is of the form `/dev/fd/n',
1864 where n is an integer, then the test applied to the open file whose
1865 descriptor number is n, even if the underlying system does not support
1866 the /dev/fd directory.
1867
1868 In the forms which do numeric comparison, the expressions exp undergo
1869 arithmetic expansion as if they were enclosed in $((...)).
1870
1871 For example, the following:
1872
1873 [[ ( -f foo || -f bar ) && $report = y* ]] && print File exists.
1874
1875 tests if either file foo or file bar exists, and if so, if the value of
1876 the parameter report begins with `y'; if the complete condition is
1877 true, the message `File exists.' is printed.
1878
1880 Prompt sequences undergo a special form of expansion. This type of
1881 expansion is also available using the -P option to the print builtin.
1882
1883 If the PROMPT_SUBST option is set, the prompt string is first subjected
1884 to parameter expansion, command substitution and arithmetic expansion.
1885 See zshexpn(1).
1886
1887 Certain escape sequences may be recognised in the prompt string.
1888
1889 If the PROMPT_BANG option is set, a `!' in the prompt is replaced by
1890 the current history event number. A literal `!' may then be repre‐
1891 sented as `!!'.
1892
1893 If the PROMPT_PERCENT option is set, certain escape sequences that
1894 start with `%' are expanded. Many escapes are followed by a single
1895 character, although some of these take an optional integer argument
1896 that should appear between the `%' and the next character of the
1897 sequence. More complicated escape sequences are available to provide
1898 conditional expansion.
1899
1901 Special characters
1902 %% A `%'.
1903
1904 %) A `)'.
1905
1906 Login information
1907 %l The line (tty) the user is logged in on, without `/dev/' prefix.
1908 If the name starts with `/dev/tty', that prefix is stripped.
1909
1910 %M The full machine hostname.
1911
1912 %m The hostname up to the first `.'. An integer may follow the `%'
1913 to specify how many components of the hostname are desired.
1914 With a negative integer, trailing components of the hostname are
1915 shown.
1916
1917 %n $USERNAME.
1918
1919 %y The line (tty) the user is logged in on, without `/dev/' prefix.
1920 This does not treat `/dev/tty' names specially.
1921
1922 Shell state
1923 %# A `#' if the shell is running with privileges, a `%' if not.
1924 Equivalent to `%(!.#.%%)'. The definition of `privileged', for
1925 these purposes, is that either the effective user ID is zero,
1926 or, if POSIX.1e capabilities are supported, that at least one
1927 capability is raised in either the Effective or Inheritable
1928 capability vectors.
1929
1930 %? The return status of the last command executed just before the
1931 prompt.
1932
1933 %_ The status of the parser, i.e. the shell constructs (like `if'
1934 and `for') that have been started on the command line. If given
1935 an integer number that many strings will be printed; zero or
1936 negative or no integer means print as many as there are. This
1937 is most useful in prompts PS2 for continuation lines and PS4 for
1938 debugging with the XTRACE option; in the latter case it will
1939 also work non-interactively.
1940
1941 %^ The status of the parser in reverse. This is the same as `%_'
1942 other than the order of strings. It is often used in RPS2.
1943
1944 %d
1945 %/ Current working directory. If an integer follows the `%', it
1946 specifies a number of trailing components of the current working
1947 directory to show; zero means the whole path. A negative inte‐
1948 ger specifies leading components, i.e. %-1d specifies the first
1949 component.
1950
1951 %~ As %d and %/, but if the current working directory starts with
1952 $HOME, that part is replaced by a `~'. Furthermore, if it has a
1953 named directory as its prefix, that part is replaced by a `~'
1954 followed by the name of the directory, but only if the result is
1955 shorter than the full path; see Dynamic and Static named direc‐
1956 tories in zshexpn(1).
1957
1958 %e Evaluation depth of the current sourced file, shell function, or
1959 eval. This is incremented or decremented every time the value
1960 of %N is set or reverted to a previous value, respectively.
1961 This is most useful for debugging as part of $PS4.
1962
1963 %h
1964 %! Current history event number.
1965
1966 %i The line number currently being executed in the script, sourced
1967 file, or shell function given by %N. This is most useful for
1968 debugging as part of $PS4.
1969
1970 %I The line number currently being executed in the file %x. This
1971 is similar to %i, but the line number is always a line number in
1972 the file where the code was defined, even if the code is a shell
1973 function.
1974
1975 %j The number of jobs.
1976
1977 %L The current value of $SHLVL.
1978
1979 %N The name of the script, sourced file, or shell function that zsh
1980 is currently executing, whichever was started most recently. If
1981 there is none, this is equivalent to the parameter $0. An inte‐
1982 ger may follow the `%' to specify a number of trailing path com‐
1983 ponents to show; zero means the full path. A negative integer
1984 specifies leading components.
1985
1986 %x The name of the file containing the source code currently being
1987 executed. This behaves as %N except that function and eval com‐
1988 mand names are not shown, instead the file where they were
1989 defined.
1990
1991 %c
1992 %.
1993 %C Trailing component of the current working directory. An integer
1994 may follow the `%' to get more than one component. Unless `%C'
1995 is used, tilde contraction is performed first. These are depre‐
1996 cated as %c and %C are equivalent to %1~ and %1/, respectively,
1997 while explicit positive integers have the same effect as for the
1998 latter two sequences.
1999
2000 Date and time
2001 %D The date in yy-mm-dd format.
2002
2003 %T Current time of day, in 24-hour format.
2004
2005 %t
2006 %@ Current time of day, in 12-hour, am/pm format.
2007
2008 %* Current time of day in 24-hour format, with seconds.
2009
2010 %w The date in day-dd format.
2011
2012 %W The date in mm/dd/yy format.
2013
2014 %D{string}
2015 string is formatted using the strftime function. See strf‐
2016 time(3) for more details. Various zsh extensions provide num‐
2017 bers with no leading zero or space if the number is a single
2018 digit:
2019
2020 %f a day of the month
2021 %K the hour of the day on the 24-hour clock
2022 %L the hour of the day on the 12-hour clock
2023
2024 In addition, if the system supports the POSIX gettimeofday sys‐
2025 tem call, %. provides decimal fractions of a second since the
2026 epoch with leading zeroes. By default three decimal places are
2027 provided, but a number of digits up to 9 may be given following
2028 the %; hence %6. outputs microseconds, and %9. outputs nanosec‐
2029 onds. (The latter requires a nanosecond-precision clock_get‐
2030 time; systems lacking this will return a value multiplied by the
2031 appropriate power of 10.) A typical example of this is the for‐
2032 mat `%D{%H:%M:%S.%.}'.
2033
2034 The GNU extension %N is handled as a synonym for %9..
2035
2036 Additionally, the GNU extension that a `-' between the % and the
2037 format character causes a leading zero or space to be stripped
2038 is handled directly by the shell for the format characters d, f,
2039 H, k, l, m, M, S and y; any other format characters are provided
2040 to the system's strftime(3) with any leading `-' present, so the
2041 handling is system dependent. Further GNU (or other) extensions
2042 are also passed to strftime(3) and may work if the system sup‐
2043 ports them.
2044
2045 Visual effects
2046 %B (%b)
2047 Start (stop) boldface mode.
2048
2049 %E Clear to end of line.
2050
2051 %U (%u)
2052 Start (stop) underline mode.
2053
2054 %S (%s)
2055 Start (stop) standout mode.
2056
2057 %F (%f)
2058 Start (stop) using a different foreground colour, if supported
2059 by the terminal. The colour may be specified two ways: either
2060 as a numeric argument, as normal, or by a sequence in braces
2061 following the %F, for example %F{red}. In the latter case the
2062 values allowed are as described for the fg zle_highlight
2063 attribute; see Character Highlighting in zshzle(1). This means
2064 that numeric colours are allowed in the second format also.
2065
2066 %K (%k)
2067 Start (stop) using a different bacKground colour. The syntax is
2068 identical to that for %F and %f.
2069
2070 %{...%}
2071 Include a string as a literal escape sequence. The string
2072 within the braces should not change the cursor position. Brace
2073 pairs can nest.
2074
2075 A positive numeric argument between the % and the { is treated
2076 as described for %G below.
2077
2078 %G Within a %{...%} sequence, include a `glitch': that is, assume
2079 that a single character width will be output. This is useful
2080 when outputting characters that otherwise cannot be correctly
2081 handled by the shell, such as the alternate character set on
2082 some terminals. The characters in question can be included
2083 within a %{...%} sequence together with the appropriate number
2084 of %G sequences to indicate the correct width. An integer
2085 between the `%' and `G' indicates a character width other than
2086 one. Hence %{seq%2G%} outputs seq and assumes it takes up the
2087 width of two standard characters.
2088
2089 Multiple uses of %G accumulate in the obvious fashion; the posi‐
2090 tion of the %G is unimportant. Negative integers are not han‐
2091 dled.
2092
2093 Note that when prompt truncation is in use it is advisable to
2094 divide up output into single characters within each %{...%}
2095 group so that the correct truncation point can be found.
2096
2098 %v The value of the first element of the psvar array parameter.
2099 Following the `%' with an integer gives that element of the
2100 array. Negative integers count from the end of the array.
2101
2102 %(x.true-text.false-text)
2103 Specifies a ternary expression. The character following the x
2104 is arbitrary; the same character is used to separate the text
2105 for the `true' result from that for the `false' result. This
2106 separator may not appear in the true-text, except as part of a
2107 %-escape sequence. A `)' may appear in the false-text as `%)'.
2108 true-text and false-text may both contain arbitrarily-nested
2109 escape sequences, including further ternary expressions.
2110
2111 The left parenthesis may be preceded or followed by a positive
2112 integer n, which defaults to zero. A negative integer will be
2113 multiplied by -1, except as noted below for `l'. The test char‐
2114 acter x may be any of the following:
2115
2116 ! True if the shell is running with privileges.
2117 # True if the effective uid of the current process is n.
2118 ? True if the exit status of the last command was n.
2119 _ True if at least n shell constructs were started.
2120 C
2121 / True if the current absolute path has at least n elements
2122 relative to the root directory, hence / is counted as 0
2123 elements.
2124 c
2125 .
2126 ~ True if the current path, with prefix replacement, has at
2127 least n elements relative to the root directory, hence /
2128 is counted as 0 elements.
2129 D True if the month is equal to n (January = 0).
2130 d True if the day of the month is equal to n.
2131 e True if the evaluation depth is at least n.
2132 g True if the effective gid of the current process is n.
2133 j True if the number of jobs is at least n.
2134 L True if the SHLVL parameter is at least n.
2135 l True if at least n characters have already been printed
2136 on the current line. When n is negative, true if at
2137 least abs(n) characters remain before the opposite margin
2138 (thus the left margin for RPROMPT).
2139 S True if the SECONDS parameter is at least n.
2140 T True if the time in hours is equal to n.
2141 t True if the time in minutes is equal to n.
2142 v True if the array psvar has at least n elements.
2143 V True if element n of the array psvar is set and
2144 non-empty.
2145 w True if the day of the week is equal to n (Sunday = 0).
2146
2147 %<string<
2148 %>string>
2149 %[xstring]
2150 Specifies truncation behaviour for the remainder of the prompt
2151 string. The third, deprecated, form is equivalent to
2152 `%xstringx', i.e. x may be `<' or `>'. The string will be dis‐
2153 played in place of the truncated portion of any string; note
2154 this does not undergo prompt expansion.
2155
2156 The numeric argument, which in the third form may appear immedi‐
2157 ately after the `[', specifies the maximum permitted length of
2158 the various strings that can be displayed in the prompt. In the
2159 first two forms, this numeric argument may be negative, in which
2160 case the truncation length is determined by subtracting the
2161 absolute value of the numeric argument from the number of char‐
2162 acter positions remaining on the current prompt line. If this
2163 results in a zero or negative length, a length of 1 is used. In
2164 other words, a negative argument arranges that after truncation
2165 at least n characters remain before the right margin (left mar‐
2166 gin for RPROMPT).
2167
2168 The forms with `<' truncate at the left of the string, and the
2169 forms with `>' truncate at the right of the string. For exam‐
2170 ple, if the current directory is `/home/pike', the prompt
2171 `%8<..<%/' will expand to `..e/pike'. In this string, the ter‐
2172 minating character (`<', `>' or `]'), or in fact any character,
2173 may be quoted by a preceding `\'; note when using print -P, how‐
2174 ever, that this must be doubled as the string is also subject to
2175 standard print processing, in addition to any backslashes
2176 removed by a double quoted string: the worst case is therefore
2177 `print -P "%<\\\\<<..."'.
2178
2179 If the string is longer than the specified truncation length, it
2180 will appear in full, completely replacing the truncated string.
2181
2182 The part of the prompt string to be truncated runs to the end of
2183 the string, or to the end of the next enclosing group of the
2184 `%(' construct, or to the next truncation encountered at the
2185 same grouping level (i.e. truncations inside a `%(' are sepa‐
2186 rate), which ever comes first. In particular, a truncation with
2187 argument zero (e.g., `%<<') marks the end of the range of the
2188 string to be truncated while turning off truncation from there
2189 on. For example, the prompt `%10<...<%~%<<%# ' will print a
2190 truncated representation of the current directory, followed by a
2191 `%' or `#', followed by a space. Without the `%<<', those two
2192 characters would be included in the string to be truncated.
2193 Note that `%-0<<' is not equivalent to `%<<' but specifies that
2194 the prompt is truncated at the right margin.
2195
2196 Truncation applies only within each individual line of the
2197 prompt, as delimited by embedded newlines (if any). If the
2198 total length of any line of the prompt after truncation is
2199 greater than the terminal width, or if the part to be truncated
2200 contains embedded newlines, truncation behavior is undefined and
2201 may change in a future version of the shell. Use
2202 `%-n(l.true-text.false-text)' to remove parts of the prompt when
2203 the available space is less than n.
2204
2205
2206
2207zsh 5.7.1 February 3, 2019 ZSHMISC(1)