1ZSHEXPN(1) General Commands Manual ZSHEXPN(1)
2
3
4
6 zshexpn - zsh expansion and substitution
7
9 The following types of expansions are performed in the indicated order
10 in five steps:
11
12 History Expansion
13 This is performed only in interactive shells.
14
15 Alias Expansion
16 Aliases are expanded immediately before the command line is
17 parsed as explained under Aliasing in zshmisc(1).
18
19 Process Substitution
20 Parameter Expansion
21 Command Substitution
22 Arithmetic Expansion
23 Brace Expansion
24 These five are performed in left-to-right fashion. On each
25 argument, any of the five steps that are needed are performed
26 one after the other. Hence, for example, all the parts of
27 parameter expansion are completed before command substitution is
28 started. After these expansions, all unquoted occurrences of
29 the characters `\',`'' and `"' are removed.
30
31 Filename Expansion
32 If the SH_FILE_EXPANSION option is set, the order of expansion
33 is modified for compatibility with sh and ksh. In that case
34 filename expansion is performed immediately after alias expan‐
35 sion, preceding the set of five expansions mentioned above.
36
37 Filename Generation
38 This expansion, commonly referred to as globbing, is always done
39 last.
40
41 The following sections explain the types of expansion in detail.
42
44 History expansion allows you to use words from previous command lines
45 in the command line you are typing. This simplifies spelling correc‐
46 tions and the repetition of complicated commands or arguments.
47
48 Immediately before execution, each command is saved in the history
49 list, the size of which is controlled by the HISTSIZE parameter. The
50 one most recent command is always retained in any case. Each saved
51 command in the history list is called a history event and is assigned a
52 number, beginning with 1 (one) when the shell starts up. The history
53 number that you may see in your prompt (see EXPANSION OF PROMPT
54 SEQUENCES in zshmisc(1)) is the number that is to be assigned to the
55 next command.
56
57 Overview
58 A history expansion begins with the first character of the histchars
59 parameter, which is `!' by default, and may occur anywhere on the com‐
60 mand line, including inside double quotes (but not inside single quotes
61 '...' or C-style quotes $'...' nor when escaped with a backslash).
62
63 The first character is followed by an optional event designator (see
64 the section `Event Designators') and then an optional word designator
65 (the section `Word Designators'); if neither of these designators is
66 present, no history expansion occurs.
67
68 Input lines containing history expansions are echoed after being
69 expanded, but before any other expansions take place and before the
70 command is executed. It is this expanded form that is recorded as the
71 history event for later references.
72
73 History expansions do not nest.
74
75 By default, a history reference with no event designator refers to the
76 same event as any preceding history reference on that command line; if
77 it is the only history reference in a command, it refers to the previ‐
78 ous command. However, if the option CSH_JUNKIE_HISTORY is set, then
79 every history reference with no event specification always refers to
80 the previous command.
81
82 For example, `!' is the event designator for the previous command, so
83 `!!:1' always refers to the first word of the previous command, and
84 `!!$' always refers to the last word of the previous command. With
85 CSH_JUNKIE_HISTORY set, then `!:1' and `!$' function in the same manner
86 as `!!:1' and `!!$', respectively. Conversely, if CSH_JUNKIE_HISTORY
87 is unset, then `!:1' and `!$' refer to the first and last words,
88 respectively, of the same event referenced by the nearest other history
89 reference preceding them on the current command line, or to the previ‐
90 ous command if there is no preceding reference.
91
92 The character sequence `^foo^bar' (where `^' is actually the second
93 character of the histchars parameter) repeats the last command, replac‐
94 ing the string foo with bar. More precisely, the sequence `^foo^bar^'
95 is synonymous with `!!:s^foo^bar^', hence other modifiers (see the sec‐
96 tion `Modifiers') may follow the final `^'. In particular,
97 `^foo^bar^:G' performs a global substitution.
98
99 If the shell encounters the character sequence `!"' in the input, the
100 history mechanism is temporarily disabled until the current list (see
101 zshmisc(1)) is fully parsed. The `!"' is removed from the input, and
102 any subsequent `!' characters have no special significance.
103
104 A less convenient but more comprehensible form of command history sup‐
105 port is provided by the fc builtin.
106
107 Event Designators
108 An event designator is a reference to a command-line entry in the his‐
109 tory list. In the list below, remember that the initial `!' in each
110 item may be changed to another character by setting the histchars
111 parameter.
112
113 ! Start a history expansion, except when followed by a blank, new‐
114 line, `=' or `('. If followed immediately by a word designator
115 (see the section `Word Designators'), this forms a history ref‐
116 erence with no event designator (see the section `Overview').
117
118 !! Refer to the previous command. By itself, this expansion
119 repeats the previous command.
120
121 !n Refer to command-line n.
122
123 !-n Refer to the current command-line minus n.
124
125 !str Refer to the most recent command starting with str.
126
127 !?str[?]
128 Refer to the most recent command containing str. The trailing
129 `?' is necessary if this reference is to be followed by a modi‐
130 fier or followed by any text that is not to be considered part
131 of str.
132
133 !# Refer to the current command line typed in so far. The line is
134 treated as if it were complete up to and including the word
135 before the one with the `!#' reference.
136
137 !{...} Insulate a history reference from adjacent characters (if neces‐
138 sary).
139
140 Word Designators
141 A word designator indicates which word or words of a given command line
142 are to be included in a history reference. A `:' usually separates the
143 event specification from the word designator. It may be omitted only
144 if the word designator begins with a `^', `$', `*', `-' or `%'. Word
145 designators include:
146
147 0 The first input word (command).
148 n The nth argument.
149 ^ The first argument. That is, 1.
150 $ The last argument.
151 % The word matched by (the most recent) ?str search.
152 x-y A range of words; x defaults to 0.
153 * All the arguments, or a null value if there are none.
154 x* Abbreviates `x-$'.
155 x- Like `x*' but omitting word $.
156
157 Note that a `%' word designator works only when used in one of `!%',
158 `!:%' or `!?str?:%', and only when used after a !? expansion (possibly
159 in an earlier command). Anything else results in an error, although
160 the error may not be the most obvious one.
161
162 Modifiers
163 After the optional word designator, you can add a sequence of one or
164 more of the following modifiers, each preceded by a `:'. These modi‐
165 fiers also work on the result of filename generation and parameter
166 expansion, except where noted.
167
168 a Turn a file name into an absolute path: prepends the current
169 directory, if necessary; remove `.' path segments; and remove
170 `..' path segments and the segments that immediately precede
171 them.
172
173 This transformation is agnostic about what is in the filesystem,
174 i.e. is on the logical, not the physical directory. It takes
175 place in the same manner as when changing directories when nei‐
176 ther of the options CHASE_DOTS or CHASE_LINKS is set. For exam‐
177 ple, `/before/here/../after' is always transformed to
178 `/before/after', regardless of whether `/before/here' exists or
179 what kind of object (dir, file, symlink, etc.) it is.
180
181 A Turn a file name into an absolute path as the `a' modifier does,
182 and then pass the result through the realpath(3) library func‐
183 tion to resolve symbolic links.
184
185 Note: on systems that do not have a realpath(3) library func‐
186 tion, symbolic links are not resolved, so on those systems `a'
187 and `A' are equivalent.
188
189 Note: foo:A and realpath(foo) are different on some inputs. For
190 realpath(foo) semantics, see the `P` modifier.
191
192 c Resolve a command name into an absolute path by searching the
193 command path given by the PATH variable. This does not work for
194 commands containing directory parts. Note also that this does
195 not usually work as a glob qualifier unless a file of the same
196 name is found in the current directory.
197
198 e Remove all but the part of the filename extension following the
199 `.'; see the definition of the filename extension in the
200 description of the r modifier below. Note that according to
201 that definition the result will be empty if the string ends with
202 a `.'.
203
204 h Remove a trailing pathname component, leaving the head. This
205 works like `dirname'.
206
207 l Convert the words to all lowercase.
208
209 p Print the new command but do not execute it. Only works with
210 history expansion.
211
212 P Turn a file name into an absolute path, like realpath(3). The
213 resulting path will be absolute, have neither `.' nor `..' com‐
214 ponents, and refer to the same directory entry as the input
215 filename.
216
217 Unlike realpath(3), non-existent trailing components are permit‐
218 ted and preserved.
219
220 q Quote the substituted words, escaping further substitutions.
221 Works with history expansion and parameter expansion, though for
222 parameters it is only useful if the resulting text is to be
223 re-evaluated such as by eval.
224
225 Q Remove one level of quotes from the substituted words.
226
227 r Remove a filename extension leaving the root name. Strings with
228 no filename extension are not altered. A filename extension is
229 a `.' followed by any number of characters (including zero) that
230 are neither `.' nor `/' and that continue to the end of the
231 string. For example, the extension of `foo.orig.c' is `.c', and
232 `dir.c/foo' has no extension.
233
234 s/l/r[/]
235 Substitute r for l as described below. The substitution is done
236 only for the first string that matches l. For arrays and for
237 filename generation, this applies to each word of the expanded
238 text. See below for further notes on substitutions.
239
240 The forms `gs/l/r' and `s/l/r/:G' perform global substitution,
241 i.e. substitute every occurrence of r for l. Note that the g or
242 :G must appear in exactly the position shown.
243
244 See further notes on this form of substitution below.
245
246 & Repeat the previous s substitution. Like s, may be preceded
247 immediately by a g. In parameter expansion the & must appear
248 inside braces, and in filename generation it must be quoted with
249 a backslash.
250
251 t Remove all leading pathname components, leaving the tail. This
252 works like `basename'.
253
254 u Convert the words to all uppercase.
255
256 x Like q, but break into words at whitespace. Does not work with
257 parameter expansion.
258
259 The s/l/r/ substitution works as follows. By default the left-hand
260 side of substitutions are not patterns, but character strings. Any
261 character can be used as the delimiter in place of `/'. A backslash
262 quotes the delimiter character. The character `&', in the
263 right-hand-side r, is replaced by the text from the left-hand-side l.
264 The `&' can be quoted with a backslash. A null l uses the previous
265 string either from the previous l or from the contextual scan string s
266 from `!?s'. You can omit the rightmost delimiter if a newline immedi‐
267 ately follows r; the rightmost `?' in a context scan can similarly be
268 omitted. Note the same record of the last l and r is maintained across
269 all forms of expansion.
270
271 Note that if a `&' is used within glob qualifiers an extra backslash is
272 needed as a & is a special character in this case.
273
274 Also note that the order of expansions affects the interpretation of l
275 and r. When used in a history expansion, which occurs before any other
276 expansions, l and r are treated as literal strings (except as explained
277 for HIST_SUBST_PATTERN below). When used in parameter expansion, the
278 replacement of r into the parameter's value is done first, and then any
279 additional process, parameter, command, arithmetic, or brace references
280 are applied, which may evaluate those substitutions and expansions more
281 than once if l appears more than once in the starting value. When used
282 in a glob qualifier, any substitutions or expansions are performed once
283 at the time the qualifier is parsed, even before the `:s' expression
284 itself is divided into l and r sides.
285
286 If the option HIST_SUBST_PATTERN is set, l is treated as a pattern of
287 the usual form described in the section FILENAME GENERATION below.
288 This can be used in all the places where modifiers are available; note,
289 however, that in globbing qualifiers parameter substitution has already
290 taken place, so parameters in the replacement string should be quoted
291 to ensure they are replaced at the correct time. Note also that com‐
292 plicated patterns used in globbing qualifiers may need the extended
293 glob qualifier notation (#q:s/.../.../) in order for the shell to rec‐
294 ognize the expression as a glob qualifier. Further, note that bad pat‐
295 terns in the substitution are not subject to the NO_BAD_PATTERN option
296 so will cause an error.
297
298 When HIST_SUBST_PATTERN is set, l may start with a # to indicate that
299 the pattern must match at the start of the string to be substituted,
300 and a % may appear at the start or after an # to indicate that the pat‐
301 tern must match at the end of the string to be substituted. The % or #
302 may be quoted with two backslashes.
303
304 For example, the following piece of filename generation code with the
305 EXTENDED_GLOB option:
306
307 print *.c(#q:s/#%(#b)s(*).c/'S${match[1]}.C'/)
308
309 takes the expansion of *.c and applies the glob qualifiers in the
310 (#q...) expression, which consists of a substitution modifier anchored
311 to the start and end of each word (#%). This turns on backreferences
312 ((#b)), so that the parenthesised subexpression is available in the
313 replacement string as ${match[1]}. The replacement string is quoted so
314 that the parameter is not substituted before the start of filename gen‐
315 eration.
316
317 The following f, F, w and W modifiers work only with parameter expan‐
318 sion and filename generation. They are listed here to provide a single
319 point of reference for all modifiers.
320
321 f Repeats the immediately (without a colon) following modifier
322 until the resulting word doesn't change any more.
323
324 F:expr:
325 Like f, but repeats only n times if the expression expr evalu‐
326 ates to n. Any character can be used instead of the `:'; if
327 `(', `[', or `{' is used as the opening delimiter, the closing
328 delimiter should be ')', `]', or `}', respectively.
329
330 w Makes the immediately following modifier work on each word in
331 the string.
332
333 W:sep: Like w but words are considered to be the parts of the string
334 that are separated by sep. Any character can be used instead of
335 the `:'; opening parentheses are handled specially, see above.
336
338 Each part of a command argument that takes the form `<(list)',
339 `>(list)' or `=(list)' is subject to process substitution. The expres‐
340 sion may be preceded or followed by other strings except that, to pre‐
341 vent clashes with commonly occurring strings and patterns, the last
342 form must occur at the start of a command argument, and the forms are
343 only expanded when first parsing command or assignment arguments.
344 Process substitutions may be used following redirection operators; in
345 this case, the substitution must appear with no trailing string.
346
347 Note that `<<(list)' is not a special syntax; it is equivalent to `<
348 <(list)', redirecting standard input from the result of process substi‐
349 tution. Hence all the following documentation applies. The second
350 form (with the space) is recommended for clarity.
351
352 In the case of the < or > forms, the shell runs the commands in list as
353 a subprocess of the job executing the shell command line. If the sys‐
354 tem supports the /dev/fd mechanism, the command argument is the name of
355 the device file corresponding to a file descriptor; otherwise, if the
356 system supports named pipes (FIFOs), the command argument will be a
357 named pipe. If the form with > is selected then writing on this spe‐
358 cial file will provide input for list. If < is used, then the file
359 passed as an argument will be connected to the output of the list
360 process. For example,
361
362 paste <(cut -f1 file1) <(cut -f3 file2) |
363 tee >(process1) >(process2) >/dev/null
364
365 cuts fields 1 and 3 from the files file1 and file2 respectively, pastes
366 the results together, and sends it to the processes process1 and
367 process2.
368
369 If =(...) is used instead of <(...), then the file passed as an argu‐
370 ment will be the name of a temporary file containing the output of the
371 list process. This may be used instead of the < form for a program
372 that expects to lseek (see lseek(2)) on the input file.
373
374 There is an optimisation for substitutions of the form =(<<<arg), where
375 arg is a single-word argument to the here-string redirection <<<. This
376 form produces a file name containing the value of arg after any substi‐
377 tutions have been performed. This is handled entirely within the cur‐
378 rent shell. This is effectively the reverse of the special form
379 $(<arg) which treats arg as a file name and replaces it with the file's
380 contents.
381
382 The = form is useful as both the /dev/fd and the named pipe implementa‐
383 tion of <(...) have drawbacks. In the former case, some programmes may
384 automatically close the file descriptor in question before examining
385 the file on the command line, particularly if this is necessary for
386 security reasons such as when the programme is running setuid. In the
387 second case, if the programme does not actually open the file, the sub‐
388 shell attempting to read from or write to the pipe will (in a typical
389 implementation, different operating systems may have different behav‐
390 iour) block for ever and have to be killed explicitly. In both cases,
391 the shell actually supplies the information using a pipe, so that pro‐
392 grammes that expect to lseek (see lseek(2)) on the file will not work.
393
394 Also note that the previous example can be more compactly and effi‐
395 ciently written (provided the MULTIOS option is set) as:
396
397 paste <(cut -f1 file1) <(cut -f3 file2) \
398 > >(process1) > >(process2)
399
400 The shell uses pipes instead of FIFOs to implement the latter two
401 process substitutions in the above example.
402
403 There is an additional problem with >(process); when this is attached
404 to an external command, the parent shell does not wait for process to
405 finish and hence an immediately following command cannot rely on the
406 results being complete. The problem and solution are the same as
407 described in the section MULTIOS in zshmisc(1). Hence in a simplified
408 version of the example above:
409
410 paste <(cut -f1 file1) <(cut -f3 file2) > >(process)
411
412 (note that no MULTIOS are involved), process will be run asynchronously
413 as far as the parent shell is concerned. The workaround is:
414
415 { paste <(cut -f1 file1) <(cut -f3 file2) } > >(process)
416
417 The extra processes here are spawned from the parent shell which will
418 wait for their completion.
419
420 Another problem arises any time a job with a substitution that requires
421 a temporary file is disowned by the shell, including the case where
422 `&!' or `&|' appears at the end of a command containing a substitution.
423 In that case the temporary file will not be cleaned up as the shell no
424 longer has any memory of the job. A workaround is to use a subshell,
425 for example,
426
427 (mycmd =(myoutput)) &!
428
429 as the forked subshell will wait for the command to finish then remove
430 the temporary file.
431
432 A general workaround to ensure a process substitution endures for an
433 appropriate length of time is to pass it as a parameter to an anonymous
434 shell function (a piece of shell code that is run immediately with
435 function scope). For example, this code:
436
437 () {
438 print File $1:
439 cat $1
440 } =(print This be the verse)
441
442 outputs something resembling the following
443
444 File /tmp/zsh6nU0kS:
445 This be the verse
446
447 The temporary file created by the process substitution will be deleted
448 when the function exits.
449
451 The character `$' is used to introduce parameter expansions. See zsh‐
452 param(1) for a description of parameters, including arrays, associative
453 arrays, and subscript notation to access individual array elements.
454
455 Note in particular the fact that words of unquoted parameters are not
456 automatically split on whitespace unless the option SH_WORD_SPLIT is
457 set; see references to this option below for more details. This is an
458 important difference from other shells.
459
460 In the expansions discussed below that require a pattern, the form of
461 the pattern is the same as that used for filename generation; see the
462 section `Filename Generation'. Note that these patterns, along with
463 the replacement text of any substitutions, are themselves subject to
464 parameter expansion, command substitution, and arithmetic expansion.
465 In addition to the following operations, the colon modifiers described
466 in the section `Modifiers' in the section `History Expansion' can be
467 applied: for example, ${i:s/foo/bar/} performs string substitution on
468 the expansion of parameter $i.
469
470 In the following descriptions, `word' refers to a single word substi‐
471 tuted on the command line, not necessarily a space delimited word.
472 With default options, after the assignments:
473
474 array=("first word" "second word")
475 scalar="only word"
476
477 then $array substitutes two words, `first word' and `second word', and
478 $scalar substitutes a single word `only word'. This may be modified by
479 explicit or implicit word-splitting, however. The full rules are com‐
480 plicated and are noted at the end.
481
482 ${name}
483 The value, if any, of the parameter name is substituted. The
484 braces are required if the expansion is to be followed by a let‐
485 ter, digit, or underscore that is not to be interpreted as part
486 of name. In addition, more complicated forms of substitution
487 usually require the braces to be present; exceptions, which only
488 apply if the option KSH_ARRAYS is not set, are a single sub‐
489 script or any colon modifiers appearing after the name, or any
490 of the characters `^', `=', `~', `#' or `+' appearing before the
491 name, all of which work with or without braces.
492
493 If name is an array parameter, and the KSH_ARRAYS option is not
494 set, then the value of each element of name is substituted, one
495 element per word. Otherwise, the expansion results in one word
496 only; with KSH_ARRAYS, this is the first element of an array.
497 No field splitting is done on the result unless the
498 SH_WORD_SPLIT option is set. See also the flags = and
499 s:string:.
500
501 ${+name}
502 If name is the name of a set parameter `1' is substituted, oth‐
503 erwise `0' is substituted.
504
505 ${name-word}
506 ${name:-word}
507 If name is set, or in the second form is non-null, then substi‐
508 tute its value; otherwise substitute word. In the second form
509 name may be omitted, in which case word is always substituted.
510
511 ${name+word}
512 ${name:+word}
513 If name is set, or in the second form is non-null, then substi‐
514 tute word; otherwise substitute nothing.
515
516 ${name=word}
517 ${name:=word}
518 ${name::=word}
519 In the first form, if name is unset then set it to word; in the
520 second form, if name is unset or null then set it to word; and
521 in the third form, unconditionally set name to word. In all
522 forms, the value of the parameter is then substituted.
523
524 ${name?word}
525 ${name:?word}
526 In the first form, if name is set, or in the second form if name
527 is both set and non-null, then substitute its value; otherwise,
528 print word and exit from the shell. Interactive shells instead
529 return to the prompt. If word is omitted, then a standard mes‐
530 sage is printed.
531
532 In any of the above expressions that test a variable and substitute an
533 alternate word, note that you can use standard shell quoting in the
534 word value to selectively override the splitting done by the
535 SH_WORD_SPLIT option and the = flag, but not splitting by the s:string:
536 flag.
537
538 In the following expressions, when name is an array and the substitu‐
539 tion is not quoted, or if the `(@)' flag or the name[@] syntax is used,
540 matching and replacement is performed on each array element separately.
541
542 ${name#pattern}
543 ${name##pattern}
544 If the pattern matches the beginning of the value of name, then
545 substitute the value of name with the matched portion deleted;
546 otherwise, just substitute the value of name. In the first
547 form, the smallest matching pattern is preferred; in the second
548 form, the largest matching pattern is preferred.
549
550 ${name%pattern}
551 ${name%%pattern}
552 If the pattern matches the end of the value of name, then sub‐
553 stitute the value of name with the matched portion deleted; oth‐
554 erwise, just substitute the value of name. In the first form,
555 the smallest matching pattern is preferred; in the second form,
556 the largest matching pattern is preferred.
557
558 ${name:#pattern}
559 If the pattern matches the value of name, then substitute the
560 empty string; otherwise, just substitute the value of name. If
561 name is an array the matching array elements are removed (use
562 the `(M)' flag to remove the non-matched elements).
563
564 ${name:|arrayname}
565 If arrayname is the name (N.B., not contents) of an array vari‐
566 able, then any elements contained in arrayname are removed from
567 the substitution of name. If the substitution is scalar, either
568 because name is a scalar variable or the expression is quoted,
569 the elements of arrayname are instead tested against the entire
570 expression.
571
572 ${name:*arrayname}
573 Similar to the preceding substitution, but in the opposite
574 sense, so that entries present in both the original substitution
575 and as elements of arrayname are retained and others removed.
576
577 ${name:^arrayname}
578 ${name:^^arrayname}
579 Zips two arrays, such that the output array is twice as long as
580 the shortest (longest for `:^^') of name and arrayname, with the
581 elements alternatingly being picked from them. For `:^', if one
582 of the input arrays is longer, the output will stop when the end
583 of the shorter array is reached. Thus,
584
585 a=(1 2 3 4); b=(a b); print ${a:^b}
586
587 will output `1 a 2 b'. For `:^^', then the input is repeated
588 until all of the longer array has been used up and the above
589 will output `1 a 2 b 3 a 4 b'.
590
591 Either or both inputs may be a scalar, they will be treated as
592 an array of length 1 with the scalar as the only element. If
593 either array is empty, the other array is output with no extra
594 elements inserted.
595
596 Currently the following code will output `a b' and `1' as two
597 separate elements, which can be unexpected. The second print
598 provides a workaround which should continue to work if this is
599 changed.
600
601 a=(a b); b=(1 2); print -l "${a:^b}"; print -l "${${a:^b}}"
602
603 ${name:offset}
604 ${name:offset:length}
605 This syntax gives effects similar to parameter subscripting in
606 the form $name[start,end], but is compatible with other shells;
607 note that both offset and length are interpreted differently
608 from the components of a subscript.
609
610 If offset is non-negative, then if the variable name is a scalar
611 substitute the contents starting offset characters from the
612 first character of the string, and if name is an array substi‐
613 tute elements starting offset elements from the first element.
614 If length is given, substitute that many characters or elements,
615 otherwise the entire rest of the scalar or array.
616
617 A positive offset is always treated as the offset of a character
618 or element in name from the first character or element of the
619 array (this is different from native zsh subscript notation).
620 Hence 0 refers to the first character or element regardless of
621 the setting of the option KSH_ARRAYS.
622
623 A negative offset counts backwards from the end of the scalar or
624 array, so that -1 corresponds to the last character or element,
625 and so on.
626
627 When positive, length counts from the offset position toward the
628 end of the scalar or array. When negative, length counts back
629 from the end. If this results in a position smaller than off‐
630 set, a diagnostic is printed and nothing is substituted.
631
632 The option MULTIBYTE is obeyed, i.e. the offset and length count
633 multibyte characters where appropriate.
634
635 offset and length undergo the same set of shell substitutions as
636 for scalar assignment; in addition, they are then subject to
637 arithmetic evaluation. Hence, for example
638
639 print ${foo:3}
640 print ${foo: 1 + 2}
641 print ${foo:$(( 1 + 2))}
642 print ${foo:$(echo 1 + 2)}
643
644 all have the same effect, extracting the string starting at the
645 fourth character of $foo if the substitution would otherwise
646 return a scalar, or the array starting at the fourth element if
647 $foo would return an array. Note that with the option
648 KSH_ARRAYS $foo always returns a scalar (regardless of the use
649 of the offset syntax) and a form such as ${foo[*]:3} is required
650 to extract elements of an array named foo.
651
652 If offset is negative, the - may not appear immediately after
653 the : as this indicates the ${name:-word} form of substitution.
654 Instead, a space may be inserted before the -. Furthermore,
655 neither offset nor length may begin with an alphabetic character
656 or & as these are used to indicate history-style modifiers. To
657 substitute a value from a variable, the recommended approach is
658 to precede it with a $ as this signifies the intention (parame‐
659 ter substitution can easily be rendered unreadable); however, as
660 arithmetic substitution is performed, the expression ${var:
661 offs} does work, retrieving the offset from $offs.
662
663 For further compatibility with other shells there is a special
664 case for array offset 0. This usually accesses the first ele‐
665 ment of the array. However, if the substitution refers to the
666 positional parameter array, e.g. $@ or $*, then offset 0 instead
667 refers to $0, offset 1 refers to $1, and so on. In other words,
668 the positional parameter array is effectively extended by
669 prepending $0. Hence ${*:0:1} substitutes $0 and ${*:1:1} sub‐
670 stitutes $1.
671
672 ${name/pattern/repl}
673 ${name//pattern/repl}
674 ${name:/pattern/repl}
675 Replace the longest possible match of pattern in the expansion
676 of parameter name by string repl. The first form replaces just
677 the first occurrence, the second form all occurrences, and the
678 third form replaces only if pattern matches the entire string.
679 Both pattern and repl are subject to double-quoted substitution,
680 so that expressions like ${name/$opat/$npat} will work, but obey
681 the usual rule that pattern characters in $opat are not treated
682 specially unless either the option GLOB_SUBST is set, or $opat
683 is instead substituted as ${~opat}.
684
685 The pattern may begin with a `#', in which case the pattern must
686 match at the start of the string, or `%', in which case it must
687 match at the end of the string, or `#%' in which case the pat‐
688 tern must match the entire string. The repl may be an empty
689 string, in which case the final `/' may also be omitted. To
690 quote the final `/' in other cases it should be preceded by a
691 single backslash; this is not necessary if the `/' occurs inside
692 a substituted parameter. Note also that the `#', `%' and `#%
693 are not active if they occur inside a substituted parameter,
694 even at the start.
695
696 If, after quoting rules apply, ${name} expands to an array, the
697 replacements act on each element individually. Note also the
698 effect of the I and S parameter expansion flags below; however,
699 the flags M, R, B, E and N are not useful.
700
701 For example,
702
703 foo="twinkle twinkle little star" sub="t*e" rep="spy"
704 print ${foo//${~sub}/$rep}
705 print ${(S)foo//${~sub}/$rep}
706
707 Here, the `~' ensures that the text of $sub is treated as a pat‐
708 tern rather than a plain string. In the first case, the longest
709 match for t*e is substituted and the result is `spy star', while
710 in the second case, the shortest matches are taken and the
711 result is `spy spy lispy star'.
712
713 ${#spec}
714 If spec is one of the above substitutions, substitute the length
715 in characters of the result instead of the result itself. If
716 spec is an array expression, substitute the number of elements
717 of the result. This has the side-effect that joining is skipped
718 even in quoted forms, which may affect other sub-expressions in
719 spec. Note that `^', `=', and `~', below, must appear to the
720 left of `#' when these forms are combined.
721
722 If the option POSIX_IDENTIFIERS is not set, and spec is a simple
723 name, then the braces are optional; this is true even for spe‐
724 cial parameters so e.g. $#- and $#* take the length of the
725 string $- and the array $* respectively. If POSIX_IDENTIFIERS
726 is set, then braces are required for the # to be treated in this
727 fashion.
728
729 ${^spec}
730 Turn on the RC_EXPAND_PARAM option for the evaluation of spec;
731 if the `^' is doubled, turn it off. When this option is set,
732 array expansions of the form foo${xx}bar, where the parameter xx
733 is set to (a b c), are substituted with `fooabar foobbar
734 foocbar' instead of the default `fooa b cbar'. Note that an
735 empty array will therefore cause all arguments to be removed.
736
737 Internally, each such expansion is converted into the equivalent
738 list for brace expansion. E.g., ${^var} becomes
739 {$var[1],$var[2],...}, and is processed as described in the sec‐
740 tion `Brace Expansion' below: note, however, the expansion hap‐
741 pens immediately, with any explicit brace expansion happening
742 later. If word splitting is also in effect the $var[N] may
743 themselves be split into different list elements.
744
745 ${=spec}
746 Perform word splitting using the rules for SH_WORD_SPLIT during
747 the evaluation of spec, but regardless of whether the parameter
748 appears in double quotes; if the `=' is doubled, turn it off.
749 This forces parameter expansions to be split into separate words
750 before substitution, using IFS as a delimiter. This is done by
751 default in most other shells.
752
753 Note that splitting is applied to word in the assignment forms
754 of spec before the assignment to name is performed. This
755 affects the result of array assignments with the A flag.
756
757 ${~spec}
758 Turn on the GLOB_SUBST option for the evaluation of spec; if the
759 `~' is doubled, turn it off. When this option is set, the
760 string resulting from the expansion will be interpreted as a
761 pattern anywhere that is possible, such as in filename expansion
762 and filename generation and pattern-matching contexts like the
763 right hand side of the `=' and `!=' operators in conditions.
764
765 In nested substitutions, note that the effect of the ~ applies
766 to the result of the current level of substitution. A surround‐
767 ing pattern operation on the result may cancel it. Hence, for
768 example, if the parameter foo is set to *, ${~foo//\*/*.c} is
769 substituted by the pattern *.c, which may be expanded by file‐
770 name generation, but ${${~foo}//\*/*.c} substitutes to the
771 string *.c, which will not be further expanded.
772
773 If a ${...} type parameter expression or a $(...) type command substi‐
774 tution is used in place of name above, it is expanded first and the
775 result is used as if it were the value of name. Thus it is possible to
776 perform nested operations: ${${foo#head}%tail} substitutes the value
777 of $foo with both `head' and `tail' deleted. The form with $(...) is
778 often useful in combination with the flags described next; see the
779 examples below. Each name or nested ${...} in a parameter expansion
780 may also be followed by a subscript expression as described in Array
781 Parameters in zshparam(1).
782
783 Note that double quotes may appear around nested expressions, in which
784 case only the part inside is treated as quoted; for example,
785 ${(f)"$(foo)"} quotes the result of $(foo), but the flag `(f)' (see
786 below) is applied using the rules for unquoted expansions. Note fur‐
787 ther that quotes are themselves nested in this context; for example, in
788 "${(@f)"$(foo)"}", there are two sets of quotes, one surrounding the
789 whole expression, the other (redundant) surrounding the $(foo) as
790 before.
791
792 Parameter Expansion Flags
793 If the opening brace is directly followed by an opening parenthesis,
794 the string up to the matching closing parenthesis will be taken as a
795 list of flags. In cases where repeating a flag is meaningful, the rep‐
796 etitions need not be consecutive; for example, `(q%q%q)' means the same
797 thing as the more readable `(%%qqq)'. The following flags are sup‐
798 ported:
799
800 # Evaluate the resulting words as numeric expressions and output
801 the characters corresponding to the resulting integer. Note
802 that this form is entirely distinct from use of the # without
803 parentheses.
804
805 If the MULTIBYTE option is set and the number is greater than
806 127 (i.e. not an ASCII character) it is treated as a Unicode
807 character.
808
809 % Expand all % escapes in the resulting words in the same way as
810 in prompts (see EXPANSION OF PROMPT SEQUENCES in zshmisc(1)). If
811 this flag is given twice, full prompt expansion is done on the
812 resulting words, depending on the setting of the PROMPT_PERCENT,
813 PROMPT_SUBST and PROMPT_BANG options.
814
815 @ In double quotes, array elements are put into separate words.
816 E.g., `"${(@)foo}"' is equivalent to `"${foo[@]}"' and
817 `"${(@)foo[1,2]}"' is the same as `"$foo[1]" "$foo[2]"'. This
818 is distinct from field splitting by the f, s or z flags, which
819 still applies within each array element.
820
821 A Convert the substitution into an array expression, even if it
822 otherwise would be scalar. This has lower precedence than sub‐
823 scripting, so one level of nested expansion is required in order
824 that subscripts apply to array elements. Thus ${${(A)name}[1]}
825 yields the full value of name when name is scalar.
826
827 This assigns an array parameter with `${...=...}', `${...:=...}'
828 or `${...::=...}'. If this flag is repeated (as in `AA'),
829 assigns an associative array parameter. Assignment is made
830 before sorting or padding; if field splitting is active, the
831 word part is split before assignment. The name part may be a
832 subscripted range for ordinary arrays; when assigning an asso‐
833 ciative array, the word part must be converted to an array, for
834 example by using `${(AA)=name=...}' to activate field splitting.
835
836 Surrounding context such as additional nesting or use of the
837 value in a scalar assignment may cause the array to be joined
838 back into a single string again.
839
840 a Sort in array index order; when combined with `O' sort in
841 reverse array index order. Note that `a' is therefore equiva‐
842 lent to the default but `Oa' is useful for obtaining an array's
843 elements in reverse order.
844
845 b Quote with backslashes only characters that are special to pat‐
846 tern matching. This is useful when the contents of the variable
847 are to be tested using GLOB_SUBST, including the ${~...} switch.
848
849 Quoting using one of the q family of flags does not work for
850 this purpose since quotes are not stripped from non-pattern
851 characters by GLOB_SUBST. In other words,
852
853 pattern=${(q)str}
854 [[ $str = ${~pattern} ]]
855
856 works if $str is `a*b' but not if it is `a b', whereas
857
858 pattern=${(b)str}
859 [[ $str = ${~pattern} ]]
860
861 is always true for any possible value of $str.
862
863 c With ${#name}, count the total number of characters in an array,
864 as if the elements were concatenated with spaces between them.
865 This is not a true join of the array, so other expressions used
866 with this flag may have an effect on the elements of the array
867 before it is counted.
868
869 C Capitalize the resulting words. `Words' in this case refers to
870 sequences of alphanumeric characters separated by non-alphanu‐
871 merics, not to words that result from field splitting.
872
873 D Assume the string or array elements contain directories and
874 attempt to substitute the leading part of these by names. The
875 remainder of the path (the whole of it if the leading part was
876 not substituted) is then quoted so that the whole string can be
877 used as a shell argument. This is the reverse of `~' substitu‐
878 tion: see the section FILENAME EXPANSION below.
879
880 e Perform single word shell expansions, namely parameter expan‐
881 sion, command substitution and arithmetic expansion, on the
882 result. Such expansions can be nested but too deep recursion may
883 have unpredictable effects.
884
885 f Split the result of the expansion at newlines. This is a short‐
886 hand for `ps:\n:'.
887
888 F Join the words of arrays together using newline as a separator.
889 This is a shorthand for `pj:\n:'.
890
891 g:opts:
892 Process escape sequences like the echo builtin when no options
893 are given (g::). With the o option, octal escapes don't take a
894 leading zero. With the c option, sequences like `^X' are also
895 processed. With the e option, processes `\M-t' and similar
896 sequences like the print builtin. With both of the o and e
897 options, behaves like the print builtin except that in none of
898 these modes is `\c' interpreted.
899
900 i Sort case-insensitively. May be combined with `n' or `O'.
901
902 k If name refers to an associative array, substitute the keys
903 (element names) rather than the values of the elements. Used
904 with subscripts (including ordinary arrays), force indices or
905 keys to be substituted even if the subscript form refers to val‐
906 ues. However, this flag may not be combined with subscript
907 ranges. With the KSH_ARRAYS option a subscript `[*]' or `[@]'
908 is needed to operate on the whole array, as usual.
909
910 L Convert all letters in the result to lower case.
911
912 n Sort decimal integers numerically; if the first differing char‐
913 acters of two test strings are not digits, sorting is lexical.
914 Integers with more initial zeroes are sorted before those with
915 fewer or none. Hence the array `foo1 foo02 foo2 foo3 foo20
916 foo23' is sorted into the order shown. May be combined with `i'
917 or `O'.
918
919 o Sort the resulting words in ascending order; if this appears on
920 its own the sorting is lexical and case-sensitive (unless the
921 locale renders it case-insensitive). Sorting in ascending order
922 is the default for other forms of sorting, so this is ignored if
923 combined with `a', `i' or `n'.
924
925 O Sort the resulting words in descending order; `O' without `a',
926 `i' or `n' sorts in reverse lexical order. May be combined with
927 `a', `i' or `n' to reverse the order of sorting.
928
929 P This forces the value of the parameter name to be interpreted as
930 a further parameter name, whose value will be used where appro‐
931 priate. Note that flags set with one of the typeset family of
932 commands (in particular case transformations) are not applied to
933 the value of name used in this fashion.
934
935 If used with a nested parameter or command substitution, the
936 result of that will be taken as a parameter name in the same
937 way. For example, if you have `foo=bar' and `bar=baz', the
938 strings ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo bar)} will be
939 expanded to `baz'.
940
941 Likewise, if the reference is itself nested, the expression with
942 the flag is treated as if it were directly replaced by the
943 parameter name. It is an error if this nested substitution pro‐
944 duces an array with more than one word. For example, if
945 `name=assoc' where the parameter assoc is an associative array,
946 then `${${(P)name}[elt]}' refers to the element of the associa‐
947 tive subscripted `elt'.
948
949 q Quote characters that are special to the shell in the resulting
950 words with backslashes; unprintable or invalid characters are
951 quoted using the $'\NNN' form, with separate quotes for each
952 octet.
953
954 If this flag is given twice, the resulting words are quoted in
955 single quotes and if it is given three times, the words are
956 quoted in double quotes; in these forms no special handling of
957 unprintable or invalid characters is attempted. If the flag is
958 given four times, the words are quoted in single quotes preceded
959 by a $. Note that in all three of these forms quoting is done
960 unconditionally, even if this does not change the way the
961 resulting string would be interpreted by the shell.
962
963 If a q- is given (only a single q may appear), a minimal form of
964 single quoting is used that only quotes the string if needed to
965 protect special characters. Typically this form gives the most
966 readable output.
967
968 If a q+ is given, an extended form of minmal quoting is used
969 that causes unprintable characters to be rendered using $'...'.
970 This quoting is similar to that used by the output of values by
971 the typeset family of commands.
972
973 Q Remove one level of quotes from the resulting words.
974
975 t Use a string describing the type of the parameter where the
976 value of the parameter would usually appear. This string con‐
977 sists of keywords separated by hyphens (`-'). The first keyword
978 in the string describes the main type, it can be one of
979 `scalar', `array', `integer', `float' or `association'. The
980 other keywords describe the type in more detail:
981
982 local for local parameters
983
984 left for left justified parameters
985
986 right_blanks
987 for right justified parameters with leading blanks
988
989 right_zeros
990 for right justified parameters with leading zeros
991
992 lower for parameters whose value is converted to all lower case
993 when it is expanded
994
995 upper for parameters whose value is converted to all upper case
996 when it is expanded
997
998 readonly
999 for readonly parameters
1000
1001 tag for tagged parameters
1002
1003 export for exported parameters
1004
1005 unique for arrays which keep only the first occurrence of dupli‐
1006 cated values
1007
1008 hide for parameters with the `hide' flag
1009
1010 hideval
1011 for parameters with the `hideval' flag
1012
1013 special
1014 for special parameters defined by the shell
1015
1016 u Expand only the first occurrence of each unique word.
1017
1018 U Convert all letters in the result to upper case.
1019
1020 v Used with k, substitute (as two consecutive words) both the key
1021 and the value of each associative array element. Used with sub‐
1022 scripts, force values to be substituted even if the subscript
1023 form refers to indices or keys.
1024
1025 V Make any special characters in the resulting words visible.
1026
1027 w With ${#name}, count words in arrays or strings; the s flag may
1028 be used to set a word delimiter.
1029
1030 W Similar to w with the difference that empty words between
1031 repeated delimiters are also counted.
1032
1033 X With this flag, parsing errors occurring with the Q, e and #
1034 flags or the pattern matching forms such as `${name#pattern}'
1035 are reported. Without the flag, errors are silently ignored.
1036
1037 z Split the result of the expansion into words using shell parsing
1038 to find the words, i.e. taking into account any quoting in the
1039 value. Comments are not treated specially but as ordinary
1040 strings, similar to interactive shells with the INTERACTIVE_COM‐
1041 MENTS option unset (however, see the Z flag below for related
1042 options)
1043
1044 Note that this is done very late, even later than the `(s)'
1045 flag. So to access single words in the result use nested expan‐
1046 sions as in `${${(z)foo}[2]}'. Likewise, to remove the quotes in
1047 the resulting words use `${(Q)${(z)foo}}'.
1048
1049 0 Split the result of the expansion on null bytes. This is a
1050 shorthand for `ps:\0:'.
1051
1052 The following flags (except p) are followed by one or more arguments as
1053 shown. Any character, or the matching pairs `(...)', `{...}', `[...]',
1054 or `<...>', may be used in place of a colon as delimiters, but note
1055 that when a flag takes more than one argument, a matched pair of delim‐
1056 iters must surround each argument.
1057
1058 p Recognize the same escape sequences as the print builtin in
1059 string arguments to any of the flags described below that follow
1060 this argument.
1061
1062 Alternatively, with this option string arguments may be in the
1063 form $var in which case the value of the variable is substi‐
1064 tuted. Note this form is strict; the string argument does not
1065 undergo general parameter expansion.
1066
1067 For example,
1068
1069 sep=:
1070 val=a:b:c
1071 print ${(ps.$sep.)val}
1072
1073 splits the variable on a :.
1074
1075 ~ Strings inserted into the expansion by any of the flags below
1076 are to be treated as patterns. This applies to the string argu‐
1077 ments of flags that follow ~ within the same set of parentheses.
1078 Compare with ~ outside parentheses, which forces the entire sub‐
1079 stituted string to be treated as a pattern. Hence, for example,
1080
1081 [[ "?" = ${(~j.|.)array} ]]
1082
1083 treats `|' as a pattern and succeeds if and only if $array con‐
1084 tains the string `?' as an element. The ~ may be repeated to
1085 toggle the behaviour; its effect only lasts to the end of the
1086 parenthesised group.
1087
1088 j:string:
1089 Join the words of arrays together using string as a separator.
1090 Note that this occurs before field splitting by the s:string:
1091 flag or the SH_WORD_SPLIT option.
1092
1093 l:expr::string1::string2:
1094 Pad the resulting words on the left. Each word will be trun‐
1095 cated if required and placed in a field expr characters wide.
1096
1097 The arguments :string1: and :string2: are optional; neither, the
1098 first, or both may be given. Note that the same pairs of delim‐
1099 iters must be used for each of the three arguments. The space
1100 to the left will be filled with string1 (concatenated as often
1101 as needed) or spaces if string1 is not given. If both string1
1102 and string2 are given, string2 is inserted once directly to the
1103 left of each word, truncated if necessary, before string1 is
1104 used to produce any remaining padding.
1105
1106 If either of string1 or string2 is present but empty, i.e. there
1107 are two delimiters together at that point, the first character
1108 of $IFS is used instead.
1109
1110 If the MULTIBYTE option is in effect, the flag m may also be
1111 given, in which case widths will be used for the calculation of
1112 padding; otherwise individual multibyte characters are treated
1113 as occupying one unit of width.
1114
1115 If the MULTIBYTE option is not in effect, each byte in the
1116 string is treated as occupying one unit of width.
1117
1118 Control characters are always assumed to be one unit wide; this
1119 allows the mechanism to be used for generating repetitions of
1120 control characters.
1121
1122 m Only useful together with one of the flags l or r or with the #
1123 length operator when the MULTIBYTE option is in effect. Use the
1124 character width reported by the system in calculating how much
1125 of the string it occupies or the overall length of the string.
1126 Most printable characters have a width of one unit, however cer‐
1127 tain Asian character sets and certain special effects use wider
1128 characters; combining characters have zero width. Non-printable
1129 characters are arbitrarily counted as zero width; how they would
1130 actually be displayed will vary.
1131
1132 If the m is repeated, the character either counts zero (if it
1133 has zero width), else one. For printable character strings this
1134 has the effect of counting the number of glyphs (visibly sepa‐
1135 rate characters), except for the case where combining characters
1136 themselves have non-zero width (true in certain alphabets).
1137
1138 r:expr::string1::string2:
1139 As l, but pad the words on the right and insert string2 immedi‐
1140 ately to the right of the string to be padded.
1141
1142 Left and right padding may be used together. In this case the
1143 strategy is to apply left padding to the first half width of
1144 each of the resulting words, and right padding to the second
1145 half. If the string to be padded has odd width the extra pad‐
1146 ding is applied on the left.
1147
1148 s:string:
1149 Force field splitting at the separator string. Note that a
1150 string of two or more characters means that all of them must
1151 match in sequence; this differs from the treatment of two or
1152 more characters in the IFS parameter. See also the = flag and
1153 the SH_WORD_SPLIT option. An empty string may also be given in
1154 which case every character will be a separate element.
1155
1156 For historical reasons, the usual behaviour that empty array
1157 elements are retained inside double quotes is disabled for
1158 arrays generated by splitting; hence the following:
1159
1160 line="one::three"
1161 print -l "${(s.:.)line}"
1162
1163 produces two lines of output for one and three and elides the
1164 empty field. To override this behaviour, supply the `(@)' flag
1165 as well, i.e. "${(@s.:.)line}".
1166
1167 Z:opts:
1168 As z but takes a combination of option letters between a follow‐
1169 ing pair of delimiter characters. With no options the effect is
1170 identical to z. (Z+c+) causes comments to be parsed as a string
1171 and retained; any field in the resulting array beginning with an
1172 unquoted comment character is a comment. (Z+C+) causes comments
1173 to be parsed and removed. The rule for comments is standard:
1174 anything between a word starting with the third character of
1175 $HISTCHARS, default #, up to the next newline is a comment.
1176 (Z+n+) causes unquoted newlines to be treated as ordinary white‐
1177 space, else they are treated as if they are shell code delim‐
1178 iters and converted to semicolons. Options are combined within
1179 the same set of delimiters, e.g. (Z+Cn+).
1180
1181 _:flags:
1182 The underscore (_) flag is reserved for future use. As of this
1183 revision of zsh, there are no valid flags; anything following an
1184 underscore, other than an empty pair of delimiters, is treated
1185 as an error, and the flag itself has no effect.
1186
1187 The following flags are meaningful with the ${...#...} or ${...%...}
1188 forms. The S and I flags may also be used with the ${.../...} forms.
1189
1190 S Search substrings as well as beginnings or ends; with # start
1191 from the beginning and with % start from the end of the string.
1192 With substitution via ${.../...} or ${...//...}, specifies
1193 non-greedy matching, i.e. that the shortest instead of the long‐
1194 est match should be replaced.
1195
1196 I:expr:
1197 Search the exprth match (where expr evaluates to a number).
1198 This only applies when searching for substrings, either with the
1199 S flag, or with ${.../...} (only the exprth match is substi‐
1200 tuted) or ${...//...} (all matches from the exprth on are sub‐
1201 stituted). The default is to take the first match.
1202
1203 The exprth match is counted such that there is either one or
1204 zero matches from each starting position in the string, although
1205 for global substitution matches overlapping previous replace‐
1206 ments are ignored. With the ${...%...} and ${...%%...} forms,
1207 the starting position for the match moves backwards from the end
1208 as the index increases, while with the other forms it moves for‐
1209 ward from the start.
1210
1211 Hence with the string
1212 which switch is the right switch for Ipswich?
1213 substitutions of the form ${(SI:N:)string#w*ch} as N increases
1214 from 1 will match and remove `which', `witch', `witch' and
1215 `wich'; the form using `##' will match and remove `which switch
1216 is the right switch for Ipswich', `witch is the right switch for
1217 Ipswich', `witch for Ipswich' and `wich'. The form using `%'
1218 will remove the same matches as for `#', but in reverse order,
1219 and the form using `%%' will remove the same matches as for `##'
1220 in reverse order.
1221
1222 B Include the index of the beginning of the match in the result.
1223
1224 E Include the index one character past the end of the match in the
1225 result (note this is inconsistent with other uses of parameter
1226 index).
1227
1228 M Include the matched portion in the result.
1229
1230 N Include the length of the match in the result.
1231
1232 R Include the unmatched portion in the result (the Rest).
1233
1234 Rules
1235 Here is a summary of the rules for substitution; this assumes that
1236 braces are present around the substitution, i.e. ${...}. Some particu‐
1237 lar examples are given below. Note that the Zsh Development Group
1238 accepts no responsibility for any brain damage which may occur during
1239 the reading of the following rules.
1240
1241 1. Nested substitution
1242 If multiple nested ${...} forms are present, substitution is
1243 performed from the inside outwards. At each level, the substi‐
1244 tution takes account of whether the current value is a scalar or
1245 an array, whether the whole substitution is in double quotes,
1246 and what flags are supplied to the current level of substitu‐
1247 tion, just as if the nested substitution were the outermost.
1248 The flags are not propagated up to enclosing substitutions; the
1249 nested substitution will return either a scalar or an array as
1250 determined by the flags, possibly adjusted for quoting. All the
1251 following steps take place where applicable at all levels of
1252 substitution.
1253
1254 Note that, unless the `(P)' flag is present, the flags and any
1255 subscripts apply directly to the value of the nested substitu‐
1256 tion; for example, the expansion ${${foo}} behaves exactly the
1257 same as ${foo}. When the `(P)' flag is present in a nested sub‐
1258 stitution, the other substitution rules are applied to the value
1259 before it is interpreted as a name, so ${${(P)foo}} may differ
1260 from ${(P)foo}.
1261
1262 At each nested level of substitution, the substituted words
1263 undergo all forms of single-word substitution (i.e. not filename
1264 generation), including command substitution, arithmetic expan‐
1265 sion and filename expansion (i.e. leading ~ and =). Thus, for
1266 example, ${${:-=cat}:h} expands to the directory where the cat
1267 program resides. (Explanation: the internal substitution has no
1268 parameter but a default value =cat, which is expanded by file‐
1269 name expansion to a full path; the outer substitution then
1270 applies the modifier :h and takes the directory part of the
1271 path.)
1272
1273 2. Internal parameter flags
1274 Any parameter flags set by one of the typeset family of com‐
1275 mands, in particular the -L, -R, -Z, -u and -l options for pad‐
1276 ding and capitalization, are applied directly to the parameter
1277 value. Note these flags are options to the command, e.g. `type‐
1278 set -Z'; they are not the same as the flags used within parame‐
1279 ter substitutions.
1280
1281 At the outermost level of substitution, the `(P)' flag (rule 4.)
1282 ignores these transformations and uses the unmodified value of
1283 the parameter as the name to be replaced. This is usually the
1284 desired behavior because padding may make the value syntacti‐
1285 cally illegal as a parameter name, but if capitalization changes
1286 are desired, use the ${${(P)foo}} form (rule 25.).
1287
1288 3. Parameter subscripting
1289 If the value is a raw parameter reference with a subscript, such
1290 as ${var[3]}, the effect of subscripting is applied directly to
1291 the parameter. Subscripts are evaluated left to right; subse‐
1292 quent subscripts apply to the scalar or array value yielded by
1293 the previous subscript. Thus if var is an array, ${var[1][2]}
1294 is the second character of the first word, but ${var[2,4][2]} is
1295 the entire third word (the second word of the range of words two
1296 through four of the original array). Any number of subscripts
1297 may appear. Flags such as `(k)' and `(v)' which alter the
1298 result of subscripting are applied.
1299
1300 4. Parameter name replacement
1301 At the outermost level of nesting only, the `(P)' flag is
1302 applied. This treats the value so far as a parameter name
1303 (which may include a subscript expression) and replaces that
1304 with the corresponding value. This replacement occurs later if
1305 the `(P)' flag appears in a nested substitution.
1306
1307 If the value so far names a parameter that has internal flags
1308 (rule 2.), those internal flags are applied to the new value
1309 after replacement.
1310
1311 5. Double-quoted joining
1312 If the value after this process is an array, and the substitu‐
1313 tion appears in double quotes, and neither an `(@)' flag nor a
1314 `#' length operator is present at the current level, then words
1315 of the value are joined with the first character of the parame‐
1316 ter $IFS, by default a space, between each word (single word
1317 arrays are not modified). If the `(j)' flag is present, that is
1318 used for joining instead of $IFS.
1319
1320 6. Nested subscripting
1321 Any remaining subscripts (i.e. of a nested substitution) are
1322 evaluated at this point, based on whether the value is an array
1323 or a scalar. As with 3., multiple subscripts can appear. Note
1324 that ${foo[2,4][2]} is thus equivalent to ${${foo[2,4]}[2]} and
1325 also to "${${(@)foo[2,4]}[2]}" (the nested substitution returns
1326 an array in both cases), but not to "${${foo[2,4]}[2]}" (the
1327 nested substitution returns a scalar because of the quotes).
1328
1329 7. Modifiers
1330 Any modifiers, as specified by a trailing `#', `%', `/' (possi‐
1331 bly doubled) or by a set of modifiers of the form `:...' (see
1332 the section `Modifiers' in the section `History Expansion'), are
1333 applied to the words of the value at this level.
1334
1335 8. Character evaluation
1336 Any `(#)' flag is applied, evaluating the result so far numeri‐
1337 cally as a character.
1338
1339 9. Length
1340 Any initial `#' modifier, i.e. in the form ${#var}, is used to
1341 evaluate the length of the expression so far.
1342
1343 10. Forced joining
1344 If the `(j)' flag is present, or no `(j)' flag is present but
1345 the string is to be split as given by rule 11., and joining did
1346 not take place at rule 5., any words in the value are joined
1347 together using the given string or the first character of $IFS
1348 if none. Note that the `(F)' flag implicitly supplies a string
1349 for joining in this manner.
1350
1351 11. Simple word splitting
1352 If one of the `(s)' or `(f)' flags are present, or the `=' spec‐
1353 ifier was present (e.g. ${=var}), the word is split on occur‐
1354 rences of the specified string, or (for = with neither of the
1355 two flags present) any of the characters in $IFS.
1356
1357 If no `(s)', `(f)' or `=' was given, but the word is not quoted
1358 and the option SH_WORD_SPLIT is set, the word is split on occur‐
1359 rences of any of the characters in $IFS. Note this step, too,
1360 takes place at all levels of a nested substitution.
1361
1362 12. Case modification
1363 Any case modification from one of the flags `(L)', `(U)' or
1364 `(C)' is applied.
1365
1366 13. Escape sequence replacement
1367 First any replacements from the `(g)' flag are performed, then
1368 any prompt-style formatting from the `(%)' family of flags is
1369 applied.
1370
1371 14. Quote application
1372 Any quoting or unquoting using `(q)' and `(Q)' and related flags
1373 is applied.
1374
1375 15. Directory naming
1376 Any directory name substitution using `(D)' flag is applied.
1377
1378 16. Visibility enhancement
1379 Any modifications to make characters visible using the `(V)'
1380 flag are applied.
1381
1382 17. Lexical word splitting
1383 If the '(z)' flag or one of the forms of the '(Z)' flag is
1384 present, the word is split as if it were a shell command line,
1385 so that quotation marks and other metacharacters are used to
1386 decide what constitutes a word. Note this form of splitting is
1387 entirely distinct from that described by rule 11.: it does not
1388 use $IFS, and does not cause forced joining.
1389
1390 18. Uniqueness
1391 If the result is an array and the `(u)' flag was present, dupli‐
1392 cate elements are removed from the array.
1393
1394 19. Ordering
1395 If the result is still an array and one of the `(o)' or `(O)'
1396 flags was present, the array is reordered.
1397
1398 20. RC_EXPAND_PARAM
1399 At this point the decision is made whether any resulting array
1400 elements are to be combined element by element with surrounding
1401 text, as given by either the RC_EXPAND_PARAM option or the `^'
1402 flag.
1403
1404 21. Re-evaluation
1405 Any `(e)' flag is applied to the value, forcing it to be
1406 re-examined for new parameter substitutions, but also for com‐
1407 mand and arithmetic substitutions.
1408
1409 22. Padding
1410 Any padding of the value by the `(l.fill.)' or `(r.fill.)' flags
1411 is applied.
1412
1413 23. Semantic joining
1414 In contexts where expansion semantics requires a single word to
1415 result, all words are rejoined with the first character of IFS
1416 between. So in `${(P)${(f)lines}}' the value of ${lines} is
1417 split at newlines, but then must be joined again before the
1418 `(P)' flag can be applied.
1419
1420 If a single word is not required, this rule is skipped.
1421
1422 24. Empty argument removal
1423 If the substitution does not appear in double quotes, any
1424 resulting zero-length argument, whether from a scalar or an ele‐
1425 ment of an array, is elided from the list of arguments inserted
1426 into the command line.
1427
1428 Strictly speaking, the removal happens later as the same happens
1429 with other forms of substitution; the point to note here is sim‐
1430 ply that it occurs after any of the above parameter operations.
1431
1432 25. Nested parameter name replacement
1433 If the `(P)' flag is present and rule 4. has not applied, the
1434 value so far is treated as a parameter name (which may include a
1435 subscript expression) and replaced with the corresponding value,
1436 with internal flags (rule 2.) applied to the new value.
1437
1438 Examples
1439 The flag f is useful to split a double-quoted substitution line by
1440 line. For example, ${(f)"$(<file)"} substitutes the contents of file
1441 divided so that each line is an element of the resulting array. Com‐
1442 pare this with the effect of $(<file) alone, which divides the file up
1443 by words, or the same inside double quotes, which makes the entire con‐
1444 tent of the file a single string.
1445
1446 The following illustrates the rules for nested parameter expansions.
1447 Suppose that $foo contains the array (bar baz):
1448
1449 "${(@)${foo}[1]}"
1450 This produces the result b. First, the inner substitution
1451 "${foo}", which has no array (@) flag, produces a single word
1452 result "bar baz". The outer substitution "${(@)...[1]}" detects
1453 that this is a scalar, so that (despite the `(@)' flag) the sub‐
1454 script picks the first character.
1455
1456 "${${(@)foo}[1]}"
1457 This produces the result `bar'. In this case, the inner substi‐
1458 tution "${(@)foo}" produces the array `(bar baz)'. The outer
1459 substitution "${...[1]}" detects that this is an array and picks
1460 the first word. This is similar to the simple case "${foo[1]}".
1461
1462 As an example of the rules for word splitting and joining, suppose $foo
1463 contains the array `(ax1 bx1)'. Then
1464
1465 ${(s/x/)foo}
1466 produces the words `a', `1 b' and `1'.
1467
1468 ${(j/x/s/x/)foo}
1469 produces `a', `1', `b' and `1'.
1470
1471 ${(s/x/)foo%%1*}
1472 produces `a' and ` b' (note the extra space). As substitution
1473 occurs before either joining or splitting, the operation first
1474 generates the modified array (ax bx), which is joined to give
1475 "ax bx", and then split to give `a', ` b' and `'. The final
1476 empty string will then be elided, as it is not in double quotes.
1477
1479 A command enclosed in parentheses preceded by a dollar sign, like
1480 `$(...)', or quoted with grave accents, like ``...`', is replaced with
1481 its standard output, with any trailing newlines deleted. If the sub‐
1482 stitution is not enclosed in double quotes, the output is broken into
1483 words using the IFS parameter.
1484
1485 The substitution `$(cat foo)' may be replaced by the faster `$(<foo)'.
1486 In this case foo undergoes single word shell expansions (parameter
1487 expansion, command substitution and arithmetic expansion), but not
1488 filename generation.
1489
1490 If the option GLOB_SUBST is set, the result of any unquoted command
1491 substitution, including the special form just mentioned, is eligible
1492 for filename generation.
1493
1495 A string of the form `$[exp]' or `$((exp))' is substituted with the
1496 value of the arithmetic expression exp. exp is subjected to parameter
1497 expansion, command substitution and arithmetic expansion before it is
1498 evaluated. See the section `Arithmetic Evaluation'.
1499
1501 A string of the form `foo{xx,yy,zz}bar' is expanded to the individual
1502 words `fooxxbar', `fooyybar' and `foozzbar'. Left-to-right order is
1503 preserved. This construct may be nested. Commas may be quoted in
1504 order to include them literally in a word.
1505
1506 An expression of the form `{n1..n2}', where n1 and n2 are integers, is
1507 expanded to every number between n1 and n2 inclusive. If either number
1508 begins with a zero, all the resulting numbers will be padded with lead‐
1509 ing zeroes to that minimum width, but for negative numbers the - char‐
1510 acter is also included in the width. If the numbers are in decreasing
1511 order the resulting sequence will also be in decreasing order.
1512
1513 An expression of the form `{n1..n2..n3}', where n1, n2, and n3 are
1514 integers, is expanded as above, but only every n3th number starting
1515 from n1 is output. If n3 is negative the numbers are output in reverse
1516 order, this is slightly different from simply swapping n1 and n2 in the
1517 case that the step n3 doesn't evenly divide the range. Zero padding
1518 can be specified in any of the three numbers, specifying it in the
1519 third can be useful to pad for example `{-99..100..01}' which is not
1520 possible to specify by putting a 0 on either of the first two numbers
1521 (i.e. pad to two characters).
1522
1523 An expression of the form `{c1..c2}', where c1 and c2 are single char‐
1524 acters (which may be multibyte characters), is expanded to every char‐
1525 acter in the range from c1 to c2 in whatever character sequence is used
1526 internally. For characters with code points below 128 this is US ASCII
1527 (this is the only case most users will need). If any intervening char‐
1528 acter is not printable, appropriate quotation is used to render it
1529 printable. If the character sequence is reversed, the output is in
1530 reverse order, e.g. `{d..a}' is substituted as `d c b a'.
1531
1532 If a brace expression matches none of the above forms, it is left
1533 unchanged, unless the option BRACE_CCL (an abbreviation for `brace
1534 character class') is set. In that case, it is expanded to a list of
1535 the individual characters between the braces sorted into the order of
1536 the characters in the ASCII character set (multibyte characters are not
1537 currently handled). The syntax is similar to a [...] expression in
1538 filename generation: `-' is treated specially to denote a range of
1539 characters, but `^' or `!' as the first character is treated normally.
1540 For example, `{abcdef0-9}' expands to 16 words 0 1 2 3 4 5 6 7 8 9 a b
1541 c d e f.
1542
1543 Note that brace expansion is not part of filename generation (glob‐
1544 bing); an expression such as */{foo,bar} is split into two separate
1545 words */foo and */bar before filename generation takes place. In par‐
1546 ticular, note that this is liable to produce a `no match' error if
1547 either of the two expressions does not match; this is to be contrasted
1548 with */(foo|bar), which is treated as a single pattern but otherwise
1549 has similar effects.
1550
1551 To combine brace expansion with array expansion, see the ${^spec} form
1552 described in the section Parameter Expansion above.
1553
1555 Each word is checked to see if it begins with an unquoted `~'. If it
1556 does, then the word up to a `/', or the end of the word if there is no
1557 `/', is checked to see if it can be substituted in one of the ways
1558 described here. If so, then the `~' and the checked portion are
1559 replaced with the appropriate substitute value.
1560
1561 A `~' by itself is replaced by the value of $HOME. A `~' followed by a
1562 `+' or a `-' is replaced by current or previous working directory,
1563 respectively.
1564
1565 A `~' followed by a number is replaced by the directory at that posi‐
1566 tion in the directory stack. `~0' is equivalent to `~+', and `~1' is
1567 the top of the stack. `~+' followed by a number is replaced by the
1568 directory at that position in the directory stack. `~+0' is equivalent
1569 to `~+', and `~+1' is the top of the stack. `~-' followed by a number
1570 is replaced by the directory that many positions from the bottom of the
1571 stack. `~-0' is the bottom of the stack. The PUSHD_MINUS option
1572 exchanges the effects of `~+' and `~-' where they are followed by a
1573 number.
1574
1575 Dynamic named directories
1576 If the function zsh_directory_name exists, or the shell variable
1577 zsh_directory_name_functions exists and contains an array of function
1578 names, then the functions are used to implement dynamic directory nam‐
1579 ing. The functions are tried in order until one returns status zero,
1580 so it is important that functions test whether they can handle the case
1581 in question and return an appropriate status.
1582
1583 A `~' followed by a string namstr in unquoted square brackets is
1584 treated specially as a dynamic directory name. Note that the first
1585 unquoted closing square bracket always terminates namstr. The shell
1586 function is passed two arguments: the string n (for name) and namstr.
1587 It should either set the array reply to a single element which is the
1588 directory corresponding to the name and return status zero (executing
1589 an assignment as the last statement is usually sufficient), or it
1590 should return status non-zero. In the former case the element of reply
1591 is used as the directory; in the latter case the substitution is deemed
1592 to have failed. If all functions fail and the option NOMATCH is set,
1593 an error results.
1594
1595 The functions defined as above are also used to see if a directory can
1596 be turned into a name, for example when printing the directory stack or
1597 when expanding %~ in prompts. In this case each function is passed two
1598 arguments: the string d (for directory) and the candidate for dynamic
1599 naming. The function should either return non-zero status, if the
1600 directory cannot be named by the function, or it should set the array
1601 reply to consist of two elements: the first is the dynamic name for the
1602 directory (as would appear within `~[...]'), and the second is the pre‐
1603 fix length of the directory to be replaced. For example, if the trial
1604 directory is /home/myname/src/zsh and the dynamic name for
1605 /home/myname/src (which has 16 characters) is s, then the function sets
1606
1607 reply=(s 16)
1608
1609 The directory name so returned is compared with possible static names
1610 for parts of the directory path, as described below; it is used if the
1611 prefix length matched (16 in the example) is longer than that matched
1612 by any static name.
1613
1614 It is not a requirement that a function implements both n and d calls;
1615 for example, it might be appropriate for certain dynamic forms of
1616 expansion not to be contracted to names. In that case any call with
1617 the first argument d should cause a non-zero status to be returned.
1618
1619 The completion system calls `zsh_directory_name c' followed by equiva‐
1620 lent calls to elements of the array zsh_directory_name_functions, if it
1621 exists, in order to complete dynamic names for directories. The code
1622 for this should be as for any other completion function as described in
1623 zshcompsys(1).
1624
1625 As a working example, here is a function that expands any dynamic names
1626 beginning with the string p: to directories below /home/pws/perforce.
1627 In this simple case a static name for the directory would be just as
1628 effective.
1629
1630 zsh_directory_name() {
1631 emulate -L zsh
1632 setopt extendedglob
1633 local -a match mbegin mend
1634 if [[ $1 = d ]]; then
1635 # turn the directory into a name
1636 if [[ $2 = (#b)(/home/pws/perforce/)([^/]##)* ]]; then
1637 typeset -ga reply
1638 reply=(p:$match[2] $(( ${#match[1]} + ${#match[2]} )) )
1639 else
1640 return 1
1641 fi
1642 elif [[ $1 = n ]]; then
1643 # turn the name into a directory
1644 [[ $2 != (#b)p:(?*) ]] && return 1
1645 typeset -ga reply
1646 reply=(/home/pws/perforce/$match[1])
1647 elif [[ $1 = c ]]; then
1648 # complete names
1649 local expl
1650 local -a dirs
1651 dirs=(/home/pws/perforce/*(/:t))
1652 dirs=(p:${^dirs})
1653 _wanted dynamic-dirs expl 'dynamic directory' compadd -S\] -a dirs
1654 return
1655 else
1656 return 1
1657 fi
1658 return 0
1659 }
1660
1661 Static named directories
1662 A `~' followed by anything not already covered consisting of any number
1663 of alphanumeric characters or underscore (`_'), hyphen (`-'), or dot
1664 (`.') is looked up as a named directory, and replaced by the value of
1665 that named directory if found. Named directories are typically home
1666 directories for users on the system. They may also be defined if the
1667 text after the `~' is the name of a string shell parameter whose value
1668 begins with a `/'. Note that trailing slashes will be removed from the
1669 path to the directory (though the original parameter is not modified).
1670
1671 It is also possible to define directory names using the -d option to
1672 the hash builtin.
1673
1674 When the shell prints a path (e.g. when expanding %~ in prompts or when
1675 printing the directory stack), the path is checked to see if it has a
1676 named directory as its prefix. If so, then the prefix portion is
1677 replaced with a `~' followed by the name of the directory. The shorter
1678 of the two ways of referring to the directory is used, i.e. either the
1679 directory name or the full path; the name is used if they are the same
1680 length. The parameters $PWD and $OLDPWD are never abbreviated in this
1681 fashion.
1682
1683 `=' expansion
1684 If a word begins with an unquoted `=' and the EQUALS option is set, the
1685 remainder of the word is taken as the name of a command. If a command
1686 exists by that name, the word is replaced by the full pathname of the
1687 command.
1688
1689 Notes
1690 Filename expansion is performed on the right hand side of a parameter
1691 assignment, including those appearing after commands of the typeset
1692 family. In this case, the right hand side will be treated as a
1693 colon-separated list in the manner of the PATH parameter, so that a `~'
1694 or an `=' following a `:' is eligible for expansion. All such behav‐
1695 iour can be disabled by quoting the `~', the `=', or the whole expres‐
1696 sion (but not simply the colon); the EQUALS option is also respected.
1697
1698 If the option MAGIC_EQUAL_SUBST is set, any unquoted shell argument in
1699 the form `identifier=expression' becomes eligible for file expansion as
1700 described in the previous paragraph. Quoting the first `=' also
1701 inhibits this.
1702
1704 If a word contains an unquoted instance of one of the characters `*',
1705 `(', `|', `<', `[', or `?', it is regarded as a pattern for filename
1706 generation, unless the GLOB option is unset. If the EXTENDED_GLOB
1707 option is set, the `^' and `#' characters also denote a pattern; other‐
1708 wise they are not treated specially by the shell.
1709
1710 The word is replaced with a list of sorted filenames that match the
1711 pattern. If no matching pattern is found, the shell gives an error
1712 message, unless the NULL_GLOB option is set, in which case the word is
1713 deleted; or unless the NOMATCH option is unset, in which case the word
1714 is left unchanged.
1715
1716 In filename generation, the character `/' must be matched explicitly;
1717 also, a `.' must be matched explicitly at the beginning of a pattern or
1718 after a `/', unless the GLOB_DOTS option is set. No filename genera‐
1719 tion pattern matches the files `.' or `..'. In other instances of pat‐
1720 tern matching, the `/' and `.' are not treated specially.
1721
1722 Glob Operators
1723 * Matches any string, including the null string.
1724
1725 ? Matches any character.
1726
1727 [...] Matches any of the enclosed characters. Ranges of characters
1728 can be specified by separating two characters by a `-'. A `-'
1729 or `]' may be matched by including it as the first character in
1730 the list. There are also several named classes of characters,
1731 in the form `[:name:]' with the following meanings. The first
1732 set use the macros provided by the operating system to test for
1733 the given character combinations, including any modifications
1734 due to local language settings, see ctype(3):
1735
1736 [:alnum:]
1737 The character is alphanumeric
1738
1739 [:alpha:]
1740 The character is alphabetic
1741
1742 [:ascii:]
1743 The character is 7-bit, i.e. is a single-byte character
1744 without the top bit set.
1745
1746 [:blank:]
1747 The character is a blank character
1748
1749 [:cntrl:]
1750 The character is a control character
1751
1752 [:digit:]
1753 The character is a decimal digit
1754
1755 [:graph:]
1756 The character is a printable character other than white‐
1757 space
1758
1759 [:lower:]
1760 The character is a lowercase letter
1761
1762 [:print:]
1763 The character is printable
1764
1765 [:punct:]
1766 The character is printable but neither alphanumeric nor
1767 whitespace
1768
1769 [:space:]
1770 The character is whitespace
1771
1772 [:upper:]
1773 The character is an uppercase letter
1774
1775 [:xdigit:]
1776 The character is a hexadecimal digit
1777
1778 Another set of named classes is handled internally by the shell
1779 and is not sensitive to the locale:
1780
1781 [:IDENT:]
1782 The character is allowed to form part of a shell identi‐
1783 fier, such as a parameter name
1784
1785 [:IFS:]
1786 The character is used as an input field separator, i.e.
1787 is contained in the IFS parameter
1788
1789 [:IFSSPACE:]
1790 The character is an IFS white space character; see the
1791 documentation for IFS in the zshparam(1) manual page.
1792
1793 [:INCOMPLETE:]
1794 Matches a byte that starts an incomplete multibyte char‐
1795 acter. Note that there may be a sequence of more than
1796 one bytes that taken together form the prefix of a multi‐
1797 byte character. To test for a potentially incomplete
1798 byte sequence, use the pattern `[[:INCOMPLETE:]]*'. This
1799 will never match a sequence starting with a valid multi‐
1800 byte character.
1801
1802 [:INVALID:]
1803 Matches a byte that does not start a valid multibyte
1804 character. Note this may be a continuation byte of an
1805 incomplete multibyte character as any part of a multibyte
1806 string consisting of invalid and incomplete multibyte
1807 characters is treated as single bytes.
1808
1809 [:WORD:]
1810 The character is treated as part of a word; this test is
1811 sensitive to the value of the WORDCHARS parameter
1812
1813 Note that the square brackets are additional to those enclosing
1814 the whole set of characters, so to test for a single alphanu‐
1815 meric character you need `[[:alnum:]]'. Named character sets
1816 can be used alongside other types, e.g. `[[:alpha:]0-9]'.
1817
1818 [^...]
1819 [!...] Like [...], except that it matches any character which is not in
1820 the given set.
1821
1822 <[x]-[y]>
1823 Matches any number in the range x to y, inclusive. Either of
1824 the numbers may be omitted to make the range open-ended; hence
1825 `<->' matches any number. To match individual digits, the [...]
1826 form is more efficient.
1827
1828 Be careful when using other wildcards adjacent to patterns of
1829 this form; for example, <0-9>* will actually match any number
1830 whatsoever at the start of the string, since the `<0-9>' will
1831 match the first digit, and the `*' will match any others. This
1832 is a trap for the unwary, but is in fact an inevitable conse‐
1833 quence of the rule that the longest possible match always suc‐
1834 ceeds. Expressions such as `<0-9>[^[:digit:]]*' can be used
1835 instead.
1836
1837 (...) Matches the enclosed pattern. This is used for grouping. If
1838 the KSH_GLOB option is set, then a `@', `*', `+', `?' or `!'
1839 immediately preceding the `(' is treated specially, as detailed
1840 below. The option SH_GLOB prevents bare parentheses from being
1841 used in this way, though the KSH_GLOB option is still available.
1842
1843 Note that grouping cannot extend over multiple directories: it
1844 is an error to have a `/' within a group (this only applies for
1845 patterns used in filename generation). There is one exception:
1846 a group of the form (pat/)# appearing as a complete path segment
1847 can match a sequence of directories. For example, foo/(a*/)#bar
1848 matches foo/bar, foo/any/bar, foo/any/anyother/bar, and so on.
1849
1850 x|y Matches either x or y. This operator has lower precedence than
1851 any other. The `|' character must be within parentheses, to
1852 avoid interpretation as a pipeline. The alternatives are tried
1853 in order from left to right.
1854
1855 ^x (Requires EXTENDED_GLOB to be set.) Matches anything except the
1856 pattern x. This has a higher precedence than `/', so `^foo/bar'
1857 will search directories in `.' except `./foo' for a file named
1858 `bar'.
1859
1860 x~y (Requires EXTENDED_GLOB to be set.) Match anything that matches
1861 the pattern x but does not match y. This has lower precedence
1862 than any operator except `|', so `*/*~foo/bar' will search for
1863 all files in all directories in `.' and then exclude `foo/bar'
1864 if there was such a match. Multiple patterns can be excluded by
1865 `foo~bar~baz'. In the exclusion pattern (y), `/' and `.' are
1866 not treated specially the way they usually are in globbing.
1867
1868 x# (Requires EXTENDED_GLOB to be set.) Matches zero or more occur‐
1869 rences of the pattern x. This operator has high precedence;
1870 `12#' is equivalent to `1(2#)', rather than `[1m(12)#'. It is an
1871 error for an unquoted `#' to follow something which cannot be
1872 repeated; this includes an empty string, a pattern already fol‐
1873 lowed by `##', or parentheses when part of a KSH_GLOB pattern
1874 (for example, `!(foo)#' is invalid and must be replaced by
1875 `*(!(foo))').
1876
1877 x## (Requires EXTENDED_GLOB to be set.) Matches one or more occur‐
1878 rences of the pattern x. This operator has high precedence;
1879 `12##' is equivalent to `1(2##)', rather than `[1m(12)##'. No more
1880 than two active `#' characters may appear together. (Note the
1881 potential clash with glob qualifiers in the form `1(2##)' which
1882 should therefore be avoided.)
1883
1884 ksh-like Glob Operators
1885 If the KSH_GLOB option is set, the effects of parentheses can be modi‐
1886 fied by a preceding `@', `*', `+', `?' or `!'. This character need not
1887 be unquoted to have special effects, but the `(' must be.
1888
1889 @(...) Match the pattern in the parentheses. (Like `(...)'.)
1890
1891 *(...) Match any number of occurrences. (Like `(...)#', except that
1892 recursive directory searching is not supported.)
1893
1894 +(...) Match at least one occurrence. (Like `(...)##', except that
1895 recursive directory searching is not supported.)
1896
1897 ?(...) Match zero or one occurrence. (Like `(|...)'.)
1898
1899 !(...) Match anything but the expression in parentheses. (Like
1900 `(^(...))'.)
1901
1902 Precedence
1903 The precedence of the operators given above is (highest) `^', `/', `~',
1904 `|' (lowest); the remaining operators are simply treated from left to
1905 right as part of a string, with `#' and `##' applying to the shortest
1906 possible preceding unit (i.e. a character, `?', `[...]', `<...>', or a
1907 parenthesised expression). As mentioned above, a `/' used as a direc‐
1908 tory separator may not appear inside parentheses, while a `|' must do
1909 so; in patterns used in other contexts than filename generation (for
1910 example, in case statements and tests within `[[...]]'), a `/' is not
1911 special; and `/' is also not special after a `~' appearing outside
1912 parentheses in a filename pattern.
1913
1914 Globbing Flags
1915 There are various flags which affect any text to their right up to the
1916 end of the enclosing group or to the end of the pattern; they require
1917 the EXTENDED_GLOB option. All take the form (#X) where X may have one
1918 of the following forms:
1919
1920 i Case insensitive: upper or lower case characters in the pattern
1921 match upper or lower case characters.
1922
1923 l Lower case characters in the pattern match upper or lower case
1924 characters; upper case characters in the pattern still only
1925 match upper case characters.
1926
1927 I Case sensitive: locally negates the effect of i or l from that
1928 point on.
1929
1930 b Activate backreferences for parenthesised groups in the pattern;
1931 this does not work in filename generation. When a pattern with
1932 a set of active parentheses is matched, the strings matched by
1933 the groups are stored in the array $match, the indices of the
1934 beginning of the matched parentheses in the array $mbegin, and
1935 the indices of the end in the array $mend, with the first ele‐
1936 ment of each array corresponding to the first parenthesised
1937 group, and so on. These arrays are not otherwise special to the
1938 shell. The indices use the same convention as does parameter
1939 substitution, so that elements of $mend and $mbegin may be used
1940 in subscripts; the KSH_ARRAYS option is respected. Sets of
1941 globbing flags are not considered parenthesised groups; only the
1942 first nine active parentheses can be referenced.
1943
1944 For example,
1945
1946 foo="a string with a message"
1947 if [[ $foo = (a|an)' '(#b)(*)' '* ]]; then
1948 print ${foo[$mbegin[1],$mend[1]]}
1949 fi
1950
1951 prints `string with a'. Note that the first parenthesis is
1952 before the (#b) and does not create a backreference.
1953
1954 Backreferences work with all forms of pattern matching other
1955 than filename generation, but note that when performing matches
1956 on an entire array, such as ${array#pattern}, or a global sub‐
1957 stitution, such as ${param//pat/repl}, only the data for the
1958 last match remains available. In the case of global replace‐
1959 ments this may still be useful. See the example for the m flag
1960 below.
1961
1962 The numbering of backreferences strictly follows the order of
1963 the opening parentheses from left to right in the pattern
1964 string, although sets of parentheses may be nested. There are
1965 special rules for parentheses followed by `#' or `##'. Only the
1966 last match of the parenthesis is remembered: for example, in `[[
1967 abab = (#b)([ab])# ]]', only the final `b' is stored in
1968 match[1]. Thus extra parentheses may be necessary to match the
1969 complete segment: for example, use `X((ab|cd)#)Y' to match a
1970 whole string of either `ab' or `cd' between `X' and `Y', using
1971 the value of $match[1] rather than $match[2].
1972
1973 If the match fails none of the parameters is altered, so in some
1974 cases it may be necessary to initialise them beforehand. If
1975 some of the backreferences fail to match -- which happens if
1976 they are in an alternate branch which fails to match, or if they
1977 are followed by # and matched zero times -- then the matched
1978 string is set to the empty string, and the start and end indices
1979 are set to -1.
1980
1981 Pattern matching with backreferences is slightly slower than
1982 without.
1983
1984 B Deactivate backreferences, negating the effect of the b flag
1985 from that point on.
1986
1987 cN,M The flag (#cN,M) can be used anywhere that the # or ## operators
1988 can be used except in the expressions `(*/)#' and `(*/)##' in
1989 filename generation, where `/' has special meaning; it cannot be
1990 combined with other globbing flags and a bad pattern error
1991 occurs if it is misplaced. It is equivalent to the form {N,M}
1992 in regular expressions. The previous character or group is
1993 required to match between N and M times, inclusive. The form
1994 (#cN) requires exactly N matches; (#c,M) is equivalent to speci‐
1995 fying N as 0; (#cN,) specifies that there is no maximum limit on
1996 the number of matches.
1997
1998 m Set references to the match data for the entire string matched;
1999 this is similar to backreferencing and does not work in filename
2000 generation. The flag must be in effect at the end of the pat‐
2001 tern, i.e. not local to a group. The parameters $MATCH, $MBEGIN
2002 and $MEND will be set to the string matched and to the indices
2003 of the beginning and end of the string, respectively. This is
2004 most useful in parameter substitutions, as otherwise the string
2005 matched is obvious.
2006
2007 For example,
2008
2009 arr=(veldt jynx grimps waqf zho buck)
2010 print ${arr//(#m)[aeiou]/${(U)MATCH}}
2011
2012 forces all the matches (i.e. all vowels) into uppercase, print‐
2013 ing `vEldt jynx grImps wAqf zhO bUck'.
2014
2015 Unlike backreferences, there is no speed penalty for using match
2016 references, other than the extra substitutions required for the
2017 replacement strings in cases such as the example shown.
2018
2019 M Deactivate the m flag, hence no references to match data will be
2020 created.
2021
2022 anum Approximate matching: num errors are allowed in the string
2023 matched by the pattern. The rules for this are described in the
2024 next subsection.
2025
2026 s, e Unlike the other flags, these have only a local effect, and each
2027 must appear on its own: `(#s)' and `(#e)' are the only valid
2028 forms. The `(#s)' flag succeeds only at the start of the test
2029 string, and the `(#e)' flag succeeds only at the end of the test
2030 string; they correspond to `^' and `$' in standard regular
2031 expressions. They are useful for matching path segments in pat‐
2032 terns other than those in filename generation (where path seg‐
2033 ments are in any case treated separately). For example,
2034 `*((#s)|/)test((#e)|/)*' matches a path segment `test' in any of
2035 the following strings: test, test/at/start, at/end/test,
2036 in/test/middle.
2037
2038 Another use is in parameter substitution; for example
2039 `${array/(#s)A*Z(#e)}' will remove only elements of an array
2040 which match the complete pattern `A*Z'. There are other ways of
2041 performing many operations of this type, however the combination
2042 of the substitution operations `/' and `//' with the `(#s)' and
2043 `(#e)' flags provides a single simple and memorable method.
2044
2045 Note that assertions of the form `(^(#s))' also work, i.e. match
2046 anywhere except at the start of the string, although this actu‐
2047 ally means `anything except a zero-length portion at the start
2048 of the string'; you need to use `(""~(#s))' to match a
2049 zero-length portion of the string not at the start.
2050
2051 q A `q' and everything up to the closing parenthesis of the glob‐
2052 bing flags are ignored by the pattern matching code. This is
2053 intended to support the use of glob qualifiers, see below. The
2054 result is that the pattern `(#b)(*).c(#q.)' can be used both for
2055 globbing and for matching against a string. In the former case,
2056 the `(#q.)' will be treated as a glob qualifier and the `(#b)'
2057 will not be useful, while in the latter case the `(#b)' is use‐
2058 ful for backreferences and the `(#q.)' will be ignored. Note
2059 that colon modifiers in the glob qualifiers are also not applied
2060 in ordinary pattern matching.
2061
2062 u Respect the current locale in determining the presence of multi‐
2063 byte characters in a pattern, provided the shell was compiled
2064 with MULTIBYTE_SUPPORT. This overrides the MULTIBYTE option;
2065 the default behaviour is taken from the option. Compare U.
2066 (Mnemonic: typically multibyte characters are from Unicode in
2067 the UTF-8 encoding, although any extension of ASCII supported by
2068 the system library may be used.)
2069
2070 U All characters are considered to be a single byte long. The
2071 opposite of u. This overrides the MULTIBYTE option.
2072
2073 For example, the test string fooxx can be matched by the pattern
2074 (#i)FOOXX, but not by (#l)FOOXX, (#i)FOO(#I)XX or ((#i)FOOX)X. The
2075 string (#ia2)readme specifies case-insensitive matching of readme with
2076 up to two errors.
2077
2078 When using the ksh syntax for grouping both KSH_GLOB and EXTENDED_GLOB
2079 must be set and the left parenthesis should be preceded by @. Note
2080 also that the flags do not affect letters inside [...] groups, in other
2081 words (#i)[a-z] still matches only lowercase letters. Finally, note
2082 that when examining whole paths case-insensitively every directory must
2083 be searched for all files which match, so that a pattern of the form
2084 (#i)/foo/bar/... is potentially slow.
2085
2086 Approximate Matching
2087 When matching approximately, the shell keeps a count of the errors
2088 found, which cannot exceed the number specified in the (#anum) flags.
2089 Four types of error are recognised:
2090
2091 1. Different characters, as in fooxbar and fooybar.
2092
2093 2. Transposition of characters, as in banana and abnana.
2094
2095 3. A character missing in the target string, as with the pattern
2096 road and target string rod.
2097
2098 4. An extra character appearing in the target string, as with stove
2099 and strove.
2100
2101 Thus, the pattern (#a3)abcd matches dcba, with the errors occurring by
2102 using the first rule twice and the second once, grouping the string as
2103 [d][cb][a] and [a][bc][d].
2104
2105 Non-literal parts of the pattern must match exactly, including charac‐
2106 ters in character ranges: hence (#a1)??? matches strings of length
2107 four, by applying rule 4 to an empty part of the pattern, but not
2108 strings of length two, since all the ? must match. Other characters
2109 which must match exactly are initial dots in filenames (unless the
2110 GLOB_DOTS option is set), and all slashes in filenames, so that a/bc is
2111 two errors from ab/c (the slash cannot be transposed with another char‐
2112 acter). Similarly, errors are counted separately for non-contiguous
2113 strings in the pattern, so that (ab|cd)ef is two errors from aebf.
2114
2115 When using exclusion via the ~ operator, approximate matching is
2116 treated entirely separately for the excluded part and must be activated
2117 separately. Thus, (#a1)README~READ_ME matches READ.ME but not READ_ME,
2118 as the trailing READ_ME is matched without approximation. However,
2119 (#a1)README~(#a1)READ_ME does not match any pattern of the form READ?ME
2120 as all such forms are now excluded.
2121
2122 Apart from exclusions, there is only one overall error count; however,
2123 the maximum errors allowed may be altered locally, and this can be
2124 delimited by grouping. For example, (#a1)cat((#a0)dog)fox allows one
2125 error in total, which may not occur in the dog section, and the pattern
2126 (#a1)cat(#a0)dog(#a1)fox is equivalent. Note that the point at which
2127 an error is first found is the crucial one for establishing whether to
2128 use approximation; for example, (#a1)abc(#a0)xyz will not match
2129 abcdxyz, because the error occurs at the `x', where approximation is
2130 turned off.
2131
2132 Entire path segments may be matched approximately, so that
2133 `(#a1)/foo/d/is/available/at/the/bar' allows one error in any path seg‐
2134 ment. This is much less efficient than without the (#a1), however,
2135 since every directory in the path must be scanned for a possible
2136 approximate match. It is best to place the (#a1) after any path seg‐
2137 ments which are known to be correct.
2138
2139 Recursive Globbing
2140 A pathname component of the form `(foo/)#' matches a path consisting of
2141 zero or more directories matching the pattern foo.
2142
2143 As a shorthand, `**/' is equivalent to `(*/)#'; note that this there‐
2144 fore matches files in the current directory as well as subdirectories.
2145 Thus:
2146
2147 ls (*/)#bar
2148
2149 or
2150
2151 ls **/bar
2152
2153 does a recursive directory search for files named `bar' (potentially
2154 including the file `bar' in the current directory). This form does not
2155 follow symbolic links; the alternative form `***/' does, but is other‐
2156 wise identical. Neither of these can be combined with other forms of
2157 globbing within the same path segment; in that case, the `*' operators
2158 revert to their usual effect.
2159
2160 Even shorter forms are available when the option GLOB_STAR_SHORT is
2161 set. In that case if no / immediately follows a ** or *** they are
2162 treated as if both a / plus a further * are present. Hence:
2163
2164 setopt GLOBSTARSHORT
2165 ls **.c
2166
2167 is equivalent to
2168
2169 ls **/*.c
2170
2171 Glob Qualifiers
2172 Patterns used for filename generation may end in a list of qualifiers
2173 enclosed in parentheses. The qualifiers specify which filenames that
2174 otherwise match the given pattern will be inserted in the argument
2175 list.
2176
2177 If the option BARE_GLOB_QUAL is set, then a trailing set of parentheses
2178 containing no `|' or `(' characters (or `~' if it is special) is taken
2179 as a set of glob qualifiers. A glob subexpression that would normally
2180 be taken as glob qualifiers, for example `(^x)', can be forced to be
2181 treated as part of the glob pattern by doubling the parentheses, in
2182 this case producing `((^x))'.
2183
2184 If the option EXTENDED_GLOB is set, a different syntax for glob quali‐
2185 fiers is available, namely `(#qx)' where x is any of the same glob
2186 qualifiers used in the other format. The qualifiers must still appear
2187 at the end of the pattern. However, with this syntax multiple glob
2188 qualifiers may be chained together. They are treated as a logical AND
2189 of the individual sets of flags. Also, as the syntax is unambiguous,
2190 the expression will be treated as glob qualifiers just as long any
2191 parentheses contained within it are balanced; appearance of `|', `(' or
2192 `~' does not negate the effect. Note that qualifiers will be recog‐
2193 nised in this form even if a bare glob qualifier exists at the end of
2194 the pattern, for example `*(#q*)(.)' will recognise executable regular
2195 files if both options are set; however, mixed syntax should probably be
2196 avoided for the sake of clarity. Note that within conditions using the
2197 `[[' form the presence of a parenthesised expression (#q...) at the end
2198 of a string indicates that globbing should be performed; the expression
2199 may include glob qualifiers, but it is also valid if it is simply (#q).
2200 This does not apply to the right hand side of pattern match operators
2201 as the syntax already has special significance.
2202
2203 A qualifier may be any one of the following:
2204
2205 / directories
2206
2207 F `full' (i.e. non-empty) directories. Note that the opposite
2208 sense (^F) expands to empty directories and all non-directories.
2209 Use (/^F) for empty directories.
2210
2211 . plain files
2212
2213 @ symbolic links
2214
2215 = sockets
2216
2217 p named pipes (FIFOs)
2218
2219 * executable plain files (0100 or 0010 or 0001)
2220
2221 % device files (character or block special)
2222
2223 %b block special files
2224
2225 %c character special files
2226
2227 r owner-readable files (0400)
2228
2229 w owner-writable files (0200)
2230
2231 x owner-executable files (0100)
2232
2233 A group-readable files (0040)
2234
2235 I group-writable files (0020)
2236
2237 E group-executable files (0010)
2238
2239 R world-readable files (0004)
2240
2241 W world-writable files (0002)
2242
2243 X world-executable files (0001)
2244
2245 s setuid files (04000)
2246
2247 S setgid files (02000)
2248
2249 t files with the sticky bit (01000)
2250
2251 fspec files with access rights matching spec. This spec may be a octal
2252 number optionally preceded by a `=', a `+', or a `-'. If none of
2253 these characters is given, the behavior is the same as for `='.
2254 The octal number describes the mode bits to be expected, if com‐
2255 bined with a `=', the value given must match the file-modes
2256 exactly, with a `+', at least the bits in the given number must
2257 be set in the file-modes, and with a `-', the bits in the number
2258 must not be set. Giving a `?' instead of a octal digit anywhere
2259 in the number ensures that the corresponding bits in the
2260 file-modes are not checked, this is only useful in combination
2261 with `='.
2262
2263 If the qualifier `f' is followed by any other character anything
2264 up to the next matching character (`[', `{', and `<' match `]',
2265 `}', and `>' respectively, any other character matches itself)
2266 is taken as a list of comma-separated sub-specs. Each sub-spec
2267 may be either an octal number as described above or a list of
2268 any of the characters `u', `g', `o', and `a', followed by a `=',
2269 a `+', or a `-', followed by a list of any of the characters
2270 `r', `w', `x', `s', and `t', or an octal digit. The first list
2271 of characters specify which access rights are to be checked. If
2272 a `u' is given, those for the owner of the file are used, if a
2273 `g' is given, those of the group are checked, a `o' means to
2274 test those of other users, and the `a' says to test all three
2275 groups. The `=', `+', and `-' again says how the modes are to be
2276 checked and have the same meaning as described for the first
2277 form above. The second list of characters finally says which
2278 access rights are to be expected: `r' for read access, `w' for
2279 write access, `x' for the right to execute the file (or to
2280 search a directory), `s' for the setuid and setgid bits, and `t'
2281 for the sticky bit.
2282
2283 Thus, `*(f70?)' gives the files for which the owner has read,
2284 write, and execute permission, and for which other group members
2285 have no rights, independent of the permissions for other users.
2286 The pattern `*(f-100)' gives all files for which the owner does
2287 not have execute permission, and `*(f:gu+w,o-rx:)' gives the
2288 files for which the owner and the other members of the group
2289 have at least write permission, and for which other users don't
2290 have read or execute permission.
2291
2292 estring
2293 +cmd The string will be executed as shell code. The filename will be
2294 included in the list if and only if the code returns a zero sta‐
2295 tus (usually the status of the last command).
2296
2297 In the first form, the first character after the `e' will be
2298 used as a separator and anything up to the next matching separa‐
2299 tor will be taken as the string; `[', `{', and `<' match `]',
2300 `}', and `>', respectively, while any other character matches
2301 itself. Note that expansions must be quoted in the string to
2302 prevent them from being expanded before globbing is done.
2303 string is then executed as shell code. The string globqual is
2304 appended to the array zsh_eval_context the duration of execu‐
2305 tion.
2306
2307 During the execution of string the filename currently being
2308 tested is available in the parameter REPLY; the parameter may be
2309 altered to a string to be inserted into the list instead of the
2310 original filename. In addition, the parameter reply may be set
2311 to an array or a string, which overrides the value of REPLY. If
2312 set to an array, the latter is inserted into the command line
2313 word by word.
2314
2315 For example, suppose a directory contains a single file
2316 `lonely'. Then the expression `*(e:'reply=(${REPLY}{1,2})':)'
2317 will cause the words `lonely1' and `lonely2' to be inserted into
2318 the command line. Note the quoting of string.
2319
2320 The form +cmd has the same effect, but no delimiters appear
2321 around cmd. Instead, cmd is taken as the longest sequence of
2322 characters following the + that are alphanumeric or underscore.
2323 Typically cmd will be the name of a shell function that contains
2324 the appropriate test. For example,
2325
2326 nt() { [[ $REPLY -nt $NTREF ]] }
2327 NTREF=reffile
2328 ls -l *(+nt)
2329
2330 lists all files in the directory that have been modified more
2331 recently than reffile.
2332
2333 ddev files on the device dev
2334
2335 l[-|+]ct
2336 files having a link count less than ct (-), greater than ct (+),
2337 or equal to ct
2338
2339 U files owned by the effective user ID
2340
2341 G files owned by the effective group ID
2342
2343 uid files owned by user ID id if that is a number. Otherwise, id
2344 specifies a user name: the character after the `u' will be taken
2345 as a separator and the string between it and the next matching
2346 separator will be taken as a user name. The starting separators
2347 `[', `{', and `<' match the final separators `]', `}', and `>',
2348 respectively; any other character matches itself. The selected
2349 files are those owned by this user. For example, `u:foo:' or
2350 `u[foo]' selects files owned by user `foo'.
2351
2352 gid like uid but with group IDs or names
2353
2354 a[Mwhms][-|+]n
2355 files accessed exactly n days ago. Files accessed within the
2356 last n days are selected using a negative value for n (-n).
2357 Files accessed more than n days ago are selected by a positive n
2358 value (+n). Optional unit specifiers `M', `w', `h', `m' or `s'
2359 (e.g. `ah5') cause the check to be performed with months (of 30
2360 days), weeks, hours, minutes or seconds instead of days, respec‐
2361 tively. An explicit `d' for days is also allowed.
2362
2363 Any fractional part of the difference between the access time
2364 and the current part in the appropriate units is ignored in the
2365 comparison. For instance, `echo *(ah-5)' would echo files
2366 accessed within the last five hours, while `echo *(ah+5)' would
2367 echo files accessed at least six hours ago, as times strictly
2368 between five and six hours are treated as five hours.
2369
2370 m[Mwhms][-|+]n
2371 like the file access qualifier, except that it uses the file
2372 modification time.
2373
2374 c[Mwhms][-|+]n
2375 like the file access qualifier, except that it uses the file
2376 inode change time.
2377
2378 L[+|-]n
2379 files less than n bytes (-), more than n bytes (+), or exactly n
2380 bytes in length.
2381
2382 If this flag is directly followed by a size specifier `k' (`K'),
2383 `m' (`M'), or `p' (`P') (e.g. `Lk-50') the check is performed
2384 with kilobytes, megabytes, or blocks (of 512 bytes) instead.
2385 (On some systems additional specifiers are available for giga‐
2386 bytes, `g' or `G', and terabytes, `t' or `T'.) If a size speci‐
2387 fier is used a file is regarded as "exactly" the size if the
2388 file size rounded up to the next unit is equal to the test size.
2389 Hence `*(Lm1)' matches files from 1 byte up to 1 Megabyte inclu‐
2390 sive. Note also that the set of files "less than" the test size
2391 only includes files that would not match the equality test;
2392 hence `*(Lm-1)' only matches files of zero size.
2393
2394 ^ negates all qualifiers following it
2395
2396 - toggles between making the qualifiers work on symbolic links
2397 (the default) and the files they point to
2398
2399 M sets the MARK_DIRS option for the current pattern
2400
2401 T appends a trailing qualifier mark to the filenames, analogous to
2402 the LIST_TYPES option, for the current pattern (overrides M)
2403
2404 N sets the NULL_GLOB option for the current pattern
2405
2406 D sets the GLOB_DOTS option for the current pattern
2407
2408 n sets the NUMERIC_GLOB_SORT option for the current pattern
2409
2410 Yn enables short-circuit mode: the pattern will expand to at most n
2411 filenames. If more than n matches exist, only the first n
2412 matches in directory traversal order will be considered.
2413
2414 Implies oN when no oc qualifier is used.
2415
2416 oc specifies how the names of the files should be sorted. If c is n
2417 they are sorted by name; if it is L they are sorted depending on
2418 the size (length) of the files; if l they are sorted by the num‐
2419 ber of links; if a, m, or c they are sorted by the time of the
2420 last access, modification, or inode change respectively; if d,
2421 files in subdirectories appear before those in the current
2422 directory at each level of the search -- this is best combined
2423 with other criteria, for example `odon' to sort on names for
2424 files within the same directory; if N, no sorting is performed.
2425 Note that a, m, and c compare the age against the current time,
2426 hence the first name in the list is the youngest file. Also note
2427 that the modifiers ^ and - are used, so `*(^-oL)' gives a list
2428 of all files sorted by file size in descending order, following
2429 any symbolic links. Unless oN is used, multiple order speci‐
2430 fiers may occur to resolve ties.
2431
2432 The default sorting is n (by name) unless the Y glob qualifier
2433 is used, in which case it is N (unsorted).
2434
2435 oe and o+ are special cases; they are each followed by shell
2436 code, delimited as for the e glob qualifier and the + glob qual‐
2437 ifier respectively (see above). The code is executed for each
2438 matched file with the parameter REPLY set to the name of the
2439 file on entry and globsort appended to zsh_eval_context. The
2440 code should modify the parameter REPLY in some fashion. On
2441 return, the value of the parameter is used instead of the file
2442 name as the string on which to sort. Unlike other sort opera‐
2443 tors, oe and o+ may be repeated, but note that the maximum num‐
2444 ber of sort operators of any kind that may appear in any glob
2445 expression is 12.
2446
2447 Oc like `o', but sorts in descending order; i.e. `*(^oc)' is the
2448 same as `*(Oc)' and `*(^Oc)' is the same as `*(oc)'; `Od' puts
2449 files in the current directory before those in subdirectories at
2450 each level of the search.
2451
2452 [beg[,end]]
2453 specifies which of the matched filenames should be included in
2454 the returned list. The syntax is the same as for array sub‐
2455 scripts. beg and the optional end may be mathematical expres‐
2456 sions. As in parameter subscripting they may be negative to make
2457 them count from the last match backward. E.g.: `*(-OL[1,3])'
2458 gives a list of the names of the three largest files.
2459
2460 Pstring
2461 The string will be prepended to each glob match as a separate
2462 word. string is delimited in the same way as arguments to the e
2463 glob qualifier described above. The qualifier can be repeated;
2464 the words are prepended separately so that the resulting command
2465 line contains the words in the same order they were given in the
2466 list of glob qualifiers.
2467
2468 A typical use for this is to prepend an option before all occur‐
2469 rences of a file name; for example, the pattern `*(P:-f:)' pro‐
2470 duces the command line arguments `-f file1 -f file2 ...'
2471
2472 If the modifier ^ is active, then string will be appended
2473 instead of prepended. Prepending and appending is done indepen‐
2474 dently so both can be used on the same glob expression; for
2475 example by writing `*(P:foo:^P:bar:^P:baz:)' which produces the
2476 command line arguments `foo baz file1 bar ...'
2477
2478 More than one of these lists can be combined, separated by commas. The
2479 whole list matches if at least one of the sublists matches (they are
2480 `or'ed, the qualifiers in the sublists are `and'ed). Some qualifiers,
2481 however, affect all matches generated, independent of the sublist in
2482 which they are given. These are the qualifiers `M', `T', `N', `D',
2483 `n', `o', `O' and the subscripts given in brackets (`[...]').
2484
2485 If a `:' appears in a qualifier list, the remainder of the expression
2486 in parenthesis is interpreted as a modifier (see the section `Modi‐
2487 fiers' in the section `History Expansion'). Each modifier must be
2488 introduced by a separate `:'. Note also that the result after modifi‐
2489 cation does not have to be an existing file. The name of any existing
2490 file can be followed by a modifier of the form `(:...)' even if no
2491 actual filename generation is performed, although note that the pres‐
2492 ence of the parentheses causes the entire expression to be subjected to
2493 any global pattern matching options such as NULL_GLOB. Thus:
2494
2495 ls *(-/)
2496
2497 lists all directories and symbolic links that point to directories, and
2498
2499 ls *(-@)
2500
2501 lists all broken symbolic links, and
2502
2503 ls *(%W)
2504
2505 lists all world-writable device files in the current directory, and
2506
2507 ls *(W,X)
2508
2509 lists all files in the current directory that are world-writable or
2510 world-executable, and
2511
2512 echo /tmp/foo*(u0^@:t)
2513
2514 outputs the basename of all root-owned files beginning with the string
2515 `foo' in /tmp, ignoring symlinks, and
2516
2517 ls *.*~(lex|parse).[ch](^D^l1)
2518
2519 lists all files having a link count of one whose names contain a dot
2520 (but not those starting with a dot, since GLOB_DOTS is explicitly
2521 switched off) except for lex.c, lex.h, parse.c and parse.h.
2522
2523 print b*.pro(#q:s/pro/shmo/)(#q.:s/builtin/shmiltin/)
2524
2525 demonstrates how colon modifiers and other qualifiers may be chained
2526 together. The ordinary qualifier `.' is applied first, then the colon
2527 modifiers in order from left to right. So if EXTENDED_GLOB is set and
2528 the base pattern matches the regular file builtin.pro, the shell will
2529 print `shmiltin.shmo'.
2530
2531
2532
2533zsh 5.7.1 February 3, 2019 ZSHEXPN(1)