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