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