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