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