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