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