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