1ZSHEXPN(1)                  General Commands Manual                 ZSHEXPN(1)
2
3
4

NAME

6       zshexpn - zsh expansion and substitution
7

DESCRIPTION

9       The  following types of expansions are performed in the indicated order
10       in five steps:
11
12       History Expansion
13              This is performed only in interactive shells.
14
15       Alias Expansion
16              Aliases are expanded immediately  before  the  command  line  is
17              parsed as explained under Aliasing in zshmisc(1).
18
19       Process Substitution
20       Parameter Expansion
21       Command Substitution
22       Arithmetic Expansion
23       Brace Expansion
24              These  five are performed in left-to-right fashion.  On each ar‐
25              gument, any of the five steps that are needed are performed  one
26              after the other.  Hence, for example, all the parts of parameter
27              expansion are completed before command substitution is  started.
28              After  these expansions, all unquoted occurrences of the charac‐
29              ters `\',`'' and `"' are removed.
30
31       Filename Expansion
32              If the SH_FILE_EXPANSION option is set, the order  of  expansion
33              is  modified  for  compatibility  with sh and ksh.  In that case
34              filename expansion is performed immediately after  alias  expan‐
35              sion, preceding the set of five expansions mentioned above.
36
37       Filename Generation
38              This expansion, commonly referred to as globbing, is always done
39              last.
40
41       The following sections explain the types of expansion in detail.
42

HISTORY EXPANSION

44       History expansion allows you to use words from previous  command  lines
45       in  the  command line you are typing.  This simplifies spelling correc‐
46       tions and the repetition of complicated commands or arguments.
47
48       Immediately before execution, each command  is  saved  in  the  history
49       list,  the  size of which is controlled by the HISTSIZE parameter.  The
50       one most recent command is always retained in  any  case.   Each  saved
51       command in the history list is called a history event and is assigned a
52       number, beginning with 1 (one) when the shell starts up.   The  history
53       number  that  you  may  see in your prompt (see EXPANSION OF PROMPT SE‐
54       QUENCES in zshmisc(1)) is the number that is to be assigned to the next
55       command.
56
57   Overview
58       A  history  expansion  begins with the first character of the histchars
59       parameter, which is `!' by default, and may occur anywhere on the  com‐
60       mand line, including inside double quotes (but not inside single quotes
61       '...' or C-style quotes $'...' nor when escaped with a backslash).
62
63       The first character is followed by an optional  event  designator  (see
64       the  section  `Event Designators') and then an optional word designator
65       (the section `Word Designators'); if neither of  these  designators  is
66       present, no history expansion occurs.
67
68       Input  lines  containing  history expansions are echoed after being ex‐
69       panded, but before any other expansions take place and before the  com‐
70       mand  is  executed.   It  is this expanded form that is recorded as the
71       history event for later references.
72
73       History expansions do not nest.
74
75       By default, a history reference with no event designator refers to  the
76       same  event as any preceding history reference on that command line; if
77       it is the only history reference in a command, it refers to the  previ‐
78       ous  command.   However,  if the option CSH_JUNKIE_HISTORY is set, then
79       every history reference with no event specification  always  refers  to
80       the previous command.
81
82       For  example,  `!' is the event designator for the previous command, so
83       `!!:1' always refers to the first word of  the  previous  command,  and
84       `!!$'  always  refers  to  the last word of the previous command.  With
85       CSH_JUNKIE_HISTORY set, then `!:1' and `!$' function in the same manner
86       as  `!!:1'  and `!!$', respectively.  Conversely, if CSH_JUNKIE_HISTORY
87       is unset, then `!:1' and `!$' refer to the first and  last  words,  re‐
88       spectively,  of  the same event referenced by the nearest other history
89       reference preceding them on the current command line, or to the  previ‐
90       ous command if there is no preceding reference.
91
92       The  character  sequence  `^foo^bar'  (where `^' is actually the second
93       character of the histchars parameter) repeats the last command, replac‐
94       ing  the string foo with bar.  More precisely, the sequence `^foo^bar^'
95       is synonymous with `!!:s^foo^bar^', hence other modifiers (see the sec‐
96       tion   `Modifiers')   may   follow   the  final  `^'.   In  particular,
97       `^foo^bar^:G' performs a global substitution.
98
99       If the shell encounters the character sequence `!"' in the  input,  the
100       history  mechanism  is temporarily disabled until the current list (see
101       zshmisc(1)) is fully parsed.  The `!"' is removed from the  input,  and
102       any subsequent `!' characters have no special significance.
103
104       A  less convenient but more comprehensible form of command history sup‐
105       port is provided by the fc builtin.
106
107   Event Designators
108       An event designator is a reference to a command-line entry in the  his‐
109       tory  list.   In  the list below, remember that the initial `!' in each
110       item may be changed to another character by setting the  histchars  pa‐
111       rameter.
112
113       !      Start a history expansion, except when followed by a blank, new‐
114              line, `=' or `('.  If followed immediately by a word  designator
115              (see  the section `Word Designators'), this forms a history ref‐
116              erence with no event designator (see the section `Overview').
117
118       !!     Refer to the previous command.  By itself,  this  expansion  re‐
119              peats the previous command.
120
121       !n     Refer to command-line n.
122
123       !-n    Refer to the current command-line minus n.
124
125       !str   Refer to the most recent command starting with str.
126
127       !?str[?]
128              Refer  to  the most recent command containing str.  The trailing
129              `?' is necessary if this reference is to be followed by a  modi‐
130              fier  or  followed by any text that is not to be considered part
131              of str.
132
133       !#     Refer to the current command line typed in so far.  The line  is
134              treated  as if it were complete up to and including the word be‐
135              fore the one with the `!#' reference.
136
137       !{...} Insulate a history reference from adjacent characters (if neces‐
138              sary).
139
140   Word Designators
141       A word designator indicates which word or words of a given command line
142       are to be included in a history reference.  A `:' usually separates the
143       event  specification  from the word designator.  It may be omitted only
144       if the word designator begins with a `^', `$', `*', `-' or  `%'.   Word
145       designators include:
146
147       0      The first input word (command).
148       n      The nth argument.
149       ^      The first argument.  That is, 1.
150       $      The last argument.
151       %      The word matched by (the most recent) ?str search.
152       x-y    A range of words; x defaults to 0.
153       *      All the arguments, or a null value if there are none.
154       x*     Abbreviates `x-$'.
155       x-     Like `x*' but omitting word $.
156
157       Note  that  a  `%' word designator works only when used in one of `!%',
158       `!:%' or `!?str?:%', and only when used after a !? expansion  (possibly
159       in  an  earlier  command).  Anything else results in an error, although
160       the error may not be the most obvious one.
161
162   Modifiers
163       After the optional word designator, you can add a sequence  of  one  or
164       more  of  the following modifiers, each preceded by a `:'.  These modi‐
165       fiers also work on the result of filename generation and parameter  ex‐
166       pansion, except where noted.
167
168       a      Turn  a  file  name into an absolute path:  prepends the current
169              directory, if necessary; remove `.' path  segments;  and  remove
170              `..'  path  segments  and  the segments that immediately precede
171              them.
172
173              This transformation is agnostic about what is in the filesystem,
174              i.e.  is  on  the logical, not the physical directory.  It takes
175              place in the same manner as when changing directories when  nei‐
176              ther of the options CHASE_DOTS or CHASE_LINKS is set.  For exam‐
177              ple, `/before/here/../after'  is  always  transformed  to  `/be‐
178              fore/after', regardless of whether `/before/here' exists or what
179              kind of object (dir, file, symlink, etc.) it is.
180
181       A      Turn a file name into an absolute path as the `a' modifier does,
182              and  then  pass the result through the realpath(3) library func‐
183              tion to resolve symbolic links.
184
185              Note: on systems that do not have a  realpath(3)  library  func‐
186              tion,  symbolic  links are not resolved, so on those systems `a'
187              and `A' are equivalent.
188
189              Note: foo:A and realpath(foo) are different on some inputs.  For
190              realpath(foo) semantics, see the `P` modifier.
191
192       c      Resolve  a  command  name into an absolute path by searching the
193              command path given by the PATH variable.  This does not work for
194              commands  containing  directory parts.  Note also that this does
195              not usually work as a glob qualifier unless a file of  the  same
196              name is found in the current directory.
197
198       e      Remove  all but the part of the filename extension following the
199              `.'; see the definition of the filename  extension  in  the  de‐
200              scription  of the r modifier below.  Note that according to that
201              definition the result will be empty if the string  ends  with  a
202              `.'.
203
204       h [ digits ]
205              Remove a trailing pathname component, shortening the path by one
206              directory level: this is the `head' of the pathname.  This works
207              like  `dirname'.  If the h is followed immediately (with no spa‐
208              ces or other separator) by any number of decimal digits, and the
209              value  of the resulting number is non-zero, that number of lead‐
210              ing components is preserved instead of the final component being
211              removed.   In an absolute path the leading `/' is the first com‐
212              ponent, so,  for  example,  if  var=/my/path/to/something,  then
213              ${var:h3}  substitutes  /my/path.   Consecutive `/'s are treated
214              the same as a single `/'.  In parameter substitution, digits may
215              only  be used if the expression is in braces, so for example the
216              short form substitution $var:h2 is treated as ${var:h}2, not  as
217              ${var:h2}.   No restriction applies to the use of digits in his‐
218              tory substitution or globbing qualifiers.   If  more  components
219              are  requested  than are present, the entire path is substituted
220              (so this does not trigger a `failed modifier' error  in  history
221              expansion).
222
223       l      Convert the words to all lowercase.
224
225       p      Print  the  new  command but do not execute it.  Only works with
226              history expansion.
227
228       P      Turn a file name into an absolute path, like  realpath(3).   The
229              resulting  path will be absolute, have neither `.' nor `..' com‐
230              ponents, and refer to the same  directory  entry  as  the  input
231              filename.
232
233              Unlike realpath(3), non-existent trailing components are permit‐
234              ted and preserved.
235
236       q      Quote the substituted  words,  escaping  further  substitutions.
237              Works with history expansion and parameter expansion, though for
238              parameters it is only useful if the  resulting  text  is  to  be
239              re-evaluated such as by eval.
240
241       Q      Remove one level of quotes from the substituted words.
242
243       r      Remove a filename extension leaving the root name.  Strings with
244              no filename extension are not altered.  A filename extension  is
245              a `.' followed by any number of characters (including zero) that
246              are neither `.' nor `/' and that continue  to  the  end  of  the
247              string.  For example, the extension of `foo.orig.c' is `.c', and
248              `dir.c/foo' has no extension.
249
250       s/l/r[/]
251              Substitute r for l as described below.  The substitution is done
252              only  for  the  first string that matches l.  For arrays and for
253              filename generation, this applies to each word of  the  expanded
254              text.  See below for further notes on substitutions.
255
256              The  forms  `gs/l/r' and `s/l/r/:G' perform global substitution,
257              i.e. substitute every occurrence of r for l.  Note that the g or
258              :G must appear in exactly the position shown.
259
260              See further notes on this form of substitution below.
261
262       &      Repeat the previous s substitution.  Like s, may be preceded im‐
263              mediately by a g.  In parameter expansion the & must appear  in‐
264              side braces, and in filename generation it must be quoted with a
265              backslash.
266
267       t [ digits ]
268              Remove all leading pathname components, leaving the final compo‐
269              nent  (tail).  This works like `basename'.  Any trailing slashes
270              are first removed.  Decimal  digits  are  handled  as  described
271              above  for  (h), but in this case that number of trailing compo‐
272              nents is preserved instead of the default 1; 0  is  treated  the
273              same as 1.
274
275       u      Convert the words to all uppercase.
276
277       x      Like  q, but break into words at whitespace.  Does not work with
278              parameter expansion.
279
280       The s/l/r/ substitution works as follows.   By  default  the  left-hand
281       side  of  substitutions  are  not patterns, but character strings.  Any
282       character can be used as the delimiter in place of  `/'.   A  backslash
283       quotes   the   delimiter   character.    The   character  `&',  in  the
284       right-hand-side r, is replaced by the text from the  left-hand-side  l.
285       The  `&'  can  be  quoted with a backslash.  A null l uses the previous
286       string either from the previous l or from the contextual scan string  s
287       from  `!?s'.  You can omit the rightmost delimiter if a newline immedi‐
288       ately follows r; the rightmost `?' in a context scan can  similarly  be
289       omitted.  Note the same record of the last l and r is maintained across
290       all forms of expansion.
291
292       Note that if a `&' is used within glob qualifiers an extra backslash is
293       needed as a & is a special character in this case.
294
295       Also  note that the order of expansions affects the interpretation of l
296       and r.  When used in a history expansion, which occurs before any other
297       expansions, l and r are treated as literal strings (except as explained
298       for HIST_SUBST_PATTERN below).  When used in parameter  expansion,  the
299       replacement of r into the parameter's value is done first, and then any
300       additional process, parameter, command, arithmetic, or brace references
301       are applied, which may evaluate those substitutions and expansions more
302       than once if l appears more than once in the starting value.  When used
303       in a glob qualifier, any substitutions or expansions are performed once
304       at the time the qualifier is parsed, even before  the  `:s'  expression
305       itself is divided into l and r sides.
306
307       If  the  option HIST_SUBST_PATTERN is set, l is treated as a pattern of
308       the usual form described in  the  section  FILENAME  GENERATION  below.
309       This can be used in all the places where modifiers are available; note,
310       however, that in globbing qualifiers parameter substitution has already
311       taken  place,  so parameters in the replacement string should be quoted
312       to ensure they are replaced at the correct time.  Note also  that  com‐
313       plicated  patterns  used  in  globbing qualifiers may need the extended
314       glob qualifier notation (#q:s/.../.../) in order for the shell to  rec‐
315       ognize the expression as a glob qualifier.  Further, note that bad pat‐
316       terns in the substitution are not subject to the NO_BAD_PATTERN  option
317       so will cause an error.
318
319       When  HIST_SUBST_PATTERN  is set, l may start with a # to indicate that
320       the pattern must match at the start of the string  to  be  substituted,
321       and a % may appear at the start or after an # to indicate that the pat‐
322       tern must match at the end of the string to be substituted.  The % or #
323       may be quoted with two backslashes.
324
325       For  example,  the following piece of filename generation code with the
326       EXTENDED_GLOB option:
327
328              print -r -- *.c(#q:s/#%(#b)s(*).c/'S${match[1]}.C'/)
329
330       takes the expansion of *.c and  applies  the  glob  qualifiers  in  the
331       (#q...)  expression, which consists of a substitution modifier anchored
332       to the start and end of each word (#%).  This turns  on  backreferences
333       ((#b)), so that the parenthesised subexpression is available in the re‐
334       placement string as ${match[1]}.  The replacement string is  quoted  so
335       that the parameter is not substituted before the start of filename gen‐
336       eration.
337
338       The following f, F, w and W modifiers work only with  parameter  expan‐
339       sion and filename generation.  They are listed here to provide a single
340       point of reference for all modifiers.
341
342       f      Repeats the immediately (without a colon) following modifier un‐
343              til the resulting word doesn't change any more.
344
345       F:expr:
346              Like  f,  but repeats only n times if the expression expr evalu‐
347              ates to n.  Any character can be used instead  of  the  `:';  if
348              `(',  `[',  or `{' is used as the opening delimiter, the closing
349              delimiter should be ')', `]', or `}', respectively.
350
351       w      Makes the immediately following modifier work on  each  word  in
352              the string.
353
354       W:sep: Like  w  but  words are considered to be the parts of the string
355              that are separated by sep. Any character can be used instead  of
356              the `:'; opening parentheses are handled specially, see above.
357

PROCESS SUBSTITUTION

359       Each  part  of  a  command  argument  that  takes  the  form `<(list)',
360       `>(list)' or `=(list)' is subject to process substitution.  The expres‐
361       sion  may be preceded or followed by other strings except that, to pre‐
362       vent clashes with commonly occurring strings  and  patterns,  the  last
363       form  must  occur at the start of a command argument, and the forms are
364       only expanded when  first  parsing  command  or  assignment  arguments.
365       Process  substitutions  may be used following redirection operators; in
366       this case, the substitution must appear with no trailing string.
367
368       Note that `<<(list)' is not a special syntax; it is  equivalent  to  `<
369       <(list)', redirecting standard input from the result of process substi‐
370       tution.  Hence all the following  documentation  applies.   The  second
371       form (with the space) is recommended for clarity.
372
373       In the case of the < or > forms, the shell runs the commands in list as
374       a subprocess of the job executing the shell command line.  If the  sys‐
375       tem supports the /dev/fd mechanism, the command argument is the name of
376       the device file corresponding to a file descriptor; otherwise,  if  the
377       system  supports  named  pipes  (FIFOs), the command argument will be a
378       named pipe.  If the form with > is selected then writing on  this  spe‐
379       cial  file  will  provide  input for list.  If < is used, then the file
380       passed as an argument will be connected  to  the  output  of  the  list
381       process.  For example,
382
383              paste <(cut -f1 file1) <(cut -f3 file2) |
384              tee >(process1) >(process2) >/dev/null
385
386       cuts fields 1 and 3 from the files file1 and file2 respectively, pastes
387       the results together, and  sends  it  to  the  processes  process1  and
388       process2.
389
390       If  =(...)  is used instead of <(...), then the file passed as an argu‐
391       ment will be the name of a temporary file containing the output of  the
392       list  process.   This  may  be used instead of the < form for a program
393       that expects to lseek (see lseek(2)) on the input file.
394
395       There is an optimisation for substitutions of the form =(<<<arg), where
396       arg is a single-word argument to the here-string redirection <<<.  This
397       form produces a file name containing the value of arg after any substi‐
398       tutions  have been performed.  This is handled entirely within the cur‐
399       rent shell.  This is  effectively  the  reverse  of  the  special  form
400       $(<arg) which treats arg as a file name and replaces it with the file's
401       contents.
402
403       The = form is useful as both the /dev/fd and the named pipe implementa‐
404       tion of <(...) have drawbacks.  In the former case, some programmes may
405       automatically close the file descriptor in  question  before  examining
406       the file on the command line, particularly if this is necessary for se‐
407       curity reasons such as when the programme is running  setuid.   In  the
408       second case, if the programme does not actually open the file, the sub‐
409       shell attempting to read from or write to the pipe will (in  a  typical
410       implementation,  different  operating systems may have different behav‐
411       iour) block for ever and have to be killed explicitly.  In both  cases,
412       the  shell actually supplies the information using a pipe, so that pro‐
413       grammes that expect to lseek (see lseek(2)) on the file will not work.
414
415       Also note that the previous example can be  more  compactly  and  effi‐
416       ciently written (provided the MULTIOS option is set) as:
417
418              paste <(cut -f1 file1) <(cut -f3 file2) \
419              > >(process1) > >(process2)
420
421       The  shell  uses  pipes  instead  of  FIFOs to implement the latter two
422       process substitutions in the above example.
423
424       There is an additional problem with >(process); when this  is  attached
425       to  an  external command, the parent shell does not wait for process to
426       finish and hence an immediately following command cannot  rely  on  the
427       results  being  complete.  The problem and solution are the same as de‐
428       scribed in the section MULTIOS in zshmisc(1).  Hence  in  a  simplified
429       version of the example above:
430
431              paste <(cut -f1 file1) <(cut -f3 file2) > >(process)
432
433       (note that no MULTIOS are involved), process will be run asynchronously
434       as far as the parent shell is concerned.  The workaround is:
435
436              { paste <(cut -f1 file1) <(cut -f3 file2) } > >(process)
437
438       The extra processes here are spawned from the parent shell  which  will
439       wait for their completion.
440
441       Another problem arises any time a job with a substitution that requires
442       a temporary file is disowned by the shell,  including  the  case  where
443       `&!' or `&|' appears at the end of a command containing a substitution.
444       In that case the temporary file will not be cleaned up as the shell  no
445       longer  has  any memory of the job.  A workaround is to use a subshell,
446       for example,
447
448              (mycmd =(myoutput)) &!
449
450       as the forked subshell will wait for the command to finish then  remove
451       the temporary file.
452
453       A  general  workaround  to ensure a process substitution endures for an
454       appropriate length of time is to pass it as a parameter to an anonymous
455       shell  function  (a  piece  of  shell code that is run immediately with
456       function scope).  For example, this code:
457
458              () {
459                 print File $1:
460                 cat $1
461              } =(print This be the verse)
462
463       outputs something resembling the following
464
465              File /tmp/zsh6nU0kS:
466              This be the verse
467
468       The temporary file created by the process substitution will be  deleted
469       when the function exits.
470

PARAMETER EXPANSION

472       The  character `$' is used to introduce parameter expansions.  See zsh‐
473       param(1) for a description of parameters, including arrays, associative
474       arrays, and subscript notation to access individual array elements.
475
476       Note  in  particular the fact that words of unquoted parameters are not
477       automatically split on whitespace unless the  option  SH_WORD_SPLIT  is
478       set;  see references to this option below for more details.  This is an
479       important difference from other shells.  However, as in  other  shells,
480       null words are elided from unquoted parameters' expansions.
481
482       With default options, after the assignments:
483
484              array=("first word" "" "third word")
485              scalar="only word"
486
487       then  $array  substitutes two words, `first word' and `third word', and
488       $scalar substitutes a single word `only word'.  Note that  second  ele‐
489       ment of array was elided.  Scalar parameters can be elided too if their
490       value is null (empty).  To  avoid  elision,  use  quoting  as  follows:
491       "$scalar"  for  scalars  and "${array[@]}" or "${(@)array}" for arrays.
492       (The last two forms are equivalent.)
493
494       Parameter expansions can involve flags, as  in  `${(@kv)aliases}',  and
495       other  operators,  such as `${PREFIX:-"/usr/local"}'.  Parameter expan‐
496       sions can also be nested.  These topics will be introduced below.   The
497       full rules are complicated and are noted at the end.
498
499       In  the  expansions discussed below that require a pattern, the form of
500       the pattern is the same as that used for filename generation;  see  the
501       section  `Filename  Generation'.   Note that these patterns, along with
502       the replacement text of any substitutions, are  themselves  subject  to
503       parameter  expansion,  command  substitution, and arithmetic expansion.
504       In addition to the following operations, the colon modifiers  described
505       in  the  section  `Modifiers' in the section `History Expansion' can be
506       applied:  for example, ${i:s/foo/bar/} performs string substitution  on
507       the expansion of parameter $i.
508
509       In  the  following descriptions, `word' refers to a single word substi‐
510       tuted on the command line, not necessarily a space delimited word.
511
512       ${name}
513              The value, if any, of the parameter name  is  substituted.   The
514              braces are required if the expansion is to be followed by a let‐
515              ter, digit, or underscore that is not to be interpreted as  part
516              of  name.   In  addition, more complicated forms of substitution
517              usually require the braces to be present; exceptions, which only
518              apply  if  the  option  KSH_ARRAYS is not set, are a single sub‐
519              script or any colon modifiers appearing after the name,  or  any
520              of the characters `^', `=', `~', `#' or `+' appearing before the
521              name, all of which work with or without braces.
522
523              If name is an array parameter, and the KSH_ARRAYS option is  not
524              set,  then the value of each element of name is substituted, one
525              element per word.  Otherwise, the expansion results in one  word
526              only;  with  KSH_ARRAYS,  this is the first element of an array.
527              No  field  splitting  is  done  on   the   result   unless   the
528              SH_WORD_SPLIT   option  is  set.   See  also  the  flags  =  and
529              s:string:.
530
531       ${+name}
532              If name is the name of a set parameter `1' is substituted,  oth‐
533              erwise `0' is substituted.
534
535       ${name-word}
536       ${name:-word}
537              If  name is set, or in the second form is non-null, then substi‐
538              tute its value; otherwise substitute word.  In the  second  form
539              name may be omitted, in which case word is always substituted.
540
541       ${name+word}
542       ${name:+word}
543              If  name is set, or in the second form is non-null, then substi‐
544              tute word; otherwise substitute nothing.
545
546       ${name=word}
547       ${name:=word}
548       ${name::=word}
549              In the first form, if name is unset then set it to word; in  the
550              second  form,  if name is unset or null then set it to word; and
551              in the third form, unconditionally set name  to  word.   In  all
552              forms, the value of the parameter is then substituted.
553
554       ${name?word}
555       ${name:?word}
556              In the first form, if name is set, or in the second form if name
557              is both set and non-null, then substitute its value;  otherwise,
558              print  word and exit from the shell.  Interactive shells instead
559              return to the prompt.  If word is omitted, then a standard  mes‐
560              sage is printed.
561
562       In  any of the above expressions that test a variable and substitute an
563       alternate word, note that you can use standard  shell  quoting  in  the
564       word   value   to  selectively  override  the  splitting  done  by  the
565       SH_WORD_SPLIT option and the = flag, but not splitting by the s:string:
566       flag.
567
568       In  the  following expressions, when name is an array and the substitu‐
569       tion is not quoted, or if the `(@)' flag or the name[@] syntax is used,
570       matching and replacement is performed on each array element separately.
571
572       ${name#pattern}
573       ${name##pattern}
574              If  the pattern matches the beginning of the value of name, then
575              substitute the value of name with the matched  portion  deleted;
576              otherwise,  just  substitute  the  value  of name.  In the first
577              form, the smallest matching pattern is preferred; in the  second
578              form, the largest matching pattern is preferred.
579
580       ${name%pattern}
581       ${name%%pattern}
582              If  the  pattern matches the end of the value of name, then sub‐
583              stitute the value of name with the matched portion deleted; oth‐
584              erwise,  just  substitute the value of name.  In the first form,
585              the smallest matching pattern is preferred; in the second  form,
586              the largest matching pattern is preferred.
587
588       ${name:#pattern}
589              If  the  pattern  matches the value of name, then substitute the
590              empty string; otherwise, just substitute the value of name.   If
591              name  is  an  array the matching array elements are removed (use
592              the `(M)' flag to remove the non-matched elements).
593
594       ${name:|arrayname}
595              If arrayname is the name (N.B., not contents) of an array  vari‐
596              able,  then any elements contained in arrayname are removed from
597              the substitution of name.  If the substitution is scalar, either
598              because  name  is a scalar variable or the expression is quoted,
599              the elements of arrayname are instead tested against the  entire
600              expression.
601
602       ${name:*arrayname}
603              Similar  to  the  preceding  substitution,  but  in the opposite
604              sense, so that entries present in both the original substitution
605              and as elements of arrayname are retained and others removed.
606
607       ${name:^arrayname}
608       ${name:^^arrayname}
609              Zips  two arrays, such that the output array is twice as long as
610              the shortest (longest for `:^^') of name and arrayname, with the
611              elements  alternatingly being picked from them. For `:^', if one
612              of the input arrays is longer, the output will stop when the end
613              of the shorter array is reached.  Thus,
614
615                     a=(1 2 3 4); b=(a b); print ${a:^b}
616
617              will  output  `1  a 2 b'.  For `:^^', then the input is repeated
618              until all of the longer array has been used  up  and  the  above
619              will output `1 a 2 b 3 a 4 b'.
620
621              Either  or  both inputs may be a scalar, they will be treated as
622              an array of length 1 with the scalar as the only element. If ei‐
623              ther array is empty, the other array is output with no extra el‐
624              ements inserted.
625
626              Currently the following code will output `a b' and  `1'  as  two
627              separate  elements,  which  can  be unexpected. The second print
628              provides a workaround which should continue to work if  this  is
629              changed.
630
631                     a=(a b); b=(1 2); print -l "${a:^b}"; print -l "${${a:^b}}"
632
633       ${name:offset}
634       ${name:offset:length}
635              This  syntax  gives effects similar to parameter subscripting in
636              the form $name[start,end], but is compatible with other  shells;
637              note  that  both  offset  and length are interpreted differently
638              from the components of a subscript.
639
640              If offset is non-negative, then if the variable name is a scalar
641              substitute  the  contents  starting  offset  characters from the
642              first character of the string, and if name is an  array  substi‐
643              tute  elements  starting offset elements from the first element.
644              If length is given, substitute that many characters or elements,
645              otherwise the entire rest of the scalar or array.
646
647              A positive offset is always treated as the offset of a character
648              or element in name from the first character or  element  of  the
649              array  (this  is  different from native zsh subscript notation).
650              Hence 0 refers to the first character or element  regardless  of
651              the setting of the option KSH_ARRAYS.
652
653              A negative offset counts backwards from the end of the scalar or
654              array, so that -1 corresponds to the last character or  element,
655              and so on.
656
657              When positive, length counts from the offset position toward the
658              end of the scalar or array.  When negative, length  counts  back
659              from  the  end.  If this results in a position smaller than off‐
660              set, a diagnostic is printed and nothing is substituted.
661
662              The option MULTIBYTE is obeyed, i.e. the offset and length count
663              multibyte characters where appropriate.
664
665              offset and length undergo the same set of shell substitutions as
666              for scalar assignment; in addition, they  are  then  subject  to
667              arithmetic evaluation.  Hence, for example
668
669                     print ${foo:3}
670                     print ${foo: 1 + 2}
671                     print ${foo:$(( 1 + 2))}
672                     print ${foo:$(echo 1 + 2)}
673
674              all  have the same effect, extracting the string starting at the
675              fourth character of $foo if the substitution would otherwise re‐
676              turn  a  scalar,  or the array starting at the fourth element if
677              $foo would return an array.  Note that with the  option  KSH_AR‐
678              RAYS  $foo always returns a scalar (regardless of the use of the
679              offset syntax) and a form such as ${foo[*]:3} is required to ex‐
680              tract elements of an array named foo.
681
682              If  offset  is  negative, the - may not appear immediately after
683              the : as this indicates the ${name:-word} form of  substitution.
684              Instead,  a  space  may  be inserted before the -.  Furthermore,
685              neither offset nor length may begin with an alphabetic character
686              or  & as these are used to indicate history-style modifiers.  To
687              substitute a value from a variable, the recommended approach  is
688              to  precede it with a $ as this signifies the intention (parame‐
689              ter substitution can easily be rendered unreadable); however, as
690              arithmetic  substitution  is  performed,  the  expression ${var:
691              offs} does work, retrieving the offset from $offs.
692
693              For further compatibility with other shells there is  a  special
694              case  for  array offset 0.  This usually accesses the first ele‐
695              ment of the array.  However, if the substitution refers  to  the
696              positional parameter array, e.g. $@ or $*, then offset 0 instead
697              refers to $0, offset 1 refers to $1, and so on.  In other words,
698              the  positional  parameter  array  is  effectively  extended  by
699              prepending $0.  Hence ${*:0:1} substitutes $0 and ${*:1:1}  sub‐
700              stitutes $1.
701
702       ${name/pattern/repl}
703       ${name//pattern/repl}
704       ${name:/pattern/repl}
705              Replace  the  longest possible match of pattern in the expansion
706              of parameter name by string repl.  The first form replaces  just
707              the  first  occurrence, the second form all occurrences, and the
708              third form replaces only if pattern matches the  entire  string.
709              Both pattern and repl are subject to double-quoted substitution,
710              so that expressions like ${name/$opat/$npat} will work, but obey
711              the  usual rule that pattern characters in $opat are not treated
712              specially unless either the option GLOB_SUBST is set,  or  $opat
713              is instead substituted as ${~opat}.
714
715              The pattern may begin with a `#', in which case the pattern must
716              match at the start of the string, or `%', in which case it  must
717              match  at  the end of the string, or `#%' in which case the pat‐
718              tern must match the entire string.  The repl  may  be  an  empty
719              string,  in  which  case  the final `/' may also be omitted.  To
720              quote the final `/' in other cases it should be  preceded  by  a
721              single backslash; this is not necessary if the `/' occurs inside
722              a substituted parameter.  Note also that the `#',  `%'  and  `#%
723              are  not  active  if  they occur inside a substituted parameter,
724              even at the start.
725
726              If, after quoting rules apply, ${name} expands to an array,  the
727              replacements  act  on  each element individually.  Note also the
728              effect of the I and S parameter expansion flags below;  however,
729              the flags M, R, B, E and N are not useful.
730
731              For example,
732
733                     foo="twinkle twinkle little star" sub="t*e" rep="spy"
734                     print ${foo//${~sub}/$rep}
735                     print ${(S)foo//${~sub}/$rep}
736
737              Here, the `~' ensures that the text of $sub is treated as a pat‐
738              tern rather than a plain string.  In the first case, the longest
739              match for t*e is substituted and the result is `spy star', while
740              in the second case, the shortest matches are taken and  the  re‐
741              sult is `spy spy lispy star'.
742
743       ${#spec}
744              If spec is one of the above substitutions, substitute the length
745              in characters of the result instead of the  result  itself.   If
746              spec  is  an array expression, substitute the number of elements
747              of the result.  This has the side-effect that joining is skipped
748              even  in quoted forms, which may affect other sub-expressions in
749              spec.  Note that `^', `=', and `~', below, must  appear  to  the
750              left of `#' when these forms are combined.
751
752              If the option POSIX_IDENTIFIERS is not set, and spec is a simple
753              name, then the braces are optional; this is true even  for  spe‐
754              cial  parameters  so  e.g.  $#-  and  $#* take the length of the
755              string $- and the array $* respectively.   If  POSIX_IDENTIFIERS
756              is set, then braces are required for the # to be treated in this
757              fashion.
758
759       ${^spec}
760              Turn on the RC_EXPAND_PARAM option for the evaluation  of  spec;
761              if  the  `^'  is doubled, turn it off.  When this option is set,
762              array expansions of the form foo${xx}bar, where the parameter xx
763              is  set  to  (a  b  c),  are  substituted  with `fooabar foobbar
764              foocbar' instead of the default `fooa b  cbar'.   Note  that  an
765              empty array will therefore cause all arguments to be removed.
766
767              Internally, each such expansion is converted into the equivalent
768              list   for   brace    expansion.     E.g.,    ${^var}    becomes
769              {$var[1],$var[2],...}, and is processed as described in the sec‐
770              tion `Brace Expansion' below: note, however, the expansion  hap‐
771              pens  immediately,  with  any explicit brace expansion happening
772              later.  If word splitting is also  in  effect  the  $var[N]  may
773              themselves be split into different list elements.
774
775       ${=spec}
776              Perform  word splitting using the rules for SH_WORD_SPLIT during
777              the evaluation of spec, but regardless of whether the  parameter
778              appears  in  double  quotes; if the `=' is doubled, turn it off.
779              This forces parameter expansions to be split into separate words
780              before  substitution, using IFS as a delimiter.  This is done by
781              default in most other shells.
782
783              Note that splitting is applied to word in the  assignment  forms
784              of  spec  before  the assignment to name is performed.  This af‐
785              fects the result of array assignments with the A flag.
786
787       ${~spec}
788              Turn on the GLOB_SUBST option for the evaluation of spec; if the
789              `~'  is  doubled,  turn  it  off.   When this option is set, the
790              string resulting from the expansion will  be  interpreted  as  a
791              pattern anywhere that is possible, such as in filename expansion
792              and filename generation and pattern-matching contexts  like  the
793              right hand side of the `=' and `!=' operators in conditions.
794
795              In  nested  substitutions, note that the effect of the ~ applies
796              to the result of the current level of substitution.  A surround‐
797              ing  pattern  operation on the result may cancel it.  Hence, for
798              example, if the parameter foo is set to  *,  ${~foo//\*/*.c}  is
799              substituted  by  the pattern *.c, which may be expanded by file‐
800              name  generation,  but  ${${~foo}//\*/*.c}  substitutes  to  the
801              string *.c, which will not be further expanded.
802
803       If  a ${...} type parameter expression or a $(...) type command substi‐
804       tution is used in place of name above, it is expanded first and the re‐
805       sult  is  used as if it were the value of name.  Thus it is possible to
806       perform nested operations:  ${${foo#head}%tail} substitutes  the  value
807       of  $foo  with both `head' and `tail' deleted.  The form with $(...) is
808       often useful in combination with the flags described next; see the  ex‐
809       amples  below.  Each name or nested ${...} in a parameter expansion may
810       also be followed by a subscript expression as described in Array Param‐
811       eters in zshparam(1).
812
813       Note  that double quotes may appear around nested expressions, in which
814       case  only  the  part  inside  is  treated  as  quoted;  for   example,
815       ${(f)"$(foo)"} quotes the result of $(foo), but the flag `(f)' (see be‐
816       low) is applied using the rules for unquoted expansions.  Note  further
817       that  quotes  are  themselves  nested  in this context; for example, in
818       "${(@f)"$(foo)"}", there are two sets of quotes,  one  surrounding  the
819       whole  expression,  the other (redundant) surrounding the $(foo) as be‐
820       fore.
821
822   Parameter Expansion Flags
823       If the opening brace is directly followed by  an  opening  parenthesis,
824       the  string  up  to the matching closing parenthesis will be taken as a
825       list of flags.  In cases where repeating a flag is meaningful, the rep‐
826       etitions need not be consecutive; for example, `(q%q%q)' means the same
827       thing as the more readable `(%%qqq)'.  The  following  flags  are  sup‐
828       ported:
829
830       #      Evaluate  the  resulting words as numeric expressions and output
831              the characters corresponding to  the  resulting  integer.   Note
832              that  this  form  is entirely distinct from use of the # without
833              parentheses.
834
835              If the MULTIBYTE option is set and the number  is  greater  than
836              127  (i.e.  not  an  ASCII character) it is treated as a Unicode
837              character.
838
839       %      Expand all % escapes in the resulting words in the same  way  as
840              in prompts (see EXPANSION OF PROMPT SEQUENCES in zshmisc(1)). If
841              this flag is given twice, full prompt expansion is done  on  the
842              resulting words, depending on the setting of the PROMPT_PERCENT,
843              PROMPT_SUBST and PROMPT_BANG options.
844
845       @      In double quotes, array elements are put  into  separate  words.
846              E.g.,   `"${(@)foo}"'   is   equivalent   to  `"${foo[@]}"'  and
847              `"${(@)foo[1,2]}"' is the same as `"$foo[1]"  "$foo[2]"'.   This
848              is  distinct  from field splitting by the f, s or z flags, which
849              still applies within each array element.
850
851       A      Convert the substitution into an array expression,  even  if  it
852              otherwise  would be scalar.  This has lower precedence than sub‐
853              scripting, so one level of nested expansion is required in order
854              that  subscripts apply to array elements.  Thus ${${(A)name}[1]}
855              yields the full value of name when name is scalar.
856
857              This assigns an array parameter with `${...=...}', `${...:=...}'
858              or  `${...::=...}'.   If this flag is repeated (as in `AA'), as‐
859              signs an associative array parameter.  Assignment is made before
860              sorting  or padding; if field splitting is active, the word part
861              is split before assignment.  The name part may be a  subscripted
862              range  for ordinary arrays; when assigning an associative array,
863              the word part must be converted to an array, for example by  us‐
864              ing `${(AA)=name=...}' to activate field splitting.
865
866              Surrounding  context  such  as  additional nesting or use of the
867              value in a scalar assignment may cause the array  to  be  joined
868              back into a single string again.
869
870       a      Sort  in  array  index order; when combined with `O' sort in re‐
871              verse array index order.  Note that `a' is therefore  equivalent
872              to  the default but `Oa' is useful for obtaining an array's ele‐
873              ments in reverse order.
874
875       b      Quote with backslashes only characters that are special to  pat‐
876              tern  matching. This is useful when the contents of the variable
877              are to be tested using GLOB_SUBST, including the ${~...} switch.
878
879              Quoting using one of the q family of flags  does  not  work  for
880              this  purpose  since  quotes  are  not stripped from non-pattern
881              characters by GLOB_SUBST.  In other words,
882
883                     pattern=${(q)str}
884                     [[ $str = ${~pattern} ]]
885
886              works if $str is `a*b' but not if it is `a b', whereas
887
888                     pattern=${(b)str}
889                     [[ $str = ${~pattern} ]]
890
891              is always true for any possible value of $str.
892
893       c      With ${#name}, count the total number of characters in an array,
894              as  if  the elements were concatenated with spaces between them.
895              This is not a true join of the array, so other expressions  used
896              with  this  flag may have an effect on the elements of the array
897              before it is counted.
898
899       C      Capitalize the resulting words.  `Words' in this case refers  to
900              sequences  of  alphanumeric characters separated by non-alphanu‐
901              merics, not to words that result from field splitting.
902
903       D      Assume the string or array elements contain directories and  at‐
904              tempt to substitute the leading part of these by names.  The re‐
905              mainder of the path (the whole of it if the leading part was not
906              substituted) is then quoted so that the whole string can be used
907              as a shell argument.  This is the reverse of  `~'  substitution:
908              see the section FILENAME EXPANSION below.
909
910       e      Perform  single  word  shell expansions, namely parameter expan‐
911              sion, command substitution and arithmetic expansion, on the  re‐
912              sult.  Such  expansions can be nested but too deep recursion may
913              have unpredictable effects.
914
915       f      Split the result of the expansion at newlines. This is a  short‐
916              hand for `ps:\n:'.
917
918       F      Join  the words of arrays together using newline as a separator.
919              This is a shorthand for `pj:\n:'.
920
921       g:opts:
922              Process escape sequences like the echo builtin when  no  options
923              are  given (g::).  With the o option, octal escapes don't take a
924              leading zero.  With the c option, sequences like `^X'  are  also
925              processed.   With the e option, processes `\M-t' and similar se‐
926              quences like the print builtin.  With both of the o  and  e  op‐
927              tions,  behaves  like  the  print builtin except that in none of
928              these modes is `\c' interpreted.
929
930       i      Sort case-insensitively.  May be combined with `n' or `O'.
931
932       k      If name refers to an associative array, substitute the keys (el‐
933              ement  names) rather than the values of the elements.  Used with
934              subscripts (including ordinary arrays), force indices or keys to
935              be  substituted  even  if  the  subscript form refers to values.
936              However, this flag may not be combined  with  subscript  ranges.
937              With  the KSH_ARRAYS option a subscript `[*]' or `[@]' is needed
938              to operate on the whole array, as usual.
939
940       L      Convert all letters in the result to lower case.
941
942       n      Sort decimal integers numerically; if the first differing  char‐
943              acters  of  two test strings are not digits, sorting is lexical.
944              Integers with more initial zeroes are sorted before  those  with
945              fewer  or  none.   Hence  the  array `foo1 foo02 foo2 foo3 foo20
946              foo23' is sorted into the order shown.  May be combined with `i'
947              or `O'.
948
949       o      Sort  the resulting words in ascending order; if this appears on
950              its own the sorting is lexical and  case-sensitive  (unless  the
951              locale renders it case-insensitive).  Sorting in ascending order
952              is the default for other forms of sorting, so this is ignored if
953              combined with `a', `i' or `n'.
954
955       O      Sort  the  resulting words in descending order; `O' without `a',
956              `i' or `n' sorts in reverse lexical order.  May be combined with
957              `a', `i' or `n' to reverse the order of sorting.
958
959       P      This forces the value of the parameter name to be interpreted as
960              a further parameter name, whose value will be used where  appro‐
961              priate.   Note  that flags set with one of the typeset family of
962              commands (in particular case transformations) are not applied to
963              the value of name used in this fashion.
964
965              If used with a nested parameter or command substitution, the re‐
966              sult of that will be taken as a parameter name in the same  way.
967              For  example,  if  you have `foo=bar' and `bar=baz', the strings
968              ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo bar)} will be  expanded
969              to `baz'.
970
971              Likewise, if the reference is itself nested, the expression with
972              the flag is treated as if it were directly replaced by  the  pa‐
973              rameter  name.   It is an error if this nested substitution pro‐
974              duces an array  with  more  than  one  word.   For  example,  if
975              `name=assoc'  where the parameter assoc is an associative array,
976              then `${${(P)name}[elt]}' refers to the element of the  associa‐
977              tive subscripted `elt'.
978
979       q      Quote  characters that are special to the shell in the resulting
980              words with backslashes; unprintable or  invalid  characters  are
981              quoted  using  the  $'\NNN'  form, with separate quotes for each
982              octet.
983
984              If this flag is given twice, the resulting words are  quoted  in
985              single  quotes  and  if  it  is given three times, the words are
986              quoted in double quotes; in these forms no special  handling  of
987              unprintable  or invalid characters is attempted.  If the flag is
988              given four times, the words are quoted in single quotes preceded
989              by  a  $.  Note that in all three of these forms quoting is done
990              unconditionally, even if this does not change the  way  the  re‐
991              sulting string would be interpreted by the shell.
992
993              If a q- is given (only a single q may appear), a minimal form of
994              single quoting is used that only quotes the string if needed  to
995              protect  special characters.  Typically this form gives the most
996              readable output.
997
998              If a q+ is given, an extended form of minimal  quoting  is  used
999              that  causes unprintable characters to be rendered using $'...'.
1000              This quoting is similar to that used by the output of values  by
1001              the typeset family of commands.
1002
1003       Q      Remove one level of quotes from the resulting words.
1004
1005       t      Use  a  string  describing  the  type of the parameter where the
1006              value of the parameter would usually appear.  This  string  con‐
1007              sists  of keywords separated by hyphens (`-'). The first keyword
1008              in the string  describes  the  main  type,  it  can  be  one  of
1009              `scalar',  `array',  `integer',  `float'  or  `association'. The
1010              other keywords describe the type in more detail:
1011
1012              local  for local parameters
1013
1014              left   for left justified parameters
1015
1016              right_blanks
1017                     for right justified parameters with leading blanks
1018
1019              right_zeros
1020                     for right justified parameters with leading zeros
1021
1022              lower  for parameters whose value is converted to all lower case
1023                     when it is expanded
1024
1025              upper  for parameters whose value is converted to all upper case
1026                     when it is expanded
1027
1028              readonly
1029                     for readonly parameters
1030
1031              tag    for tagged parameters
1032
1033              export for exported parameters
1034
1035              unique for arrays which keep only the first occurrence of dupli‐
1036                     cated values
1037
1038              hide   for parameters with the `hide' flag
1039
1040              hideval
1041                     for parameters with the `hideval' flag
1042
1043              special
1044                     for special parameters defined by the shell
1045
1046       u      Expand only the first occurrence of each unique word.
1047
1048       U      Convert all letters in the result to upper case.
1049
1050       v      Used  with k, substitute (as two consecutive words) both the key
1051              and the value of each associative array element.  Used with sub‐
1052              scripts,  force  values  to be substituted even if the subscript
1053              form refers to indices or keys.
1054
1055       V      Make any special characters in the resulting words visible.
1056
1057       w      With ${#name}, count words in arrays or strings; the s flag  may
1058              be used to set a word delimiter.
1059
1060       W      Similar  to  w  with the difference that empty words between re‐
1061              peated delimiters are also counted.
1062
1063       X      With this flag, parsing errors occurring with the  Q,  e  and  #
1064              flags  or  the  pattern matching forms such as `${name#pattern}'
1065              are reported.  Without the flag, errors are silently ignored.
1066
1067       z      Split the result of the expansion into words using shell parsing
1068              to  find  the words, i.e. taking into account any quoting in the
1069              value.  Comments are  not  treated  specially  but  as  ordinary
1070              strings, similar to interactive shells with the INTERACTIVE_COM‐
1071              MENTS option unset (however, see the Z flag  below  for  related
1072              options)
1073
1074              Note  that  this  is  done  very late, even later than the `(s)'
1075              flag. So to access single words in the result use nested  expan‐
1076              sions as in `${${(z)foo}[2]}'. Likewise, to remove the quotes in
1077              the resulting words use `${(Q)${(z)foo}}'.
1078
1079       0      Split the result of the expansion on  null  bytes.   This  is  a
1080              shorthand for `ps:\0:'.
1081
1082       The following flags (except p) are followed by one or more arguments as
1083       shown.  Any character, or the matching pairs `(...)', `{...}', `[...]',
1084       or  `<...>',  may  be  used in place of a colon as delimiters, but note
1085       that when a flag takes more than one argument, a matched pair of delim‐
1086       iters must surround each argument.
1087
1088       p      Recognize  the  same  escape  sequences  as the print builtin in
1089              string arguments to any of the flags described below that follow
1090              this argument.
1091
1092              Alternatively,  with  this option string arguments may be in the
1093              form $var in which case the value of  the  variable  is  substi‐
1094              tuted.   Note  this form is strict; the string argument does not
1095              undergo general parameter expansion.
1096
1097              For example,
1098
1099                     sep=:
1100                     val=a:b:c
1101                     print ${(ps.$sep.)val}
1102
1103              splits the variable on a :.
1104
1105       ~      Strings inserted into the expansion by any of  the  flags  below
1106              are to be treated as patterns.  This applies to the string argu‐
1107              ments of flags that follow ~ within the same set of parentheses.
1108              Compare with ~ outside parentheses, which forces the entire sub‐
1109              stituted string to be treated as a pattern.  Hence, for example,
1110
1111                     [[ "?" = ${(~j.|.)array} ]]
1112
1113              treats `|' as a pattern and succeeds if and only if $array  con‐
1114              tains  the  string  `?' as an element.  The ~ may be repeated to
1115              toggle the behaviour; its effect only lasts to the  end  of  the
1116              parenthesised group.
1117
1118       j:string:
1119              Join  the  words of arrays together using string as a separator.
1120              Note that this occurs before field splitting  by  the  s:string:
1121              flag or the SH_WORD_SPLIT option.
1122
1123       l:expr::string1::string2:
1124              Pad  the  resulting  words on the left.  Each word will be trun‐
1125              cated if required and placed in a field expr characters wide.
1126
1127              The arguments :string1: and :string2: are optional; neither, the
1128              first, or both may be given.  Note that the same pairs of delim‐
1129              iters must be used for each of the three arguments.   The  space
1130              to  the  left will be filled with string1 (concatenated as often
1131              as needed) or spaces if string1 is not given.  If  both  string1
1132              and  string2 are given, string2 is inserted once directly to the
1133              left of each word, truncated if  necessary,  before  string1  is
1134              used to produce any remaining padding.
1135
1136              If either of string1 or string2 is present but empty, i.e. there
1137              are two delimiters together at that point, the  first  character
1138              of $IFS is used instead.
1139
1140              If  the  MULTIBYTE  option  is in effect, the flag m may also be
1141              given, in which case widths will be used for the calculation  of
1142              padding;  otherwise  individual multibyte characters are treated
1143              as occupying one unit of width.
1144
1145              If the MULTIBYTE option is not  in  effect,  each  byte  in  the
1146              string is treated as occupying one unit of width.
1147
1148              Control  characters are always assumed to be one unit wide; this
1149              allows the mechanism to be used for  generating  repetitions  of
1150              control characters.
1151
1152       m      Only  useful together with one of the flags l or r or with the #
1153              length operator when the MULTIBYTE option is in effect.  Use the
1154              character  width  reported by the system in calculating how much
1155              of the string it occupies or the overall length of  the  string.
1156              Most printable characters have a width of one unit, however cer‐
1157              tain Asian character sets and certain special effects use  wider
1158              characters; combining characters have zero width.  Non-printable
1159              characters are arbitrarily counted as zero width; how they would
1160              actually be displayed will vary.
1161
1162              If  the  m  is repeated, the character either counts zero (if it
1163              has zero width), else one.  For printable character strings this
1164              has  the  effect of counting the number of glyphs (visibly sepa‐
1165              rate characters), except for the case where combining characters
1166              themselves have non-zero width (true in certain alphabets).
1167
1168       r:expr::string1::string2:
1169              As  l, but pad the words on the right and insert string2 immedi‐
1170              ately to the right of the string to be padded.
1171
1172              Left and right padding may be used together.  In this  case  the
1173              strategy  is  to  apply  left padding to the first half width of
1174              each of the resulting words, and right  padding  to  the  second
1175              half.   If  the string to be padded has odd width the extra pad‐
1176              ding is applied on the left.
1177
1178       s:string:
1179              Force field splitting at the  separator  string.   Note  that  a
1180              string  of  two  or  more characters means that all of them must
1181              match in sequence; this differs from the  treatment  of  two  or
1182              more  characters  in the IFS parameter.  See also the = flag and
1183              the SH_WORD_SPLIT option.  An empty string may also be given  in
1184              which case every character will be a separate element.
1185
1186              For historical reasons, the usual behaviour that empty array el‐
1187              ements are retained inside double quotes is disabled for  arrays
1188              generated by splitting; hence the following:
1189
1190                     line="one::three"
1191                     print -l "${(s.:.)line}"
1192
1193              produces  two  lines  of output for one and three and elides the
1194              empty field.  To override this behaviour, supply the `(@)'  flag
1195              as well, i.e.  "${(@s.:.)line}".
1196
1197       Z:opts:
1198              As z but takes a combination of option letters between a follow‐
1199              ing pair of delimiter characters.  With no options the effect is
1200              identical to z.  (Z+c+) causes comments to be parsed as a string
1201              and retained; any field in the resulting array beginning with an
1202              unquoted comment character is a comment.  (Z+C+) causes comments
1203              to be parsed and removed.  The rule for  comments  is  standard:
1204              anything  between  a  word  starting with the third character of
1205              $HISTCHARS, default #, up to the  next  newline  is  a  comment.
1206              (Z+n+) causes unquoted newlines to be treated as ordinary white‐
1207              space, else they are treated as if they are  shell  code  delim‐
1208              iters  and converted to semicolons.  Options are combined within
1209              the same set of delimiters, e.g. (Z+Cn+).
1210
1211       _:flags:
1212              The underscore (_) flag is reserved for future use.  As of  this
1213              revision of zsh, there are no valid flags; anything following an
1214              underscore, other than an empty pair of delimiters,  is  treated
1215              as an error, and the flag itself has no effect.
1216
1217       The  following  flags  are meaningful with the ${...#...} or ${...%...}
1218       forms.  The S and I flags may also be used with the ${.../...} forms.
1219
1220       S      With # or ##, search for the match that starts  closest  to  the
1221              start  of  the string (a `substring match'). Of all matches at a
1222              particular position, # selects the shortest and ## the longest:
1223
1224                     % str="aXbXc"
1225                     % echo ${(S)str#X*}
1226                     abXc
1227                     % echo ${(S)str##X*}
1228                     a
1229                     %
1230
1231              With % or %%, search for the match that starts  closest  to  the
1232              end of the string:
1233
1234                     % str="aXbXc"
1235                     % echo ${(S)str%X*}
1236                     aXbc
1237                     % echo ${(S)str%%X*}
1238                     aXb
1239                     %
1240
1241              (Note that % and %% don't search for the match that ends closest
1242              to the end of the string, as one might expect.)
1243
1244              With  substitution  via  ${.../...}  or  ${...//...},  specifies
1245              non-greedy matching, i.e. that the shortest instead of the long‐
1246              est match should be replaced:
1247
1248                     % str="abab"
1249                     % echo ${str/*b/_}
1250                     _
1251                     % echo ${(S)str/*b/_}
1252                     _ab
1253                     %
1254
1255       I:expr:
1256              Search the exprth match (where  expr  evaluates  to  a  number).
1257              This only applies when searching for substrings, either with the
1258              S flag, or with ${.../...} (only the  exprth  match  is  substi‐
1259              tuted)  or  ${...//...} (all matches from the exprth on are sub‐
1260              stituted).  The default is to take the first match.
1261
1262              The exprth match is counted such that there  is  either  one  or
1263              zero matches from each starting position in the string, although
1264              for global substitution matches  overlapping  previous  replace‐
1265              ments  are  ignored.  With the ${...%...} and ${...%%...} forms,
1266              the starting position for the match moves backwards from the end
1267              as the index increases, while with the other forms it moves for‐
1268              ward from the start.
1269
1270              Hence with the string
1271                     which switch is the right switch for Ipswich?
1272              substitutions of the form ${(SI:N:)string#w*ch} as  N  increases
1273              from  1  will  match  and  remove  `which', `witch', `witch' and
1274              `wich'; the form using `##' will match and remove `which  switch
1275              is the right switch for Ipswich', `witch is the right switch for
1276              Ipswich', `witch for Ipswich' and `wich'.  The  form  using  `%'
1277              will  remove  the same matches as for `#', but in reverse order,
1278              and the form using `%%' will remove the same matches as for `##'
1279              in reverse order.
1280
1281       B      Include the index of the beginning of the match in the result.
1282
1283       E      Include the index one character past the end of the match in the
1284              result (note this is inconsistent with other uses  of  parameter
1285              index).
1286
1287       M      Include the matched portion in the result.
1288
1289       N      Include the length of the match in the result.
1290
1291       R      Include the unmatched portion in the result (the Rest).
1292
1293   Rules
1294       Here  is  a  summary  of  the rules for substitution; this assumes that
1295       braces are present around the substitution, i.e. ${...}.  Some particu‐
1296       lar  examples are given below.  Note that the Zsh Development Group ac‐
1297       cepts no responsibility for any brain damage which may occur during the
1298       reading of the following rules.
1299
1300       1. Nested substitution
1301              If  multiple  nested  ${...}  forms are present, substitution is
1302              performed from the inside outwards.  At each level, the  substi‐
1303              tution takes account of whether the current value is a scalar or
1304              an array, whether the whole substitution is  in  double  quotes,
1305              and  what  flags  are supplied to the current level of substitu‐
1306              tion, just as if the nested  substitution  were  the  outermost.
1307              The  flags are not propagated up to enclosing substitutions; the
1308              nested substitution will return either a scalar or an  array  as
1309              determined by the flags, possibly adjusted for quoting.  All the
1310              following steps take place where applicable  at  all  levels  of
1311              substitution.
1312
1313              Note  that,  unless the `(P)' flag is present, the flags and any
1314              subscripts apply directly to the value of the  nested  substitu‐
1315              tion;  for  example, the expansion ${${foo}} behaves exactly the
1316              same as ${foo}.  When the `(P)' flag is present in a nested sub‐
1317              stitution, the other substitution rules are applied to the value
1318              before it is interpreted as a name, so ${${(P)foo}}  may  differ
1319              from ${(P)foo}.
1320
1321              At  each nested level of substitution, the substituted words un‐
1322              dergo all forms of single-word substitution (i.e.  not  filename
1323              generation),  including  command substitution, arithmetic expan‐
1324              sion and filename expansion (i.e. leading ~ and =).   Thus,  for
1325              example,  ${${:-=cat}:h}  expands to the directory where the cat
1326              program resides.  (Explanation: the internal substitution has no
1327              parameter  but  a default value =cat, which is expanded by file‐
1328              name expansion to a full path; the outer substitution  then  ap‐
1329              plies the modifier :h and takes the directory part of the path.)
1330
1331       2. Internal parameter flags
1332              Any  parameter  flags  set  by one of the typeset family of com‐
1333              mands, in particular the -L, -R, -Z, -u and -l options for  pad‐
1334              ding  and  capitalization, are applied directly to the parameter
1335              value.  Note these flags are options to the command, e.g. `type‐
1336              set  -Z'; they are not the same as the flags used within parame‐
1337              ter substitutions.
1338
1339              At the outermost level of substitution, the `(P)' flag (rule 4.)
1340              ignores  these  transformations and uses the unmodified value of
1341              the parameter as the name to be replaced.  This is  usually  the
1342              desired  behavior  because  padding may make the value syntacti‐
1343              cally illegal as a parameter name, but if capitalization changes
1344              are desired, use the ${${(P)foo}} form (rule 25.).
1345
1346       3. Parameter subscripting
1347              If the value is a raw parameter reference with a subscript, such
1348              as ${var[3]}, the effect of subscripting is applied directly  to
1349              the  parameter.   Subscripts are evaluated left to right; subse‐
1350              quent subscripts apply to the scalar or array value  yielded  by
1351              the  previous  subscript.  Thus if var is an array, ${var[1][2]}
1352              is the second character of the first word, but ${var[2,4][2]} is
1353              the entire third word (the second word of the range of words two
1354              through four of the original array).  Any number  of  subscripts
1355              may  appear.   Flags such as `(k)' and `(v)' which alter the re‐
1356              sult of subscripting are applied.
1357
1358       4. Parameter name replacement
1359              At the outermost level of nesting only, the `(P)'  flag  is  ap‐
1360              plied.   This treats the value so far as a parameter name (which
1361              may include a subscript expression) and replaces that  with  the
1362              corresponding value.  This replacement occurs later if the `(P)'
1363              flag appears in a nested substitution.
1364
1365              If the value so far names a parameter that  has  internal  flags
1366              (rule 2.), those internal flags are applied to the new value af‐
1367              ter replacement.
1368
1369       5. Double-quoted joining
1370              If the value after this process is an array, and  the  substitu‐
1371              tion  appears  in double quotes, and neither an `(@)' flag nor a
1372              `#' length operator is present at the current level, then  words
1373              of  the value are joined with the first character of the parame‐
1374              ter $IFS, by default a space, between each word (single word ar‐
1375              rays  are  not modified).  If the `(j)' flag is present, that is
1376              used for joining instead of $IFS.
1377
1378       6. Nested subscripting
1379              Any remaining subscripts (i.e. of  a  nested  substitution)  are
1380              evaluated  at this point, based on whether the value is an array
1381              or a scalar.  As with 3., multiple subscripts can appear.   Note
1382              that  ${foo[2,4][2]} is thus equivalent to ${${foo[2,4]}[2]} and
1383              also to "${${(@)foo[2,4]}[2]}" (the nested substitution  returns
1384              an  array  in  both  cases), but not to "${${foo[2,4]}[2]}" (the
1385              nested substitution returns a scalar because of the quotes).
1386
1387       7. Modifiers
1388              Any modifiers, as specified by a trailing `#', `%', `/'  (possi‐
1389              bly  doubled)  or  by a set of modifiers of the form `:...' (see
1390              the section `Modifiers' in the section `History Expansion'), are
1391              applied to the words of the value at this level.
1392
1393       8. Character evaluation
1394              Any  `(#)' flag is applied, evaluating the result so far numeri‐
1395              cally as a character.
1396
1397       9. Length
1398              Any initial `#' modifier, i.e. in the form ${#var}, is  used  to
1399              evaluate the length of the expression so far.
1400
1401       10. Forced joining
1402              If  the  `(j)'  flag is present, or no `(j)' flag is present but
1403              the string is to be split as given by rule 11., and joining  did
1404              not take place at rule 5., any words in the value are joined to‐
1405              gether using the given string or the first character of $IFS  if
1406              none.  Note that the `(F)' flag implicitly supplies a string for
1407              joining in this manner.
1408
1409       11. Simple word splitting
1410              If one of the `(s)' or `(f)' flags are present, or the `=' spec‐
1411              ifier  was  present  (e.g. ${=var}), the word is split on occur‐
1412              rences of the specified string, or (for = with  neither  of  the
1413              two flags present) any of the characters in $IFS.
1414
1415              If  no `(s)', `(f)' or `=' was given, but the word is not quoted
1416              and the option SH_WORD_SPLIT is set, the word is split on occur‐
1417              rences  of  any of the characters in $IFS.  Note this step, too,
1418              takes place at all levels of a nested substitution.
1419
1420       12. Case modification
1421              Any case modification from one of  the  flags  `(L)',  `(U)'  or
1422              `(C)' is applied.
1423
1424       13. Escape sequence replacement
1425              First  any  replacements from the `(g)' flag are performed, then
1426              any prompt-style formatting from the `(%)' family  of  flags  is
1427              applied.
1428
1429       14. Quote application
1430              Any quoting or unquoting using `(q)' and `(Q)' and related flags
1431              is applied.
1432
1433       15. Directory naming
1434              Any directory name substitution using `(D)' flag is applied.
1435
1436       16. Visibility enhancement
1437              Any modifications to make characters  visible  using  the  `(V)'
1438              flag are applied.
1439
1440       17. Lexical word splitting
1441              If  the  '(z)'  flag  or  one  of the forms of the '(Z)' flag is
1442              present, the word is split as if it were a shell  command  line,
1443              so that quotation marks and other metacharacters are used to de‐
1444              cide what constitutes a word.  Note this form  of  splitting  is
1445              entirely  distinct  from that described by rule 11.: it does not
1446              use $IFS, and does not cause forced joining.
1447
1448       18. Uniqueness
1449              If the result is an array and the `(u)' flag was present, dupli‐
1450              cate elements are removed from the array.
1451
1452       19. Ordering
1453              If  the  result  is still an array and one of the `(o)' or `(O)'
1454              flags was present, the array is reordered.
1455
1456       20. RC_EXPAND_PARAM
1457              At this point the decision is made whether any  resulting  array
1458              elements  are to be combined element by element with surrounding
1459              text, as given by either the RC_EXPAND_PARAM option or  the  `^'
1460              flag.
1461
1462       21. Re-evaluation
1463              Any  `(e)' flag is applied to the value, forcing it to be re-ex‐
1464              amined for new parameter substitutions, but also for command and
1465              arithmetic substitutions.
1466
1467       22. Padding
1468              Any padding of the value by the `(l.fill.)' or `(r.fill.)' flags
1469              is applied.
1470
1471       23. Semantic joining
1472              In contexts where expansion semantics requires a single word  to
1473              result,  all  words are rejoined with the first character of IFS
1474              between.  So in `${(P)${(f)lines}}' the  value  of  ${lines}  is
1475              split  at  newlines,  but  then  must be joined again before the
1476              `(P)' flag can be applied.
1477
1478              If a single word is not required, this rule is skipped.
1479
1480       24. Empty argument removal
1481              If the substitution does not appear in double  quotes,  any  re‐
1482              sulting  zero-length  argument, whether from a scalar or an ele‐
1483              ment of an array, is elided from the list of arguments  inserted
1484              into the command line.
1485
1486              Strictly speaking, the removal happens later as the same happens
1487              with other forms of substitution; the point to note here is sim‐
1488              ply that it occurs after any of the above parameter operations.
1489
1490       25. Nested parameter name replacement
1491              If  the  `(P)'  flag is present and rule 4. has not applied, the
1492              value so far is treated as a parameter name (which may include a
1493              subscript expression) and replaced with the corresponding value,
1494              with internal flags (rule 2.) applied to the new value.
1495
1496   Examples
1497       The flag f is useful to split  a  double-quoted  substitution  line  by
1498       line.   For  example, ${(f)"$(<file)"} substitutes the contents of file
1499       divided so that each line is an element of the resulting  array.   Com‐
1500       pare  this with the effect of $(<file) alone, which divides the file up
1501       by words, or the same inside double quotes, which makes the entire con‐
1502       tent of the file a single string.
1503
1504       The  following  illustrates  the rules for nested parameter expansions.
1505       Suppose that $foo contains the array (bar baz):
1506
1507       "${(@)${foo}[1]}"
1508              This produces the  result  b.   First,  the  inner  substitution
1509              "${foo}",  which  has  no array (@) flag, produces a single word
1510              result "bar baz".  The outer substitution "${(@)...[1]}" detects
1511              that this is a scalar, so that (despite the `(@)' flag) the sub‐
1512              script picks the first character.
1513
1514       "${${(@)foo}[1]}"
1515              This produces the result `bar'.  In this case, the inner substi‐
1516              tution  "${(@)foo}"  produces  the array `(bar baz)'.  The outer
1517              substitution "${...[1]}" detects that this is an array and picks
1518              the first word.  This is similar to the simple case "${foo[1]}".
1519
1520       As an example of the rules for word splitting and joining, suppose $foo
1521       contains the array `(ax1 bx1)'.  Then
1522
1523       ${(s/x/)foo}
1524              produces the words `a', `1 b' and `1'.
1525
1526       ${(j/x/s/x/)foo}
1527              produces `a', `1', `b' and `1'.
1528
1529       ${(s/x/)foo%%1*}
1530              produces `a' and ` b' (note the extra space).   As  substitution
1531              occurs  before either joining or splitting, the operation  first
1532              generates the modified array (ax bx), which is  joined  to  give
1533              "ax  bx",  and  then  split to give `a', ` b' and `'.  The final
1534              empty string will then be elided, as it is not in double quotes.
1535

COMMAND SUBSTITUTION

1537       A command enclosed in parentheses  preceded  by  a  dollar  sign,  like
1538       `$(...)',  or quoted with grave accents, like ``...`', is replaced with
1539       its standard output, with any trailing newlines deleted.  If  the  sub‐
1540       stitution  is  not enclosed in double quotes, the output is broken into
1541       words using the IFS parameter.
1542
1543       The substitution `$(cat foo)' may be replaced by the faster  `$(<foo)'.
1544       In  this case foo undergoes single word shell expansions (parameter ex‐
1545       pansion, command substitution and arithmetic expansion), but not  file‐
1546       name generation.
1547
1548       If  the  option  GLOB_SUBST  is set, the result of any unquoted command
1549       substitution, including the special form just  mentioned,  is  eligible
1550       for filename generation.
1551

ARITHMETIC EXPANSION

1553       A  string  of  the  form `$[exp]' or `$((exp))' is substituted with the
1554       value of the arithmetic expression exp.  exp is subjected to  parameter
1555       expansion,  command  substitution and arithmetic expansion before it is
1556       evaluated.  See the section `Arithmetic Evaluation'.
1557

BRACE EXPANSION

1559       A string of the form `foo{xx,yy,zz}bar' is expanded to  the  individual
1560       words  `fooxxbar',  `fooyybar'  and `foozzbar'.  Left-to-right order is
1561       preserved.  This construct may be nested.  Commas may be quoted in  or‐
1562       der to include them literally in a word.
1563
1564       An  expression of the form `{n1..n2}', where n1 and n2 are integers, is
1565       expanded to every number between n1 and n2 inclusive.  If either number
1566       begins with a zero, all the resulting numbers will be padded with lead‐
1567       ing zeroes to that minimum width, but for negative numbers the -  char‐
1568       acter  is also included in the width.  If the numbers are in decreasing
1569       order the resulting sequence will also be in decreasing order.
1570
1571       An expression of the form `{n1..n2..n3}', where n1, n2, and n3 are  in‐
1572       tegers,  is expanded as above, but only every n3th number starting from
1573       n1 is output.  If n3 is negative the numbers are output in reverse  or‐
1574       der,  this  is slightly different from simply swapping n1 and n2 in the
1575       case that the step n3 doesn't evenly divide the  range.   Zero  padding
1576       can  be  specified  in  any  of the three numbers, specifying it in the
1577       third can be useful to pad for example `{-99..100..01}'  which  is  not
1578       possible  to  specify by putting a 0 on either of the first two numbers
1579       (i.e. pad to two characters).
1580
1581       An expression of the form `{c1..c2}', where c1 and c2 are single  char‐
1582       acters  (which may be multibyte characters), is expanded to every char‐
1583       acter in the range from c1 to c2 in whatever character sequence is used
1584       internally.  For characters with code points below 128 this is US ASCII
1585       (this is the only case most users will need).  If any intervening char‐
1586       acter  is  not  printable,  appropriate  quotation is used to render it
1587       printable.  If the character sequence is reversed, the output is in re‐
1588       verse order, e.g. `{d..a}' is substituted as `d c b a'.
1589
1590       If  a  brace expression matches none of the above forms, it is left un‐
1591       changed, unless the option BRACE_CCL (an abbreviation for `brace  char‐
1592       acter  class')  is  set.  In that case, it is expanded to a list of the
1593       individual characters between the braces sorted into the order  of  the
1594       characters  in  the  ASCII  character set (multibyte characters are not
1595       currently handled).  The syntax is similar to  a  [...]  expression  in
1596       filename  generation:  `-'  is  treated  specially to denote a range of
1597       characters, but `^' or `!' as the first character is treated  normally.
1598       For  example, `{abcdef0-9}' expands to 16 words 0 1 2 3 4 5 6 7 8 9 a b
1599       c d e f.
1600
1601       Note that brace expansion is not part  of  filename  generation  (glob‐
1602       bing);  an  expression  such  as */{foo,bar} is split into two separate
1603       words */foo and */bar before filename generation takes place.  In  par‐
1604       ticular,  note that this is liable to produce a `no match' error if ei‐
1605       ther of the two expressions does not match; this is  to  be  contrasted
1606       with  */(foo|bar),  which  is treated as a single pattern but otherwise
1607       has similar effects.
1608
1609       To combine brace expansion with array expansion, see the ${^spec}  form
1610       described in the section Parameter Expansion above.
1611

FILENAME EXPANSION

1613       Each  word  is checked to see if it begins with an unquoted `~'.  If it
1614       does, then the word up to a `/', or the end of the word if there is  no
1615       `/',  is checked to see if it can be substituted in one of the ways de‐
1616       scribed here.  If so, then the `~' and the checked portion are replaced
1617       with the appropriate substitute value.
1618
1619       A `~' by itself is replaced by the value of $HOME.  A `~' followed by a
1620       `+' or a `-' is replaced by current or previous working directory,  re‐
1621       spectively.
1622
1623       A  `~'  followed by a number is replaced by the directory at that posi‐
1624       tion in the directory stack.  `~0' is equivalent to `~+', and  `~1'  is
1625       the top of the stack.  `~+' followed by a number is replaced by the di‐
1626       rectory at that position in the directory stack.  `~+0'  is  equivalent
1627       to  `~+', and `~+1' is the top of the stack.  `~-' followed by a number
1628       is replaced by the directory that many positions from the bottom of the
1629       stack.   `~-0'  is the bottom of the stack.  The PUSHD_MINUS option ex‐
1630       changes the effects of `~+' and `~-' where they are followed by a  num‐
1631       ber.
1632
1633   Dynamic named directories
1634       If  the  function  zsh_directory_name  exists,  or  the  shell variable
1635       zsh_directory_name_functions exists and contains an array  of  function
1636       names,  then the functions are used to implement dynamic directory nam‐
1637       ing.  The functions are tried in order until one returns  status  zero,
1638       so it is important that functions test whether they can handle the case
1639       in question and return an appropriate status.
1640
1641       A `~' followed by a  string  namstr  in  unquoted  square  brackets  is
1642       treated specially as a dynamic directory name.  Note that the first un‐
1643       quoted closing square bracket  always  terminates  namstr.   The  shell
1644       function  is  passed two arguments: the string n (for name) and namstr.
1645       It should either set the array reply to a single element which  is  the
1646       directory  corresponding  to the name and return status zero (executing
1647       an assignment as the last  statement  is  usually  sufficient),  or  it
1648       should return status non-zero.  In the former case the element of reply
1649       is used as the directory; in the latter case the substitution is deemed
1650       to  have  failed.  If all functions fail and the option NOMATCH is set,
1651       an error results.
1652
1653       The functions defined as above are also used to see if a directory  can
1654       be turned into a name, for example when printing the directory stack or
1655       when expanding %~ in prompts.  In this case each function is passed two
1656       arguments:  the  string d (for directory) and the candidate for dynamic
1657       naming.  The function should either return non-zero status, if the  di‐
1658       rectory cannot be named by the function, or it should set the array re‐
1659       ply to consist of two elements: the first is the dynamic name  for  the
1660       directory (as would appear within `~[...]'), and the second is the pre‐
1661       fix length of the directory to be replaced.  For example, if the  trial
1662       directory  is  /home/myname/src/zsh  and the dynamic name for /home/my‐
1663       name/src (which has 16 characters) is s, then the function sets
1664
1665              reply=(s 16)
1666
1667       The directory name so returned is compared with possible  static  names
1668       for  parts of the directory path, as described below; it is used if the
1669       prefix length matched (16 in the example) is longer than  that  matched
1670       by any static name.
1671
1672       It  is not a requirement that a function implements both n and d calls;
1673       for example, it might be appropriate for certain dynamic forms  of  ex‐
1674       pansion  not to be contracted to names.  In that case any call with the
1675       first argument d should cause a non-zero status to be returned.
1676
1677       The completion system calls `zsh_directory_name c' followed by  equiva‐
1678       lent calls to elements of the array zsh_directory_name_functions, if it
1679       exists, in order to complete dynamic names for directories.   The  code
1680       for this should be as for any other completion function as described in
1681       zshcompsys(1).
1682
1683       As a working example, here is a function that expands any dynamic names
1684       beginning  with  the string p: to directories below /home/pws/perforce.
1685       In this simple case a static name for the directory would  be  just  as
1686       effective.
1687
1688              zsh_directory_name() {
1689                emulate -L zsh
1690                setopt extendedglob
1691                local -a match mbegin mend
1692                if [[ $1 = d ]]; then
1693                  # turn the directory into a name
1694                  if [[ $2 = (#b)(/home/pws/perforce/)([^/]##)* ]]; then
1695                    typeset -ga reply
1696                    reply=(p:$match[2] $(( ${#match[1]} + ${#match[2]} )) )
1697                  else
1698                    return 1
1699                  fi
1700                elif [[ $1 = n ]]; then
1701                  # turn the name into a directory
1702                  [[ $2 != (#b)p:(?*) ]] && return 1
1703                  typeset -ga reply
1704                  reply=(/home/pws/perforce/$match[1])
1705                elif [[ $1 = c ]]; then
1706                  # complete names
1707                  local expl
1708                  local -a dirs
1709                  dirs=(/home/pws/perforce/*(/:t))
1710                  dirs=(p:${^dirs})
1711                  _wanted dynamic-dirs expl 'dynamic directory' compadd -S\] -a dirs
1712                  return
1713                else
1714                  return 1
1715                fi
1716                return 0
1717              }
1718
1719   Static named directories
1720       A `~' followed by anything not already covered consisting of any number
1721       of alphanumeric characters or underscore (`_'), hyphen  (`-'),  or  dot
1722       (`.')  is  looked up as a named directory, and replaced by the value of
1723       that named directory if found.  Named directories  are  typically  home
1724       directories  for  users on the system.  They may also be defined if the
1725       text after the `~' is the name of a string shell parameter whose  value
1726       begins with a `/'.  Note that trailing slashes will be removed from the
1727       path to the directory (though the original parameter is not modified).
1728
1729       It is also possible to define directory names using the  -d  option  to
1730       the hash builtin.
1731
1732       When the shell prints a path (e.g. when expanding %~ in prompts or when
1733       printing the directory stack), the path is checked to see if it  has  a
1734       named  directory  as its prefix.  If so, then the prefix portion is re‐
1735       placed with a `~' followed by the name of the directory.   The  shorter
1736       of  the two ways of referring to the directory is used, i.e. either the
1737       directory name or the full path; the name is used if they are the  same
1738       length.   The parameters $PWD and $OLDPWD are never abbreviated in this
1739       fashion.
1740
1741   `=' expansion
1742       If a word begins with an unquoted `=' and the EQUALS option is set, the
1743       remainder  of the word is taken as the name of a command.  If a command
1744       exists by that name, the word is replaced by the full pathname  of  the
1745       command.
1746
1747   Notes
1748       Filename  expansion  is performed on the right hand side of a parameter
1749       assignment, including those appearing after  commands  of  the  typeset
1750       family.   In  this  case,  the  right  hand  side  will be treated as a
1751       colon-separated list in the manner of the PATH parameter, so that a `~'
1752       or  an  `=' following a `:' is eligible for expansion.  All such behav‐
1753       iour can be disabled by quoting the `~', the `=', or the whole  expres‐
1754       sion (but not simply the colon); the EQUALS option is also respected.
1755
1756       If  the option MAGIC_EQUAL_SUBST is set, any unquoted shell argument in
1757       the form `identifier=expression' becomes eligible for file expansion as
1758       described  in  the  previous paragraph.  Quoting the first `=' also in‐
1759       hibits this.
1760

FILENAME GENERATION

1762       If a word contains an unquoted instance of one of the  characters  `*',
1763       `(',  `|',  `<',  `[', or `?', it is regarded as a pattern for filename
1764       generation, unless the GLOB option is unset.  If the EXTENDED_GLOB  op‐
1765       tion  is  set, the `^' and `#' characters also denote a pattern; other‐
1766       wise they are not treated specially by the shell.
1767
1768       The word is replaced with a list of sorted  filenames  that  match  the
1769       pattern.   If  no  matching  pattern is found, the shell gives an error
1770       message, unless the NULL_GLOB option is set, in which case the word  is
1771       deleted;  or unless the NOMATCH option is unset, in which case the word
1772       is left unchanged.
1773
1774       In filename generation, the character `/' must be  matched  explicitly;
1775       also, a `.' must be matched explicitly at the beginning of a pattern or
1776       after a `/', unless the GLOB_DOTS option is set.  No  filename  genera‐
1777       tion pattern matches the files `.' or `..'.  In other instances of pat‐
1778       tern matching, the `/' and `.' are not treated specially.
1779
1780   Glob Operators
1781       *      Matches any string, including the null string.
1782
1783       ?      Matches any character.
1784
1785       [...]  Matches any of the enclosed characters.   Ranges  of  characters
1786              can  be  specified by separating two characters by a `-'.  A `-'
1787              or `]' may be matched by including it as the first character  in
1788              the  list.   There are also several named classes of characters,
1789              in the form `[:name:]' with the following meanings.   The  first
1790              set  use the macros provided by the operating system to test for
1791              the given character combinations,  including  any  modifications
1792              due to local language settings, see ctype(3):
1793
1794              [:alnum:]
1795                     The character is alphanumeric
1796
1797              [:alpha:]
1798                     The character is alphabetic
1799
1800              [:ascii:]
1801                     The  character  is 7-bit, i.e. is a single-byte character
1802                     without the top bit set.
1803
1804              [:blank:]
1805                     The character is a blank character
1806
1807              [:cntrl:]
1808                     The character is a control character
1809
1810              [:digit:]
1811                     The character is a decimal digit
1812
1813              [:graph:]
1814                     The character is a printable character other than  white‐
1815                     space
1816
1817              [:lower:]
1818                     The character is a lowercase letter
1819
1820              [:print:]
1821                     The character is printable
1822
1823              [:punct:]
1824                     The  character  is printable but neither alphanumeric nor
1825                     whitespace
1826
1827              [:space:]
1828                     The character is whitespace
1829
1830              [:upper:]
1831                     The character is an uppercase letter
1832
1833              [:xdigit:]
1834                     The character is a hexadecimal digit
1835
1836              Another set of named classes is handled internally by the  shell
1837              and is not sensitive to the locale:
1838
1839              [:IDENT:]
1840                     The  character is allowed to form part of a shell identi‐
1841                     fier, such as a parameter name
1842
1843              [:IFS:]
1844                     The character is used as an input field  separator,  i.e.
1845                     is contained in the IFS parameter
1846
1847              [:IFSSPACE:]
1848                     The  character  is  an IFS white space character; see the
1849                     documentation for IFS in the zshparam(1) manual page.
1850
1851              [:INCOMPLETE:]
1852                     Matches a byte that starts an incomplete multibyte  char‐
1853                     acter.   Note  that  there may be a sequence of more than
1854                     one bytes that taken together form the prefix of a multi‐
1855                     byte  character.   To  test  for a potentially incomplete
1856                     byte sequence, use the pattern `[[:INCOMPLETE:]]*'.  This
1857                     will  never match a sequence starting with a valid multi‐
1858                     byte character.
1859
1860              [:INVALID:]
1861                     Matches a byte that does  not  start  a  valid  multibyte
1862                     character.   Note  this  may be a continuation byte of an
1863                     incomplete multibyte character as any part of a multibyte
1864                     string  consisting  of  invalid  and incomplete multibyte
1865                     characters is treated as single bytes.
1866
1867              [:WORD:]
1868                     The character is treated as part of a word; this test  is
1869                     sensitive to the value of the WORDCHARS parameter
1870
1871              Note  that the square brackets are additional to those enclosing
1872              the whole set of characters, so to test for  a  single  alphanu‐
1873              meric  character  you  need `[[:alnum:]]'.  Named character sets
1874              can be used alongside other types, e.g. `[[:alpha:]0-9]'.
1875
1876       [^...]
1877       [!...] Like [...], except that it matches any character which is not in
1878              the given set.
1879
1880       <[x]-[y]>
1881              Matches  any  number  in the range x to y, inclusive.  Either of
1882              the numbers may be omitted to make the range  open-ended;  hence
1883              `<->' matches any number.  To match individual digits, the [...]
1884              form is more efficient.
1885
1886              Be careful when using other wildcards adjacent  to  patterns  of
1887              this  form;  for  example, <0-9>* will actually match any number
1888              whatsoever at the start of the string, since  the  `<0-9>'  will
1889              match  the first digit, and the `*' will match any others.  This
1890              is a trap for the unwary, but is in fact  an  inevitable  conse‐
1891              quence  of  the rule that the longest possible match always suc‐
1892              ceeds.  Expressions such as `<0-9>[^[:digit:]]*' can be used in‐
1893              stead.
1894
1895       (...)  Matches  the  enclosed  pattern.  This is used for grouping.  If
1896              the KSH_GLOB option is set, then a `@', `*', `+', `?' or `!' im‐
1897              mediately  preceding  the  `(' is treated specially, as detailed
1898              below. The option SH_GLOB prevents bare parentheses  from  being
1899              used in this way, though the KSH_GLOB option is still available.
1900
1901              Note  that  grouping cannot extend over multiple directories: it
1902              is an error to have a `/' within a group (this only applies  for
1903              patterns  used in filename generation).  There is one exception:
1904              a group of the form (pat/)# appearing as a complete path segment
1905              can match a sequence of directories.  For example, foo/(a*/)#bar
1906              matches foo/bar, foo/any/bar, foo/any/anyother/bar, and so on.
1907
1908       x|y    Matches either x or y.  This operator has lower precedence  than
1909              any  other.   The  `|'  character must be within parentheses, to
1910              avoid interpretation as a pipeline.  The alternatives are  tried
1911              in order from left to right.
1912
1913       ^x     (Requires EXTENDED_GLOB to be set.)  Matches anything except the
1914              pattern x.  This has a higher precedence than `/', so `^foo/bar'
1915              will  search  directories in `.' except `./foo' for a file named
1916              `bar'.
1917
1918       x~y    (Requires EXTENDED_GLOB to be set.)  Match anything that matches
1919              the  pattern  x but does not match y.  This has lower precedence
1920              than any operator except `|', so `*/*~foo/bar' will  search  for
1921              all  files in all directories in `.'  and then exclude `foo/bar'
1922              if there was such a match.  Multiple patterns can be excluded by
1923              `foo~bar~baz'.   In  the  exclusion pattern (y), `/' and `.' are
1924              not treated specially the way they usually are in globbing.
1925
1926       x#     (Requires EXTENDED_GLOB to be set.)  Matches zero or more occur‐
1927              rences  of  the  pattern  x.  This operator has high precedence;
1928              `12#' is equivalent to `1(2#)', rather than `(12)#'.  It  is  an
1929              error  for  an  unquoted `#' to follow something which cannot be
1930              repeated; this includes an empty string, a pattern already  fol‐
1931              lowed  by  `##',  or parentheses when part of a KSH_GLOB pattern
1932              (for example, `!(foo)#' is  invalid  and  must  be  replaced  by
1933              `*(!(foo))').
1934
1935       x##    (Requires  EXTENDED_GLOB to be set.)  Matches one or more occur‐
1936              rences of the pattern x.  This  operator  has  high  precedence;
1937              `12##' is equivalent to `1(2##)', rather than `(12)##'.  No more
1938              than two active `#' characters may appear together.   (Note  the
1939              potential  clash with glob qualifiers in the form `1(2##)' which
1940              should therefore be avoided.)
1941
1942   ksh-like Glob Operators
1943       If the KSH_GLOB option is set, the effects of parentheses can be  modi‐
1944       fied by a preceding `@', `*', `+', `?' or `!'.  This character need not
1945       be unquoted to have special effects, but the `(' must be.
1946
1947       @(...) Match the pattern in the parentheses.  (Like `(...)'.)
1948
1949       *(...) Match any number of occurrences.  (Like  `(...)#',  except  that
1950              recursive directory searching is not supported.)
1951
1952       +(...) Match at least one occurrence.  (Like `(...)##', except that re‐
1953              cursive directory searching is not supported.)
1954
1955       ?(...) Match zero or one occurrence.  (Like `(|...)'.)
1956
1957       !(...) Match  anything  but  the  expression  in  parentheses.    (Like
1958              `(^(...))'.)
1959
1960   Precedence
1961       The precedence of the operators given above is (highest) `^', `/', `~',
1962       `|' (lowest); the remaining operators are simply treated from  left  to
1963       right  as  part of a string, with `#' and `##' applying to the shortest
1964       possible preceding unit (i.e. a character, `?', `[...]', `<...>', or  a
1965       parenthesised  expression).  As mentioned above, a `/' used as a direc‐
1966       tory separator may not appear inside parentheses, while a `|'  must  do
1967       so;  in  patterns  used in other contexts than filename generation (for
1968       example, in case statements and tests within `[[...]]'), a `/'  is  not
1969       special;  and  `/'  is  also  not special after a `~' appearing outside
1970       parentheses in a filename pattern.
1971
1972   Globbing Flags
1973       There are various flags which affect any text to their right up to  the
1974       end  of  the enclosing group or to the end of the pattern; they require
1975       the EXTENDED_GLOB option. All take the form (#X) where X may  have  one
1976       of the following forms:
1977
1978       i      Case insensitive:  upper or lower case characters in the pattern
1979              match upper or lower case characters.
1980
1981       l      Lower case characters in the pattern match upper or  lower  case
1982              characters;  upper  case  characters  in  the pattern still only
1983              match upper case characters.
1984
1985       I      Case sensitive:  locally negates the effect of i or l from  that
1986              point on.
1987
1988       b      Activate backreferences for parenthesised groups in the pattern;
1989              this does not work in filename generation.  When a pattern  with
1990              a  set  of active parentheses is matched, the strings matched by
1991              the groups are stored in the array $match, the  indices  of  the
1992              beginning  of  the matched parentheses in the array $mbegin, and
1993              the indices of the end in the array $mend, with the  first  ele‐
1994              ment  of  each  array  corresponding  to the first parenthesised
1995              group, and so on.  These arrays are not otherwise special to the
1996              shell.   The  indices  use the same convention as does parameter
1997              substitution, so that elements of $mend and $mbegin may be  used
1998              in  subscripts;  the  KSH_ARRAYS  option  is respected.  Sets of
1999              globbing flags are not considered parenthesised groups; only the
2000              first nine active parentheses can be referenced.
2001
2002              For example,
2003
2004                     foo="a_string_with_a_message"
2005                     if [[ $foo = (a|an)_(#b)(*) ]]; then
2006                       print ${foo[$mbegin[1],$mend[1]]}
2007                     fi
2008
2009              prints  `string_with_a_message'.   Note  that  the  first set of
2010              parentheses is before the (#b) and does not create a  backrefer‐
2011              ence.
2012
2013              Backreferences  work  with  all  forms of pattern matching other
2014              than filename generation, but note that when performing  matches
2015              on  an  entire array, such as ${array#pattern}, or a global sub‐
2016              stitution, such as ${param//pat/repl}, only  the  data  for  the
2017              last  match  remains  available.  In the case of global replace‐
2018              ments this may still be useful.  See the example for the m  flag
2019              below.
2020
2021              The  numbering  of  backreferences strictly follows the order of
2022              the opening parentheses  from  left  to  right  in  the  pattern
2023              string,  although  sets of parentheses may be nested.  There are
2024              special rules for parentheses followed by `#' or `##'.  Only the
2025              last match of the parenthesis is remembered: for example, in `[[
2026              abab =  (#b)([ab])#  ]]',  only  the  final  `b'  is  stored  in
2027              match[1].   Thus extra parentheses may be necessary to match the
2028              complete segment: for example, use  `X((ab|cd)#)Y'  to  match  a
2029              whole  string  of either `ab' or `cd' between `X' and `Y', using
2030              the value of $match[1] rather than $match[2].
2031
2032              If the match fails none of the parameters is altered, so in some
2033              cases  it  may  be  necessary to initialise them beforehand.  If
2034              some of the backreferences fail to match  --  which  happens  if
2035              they are in an alternate branch which fails to match, or if they
2036              are followed by # and matched zero times  --  then  the  matched
2037              string is set to the empty string, and the start and end indices
2038              are set to -1.
2039
2040              Pattern matching with backreferences  is  slightly  slower  than
2041              without.
2042
2043       B      Deactivate  backreferences,  negating  the  effect of the b flag
2044              from that point on.
2045
2046       cN,M   The flag (#cN,M) can be used anywhere that the # or ## operators
2047              can  be  used  except in the expressions `(*/)#' and `(*/)##' in
2048              filename generation, where `/' has special meaning; it cannot be
2049              combined  with  other globbing flags and a bad pattern error oc‐
2050              curs if it is misplaced.  It is equivalent to the form {N,M}  in
2051              regular  expressions.   The  previous  character or group is re‐
2052              quired to match between N and  M  times,  inclusive.   The  form
2053              (#cN) requires exactly N matches; (#c,M) is equivalent to speci‐
2054              fying N as 0; (#cN,) specifies that there is no maximum limit on
2055              the number of matches.
2056
2057       m      Set  references to the match data for the entire string matched;
2058              this is similar to backreferencing and does not work in filename
2059              generation.   The  flag must be in effect at the end of the pat‐
2060              tern, i.e. not local to a group. The parameters $MATCH,  $MBEGIN
2061              and  $MEND  will be set to the string matched and to the indices
2062              of the beginning and end of the string, respectively.   This  is
2063              most  useful in parameter substitutions, as otherwise the string
2064              matched is obvious.
2065
2066              For example,
2067
2068                     arr=(veldt jynx grimps waqf zho buck)
2069                     print ${arr//(#m)[aeiou]/${(U)MATCH}}
2070
2071              forces all the matches (i.e. all vowels) into uppercase,  print‐
2072              ing `vEldt jynx grImps wAqf zhO bUck'.
2073
2074              Unlike backreferences, there is no speed penalty for using match
2075              references, other than the extra substitutions required for  the
2076              replacement strings in cases such as the example shown.
2077
2078       M      Deactivate the m flag, hence no references to match data will be
2079              created.
2080
2081       anum   Approximate matching: num  errors  are  allowed  in  the  string
2082              matched by the pattern.  The rules for this are described in the
2083              next subsection.
2084
2085       s, e   Unlike the other flags, these have only a local effect, and each
2086              must  appear  on  its own:  `(#s)' and `(#e)' are the only valid
2087              forms.  The `(#s)' flag succeeds only at the start of  the  test
2088              string, and the `(#e)' flag succeeds only at the end of the test
2089              string; they correspond to `^' and `$' in standard  regular  ex‐
2090              pressions.   They  are useful for matching path segments in pat‐
2091              terns other than those in filename generation (where  path  seg‐
2092              ments  are  in  any  case  treated  separately).   For  example,
2093              `*((#s)|/)test((#e)|/)*' matches a path segment `test' in any of
2094              the   following   strings:   test,  test/at/start,  at/end/test,
2095              in/test/middle.
2096
2097              Another use is in parameter  substitution;  for  example  `${ar‐
2098              ray/(#s)A*Z(#e)}'  will  remove  only elements of an array which
2099              match the complete pattern `A*Z'.  There are other ways of  per‐
2100              forming many operations of this type, however the combination of
2101              the substitution operations `/' and `//'  with  the  `(#s)'  and
2102              `(#e)' flags provides a single simple and memorable method.
2103
2104              Note that assertions of the form `(^(#s))' also work, i.e. match
2105              anywhere except at the start of the string, although this  actu‐
2106              ally  means  `anything except a zero-length portion at the start
2107              of  the  string';  you  need  to  use  `(""~(#s))'  to  match  a
2108              zero-length portion of the string not at the start.
2109
2110       q      A  `q' and everything up to the closing parenthesis of the glob‐
2111              bing flags are ignored by the pattern matching  code.   This  is
2112              intended  to support the use of glob qualifiers, see below.  The
2113              result is that the pattern `(#b)(*).c(#q.)' can be used both for
2114              globbing and for matching against a string.  In the former case,
2115              the `(#q.)' will be treated as a glob qualifier and  the  `(#b)'
2116              will  not be useful, while in the latter case the `(#b)' is use‐
2117              ful for backreferences and the `(#q.)' will  be  ignored.   Note
2118              that colon modifiers in the glob qualifiers are also not applied
2119              in ordinary pattern matching.
2120
2121       u      Respect the current locale in determining the presence of multi‐
2122              byte  characters  in  a pattern, provided the shell was compiled
2123              with MULTIBYTE_SUPPORT.  This overrides  the  MULTIBYTE  option;
2124              the  default  behaviour  is  taken  from the option.  Compare U.
2125              (Mnemonic: typically multibyte characters are  from  Unicode  in
2126              the UTF-8 encoding, although any extension of ASCII supported by
2127              the system library may be used.)
2128
2129       U      All characters are considered to be a single byte long.  The op‐
2130              posite of u.  This overrides the MULTIBYTE option.
2131
2132       For  example,  the  test  string  fooxx  can  be matched by the pattern
2133       (#i)FOOXX, but not by (#l)FOOXX,  (#i)FOO(#I)XX  or  ((#i)FOOX)X.   The
2134       string  (#ia2)readme specifies case-insensitive matching of readme with
2135       up to two errors.
2136
2137       When using the ksh syntax for grouping both KSH_GLOB and  EXTENDED_GLOB
2138       must  be  set  and  the left parenthesis should be preceded by @.  Note
2139       also that the flags do not affect letters inside [...] groups, in other
2140       words  (#i)[a-z]  still  matches only lowercase letters.  Finally, note
2141       that when examining whole paths case-insensitively every directory must
2142       be  searched  for  all files which match, so that a pattern of the form
2143       (#i)/foo/bar/... is potentially slow.
2144
2145   Approximate Matching
2146       When matching approximately, the shell keeps  a  count  of  the  errors
2147       found,  which  cannot exceed the number specified in the (#anum) flags.
2148       Four types of error are recognised:
2149
2150       1.     Different characters, as in fooxbar and fooybar.
2151
2152       2.     Transposition of characters, as in banana and abnana.
2153
2154       3.     A character missing in the target string, as  with  the  pattern
2155              road and target string rod.
2156
2157       4.     An extra character appearing in the target string, as with stove
2158              and strove.
2159
2160       Thus, the pattern (#a3)abcd matches dcba, with the errors occurring  by
2161       using  the first rule twice and the second once, grouping the string as
2162       [d][cb][a] and [a][bc][d].
2163
2164       Non-literal parts of the pattern must match exactly, including  charac‐
2165       ters  in  character  ranges:  hence (#a1)???  matches strings of length
2166       four, by applying rule 4 to an empty  part  of  the  pattern,  but  not
2167       strings  of  length  two, since all the ? must match.  Other characters
2168       which must match exactly are initial  dots  in  filenames  (unless  the
2169       GLOB_DOTS option is set), and all slashes in filenames, so that a/bc is
2170       two errors from ab/c (the slash cannot be transposed with another char‐
2171       acter).   Similarly,  errors  are counted separately for non-contiguous
2172       strings in the pattern, so that (ab|cd)ef is two errors from aebf.
2173
2174       When using exclusion  via  the  ~  operator,  approximate  matching  is
2175       treated entirely separately for the excluded part and must be activated
2176       separately.  Thus, (#a1)README~READ_ME matches READ.ME but not READ_ME,
2177       as  the  trailing  READ_ME  is matched without approximation.  However,
2178       (#a1)README~(#a1)READ_ME does not match any pattern of the form READ?ME
2179       as all such forms are now excluded.
2180
2181       Apart  from exclusions, there is only one overall error count; however,
2182       the maximum errors allowed may be altered locally, and this can be  de‐
2183       limited by grouping.  For example, (#a1)cat((#a0)dog)fox allows one er‐
2184       ror in total, which may not occur in the dog section, and  the  pattern
2185       (#a1)cat(#a0)dog(#a1)fox  is  equivalent.  Note that the point at which
2186       an error is first found is the crucial one for establishing whether  to
2187       use   approximation;  for  example,  (#a1)abc(#a0)xyz  will  not  match
2188       abcdxyz, because the error occurs at the `x',  where  approximation  is
2189       turned off.
2190
2191       Entire   path   segments   may   be   matched  approximately,  so  that
2192       `(#a1)/foo/d/is/available/at/the/bar' allows one error in any path seg‐
2193       ment.   This  is  much  less efficient than without the (#a1), however,
2194       since every directory in the path must be scanned for  a  possible  ap‐
2195       proximate match.  It is best to place the (#a1) after any path segments
2196       which are known to be correct.
2197
2198   Recursive Globbing
2199       A pathname component of the form `(foo/)#' matches a path consisting of
2200       zero or more directories matching the pattern foo.
2201
2202       As  a  shorthand, `**/' is equivalent to `(*/)#'; note that this there‐
2203       fore matches files in the current directory as well as  subdirectories.
2204       Thus:
2205
2206              ls -ld -- (*/)#bar
2207
2208       or
2209
2210              ls -ld -- **/bar
2211
2212       does  a  recursive  directory search for files named `bar' (potentially
2213       including the file `bar' in the current directory).  This form does not
2214       follow  symbolic links; the alternative form `***/' does, but is other‐
2215       wise identical.  Neither of these can be combined with other  forms  of
2216       globbing  within the same path segment; in that case, the `*' operators
2217       revert to their usual effect.
2218
2219       Even shorter forms are available when  the  option  GLOB_STAR_SHORT  is
2220       set.   In  that  case  if no / immediately follows a ** or *** they are
2221       treated as if both a / plus a further * are present.  Hence:
2222
2223              setopt GLOBSTARSHORT
2224              ls -ld -- **.c
2225
2226       is equivalent to
2227
2228              ls -ld -- **/*.c
2229
2230   Glob Qualifiers
2231       Patterns used for filename generation may end in a list  of  qualifiers
2232       enclosed  in  parentheses.  The qualifiers specify which filenames that
2233       otherwise match the given pattern will  be  inserted  in  the  argument
2234       list.
2235
2236       If the option BARE_GLOB_QUAL is set, then a trailing set of parentheses
2237       containing no `|' or `(' characters (or `~' if it is special) is  taken
2238       as  a set of glob qualifiers.  A glob subexpression that would normally
2239       be taken as glob qualifiers, for example `(^x)', can be  forced  to  be
2240       treated  as  part  of  the glob pattern by doubling the parentheses, in
2241       this case producing `((^x))'.
2242
2243       If the option EXTENDED_GLOB is set, a different syntax for glob  quali‐
2244       fiers  is  available,  namely  `(#qx)'  where x is any of the same glob
2245       qualifiers used in the other format.  The qualifiers must still  appear
2246       at  the  end  of  the pattern.  However, with this syntax multiple glob
2247       qualifiers may be chained together.  They are treated as a logical  AND
2248       of  the  individual sets of flags.  Also, as the syntax is unambiguous,
2249       the expression will be treated as glob  qualifiers  just  as  long  any
2250       parentheses contained within it are balanced; appearance of `|', `(' or
2251       `~' does not negate the effect.  Note that qualifiers  will  be  recog‐
2252       nised  in  this form even if a bare glob qualifier exists at the end of
2253       the pattern, for example `*(#q*)(.)' will recognise executable  regular
2254       files if both options are set; however, mixed syntax should probably be
2255       avoided for the sake of clarity.  Note that within conditions using the
2256       `[[' form the presence of a parenthesised expression (#q...) at the end
2257       of a string indicates that globbing should be performed; the expression
2258       may include glob qualifiers, but it is also valid if it is simply (#q).
2259       This does not apply to the right hand side of pattern  match  operators
2260       as the syntax already has special significance.
2261
2262       A qualifier may be any one of the following:
2263
2264       /      directories
2265
2266       F      `full'  (i.e.  non-empty)  directories.   Note that the opposite
2267              sense (^F) expands to empty directories and all non-directories.
2268              Use (/^F) for empty directories.
2269
2270       .      plain files
2271
2272       @      symbolic links
2273
2274       =      sockets
2275
2276       p      named pipes (FIFOs)
2277
2278       *      executable plain files (0100 or 0010 or 0001)
2279
2280       %      device files (character or block special)
2281
2282       %b     block special files
2283
2284       %c     character special files
2285
2286       r      owner-readable files (0400)
2287
2288       w      owner-writable files (0200)
2289
2290       x      owner-executable files (0100)
2291
2292       A      group-readable files (0040)
2293
2294       I      group-writable files (0020)
2295
2296       E      group-executable files (0010)
2297
2298       R      world-readable files (0004)
2299
2300       W      world-writable files (0002)
2301
2302       X      world-executable files (0001)
2303
2304       s      setuid files (04000)
2305
2306       S      setgid files (02000)
2307
2308       t      files with the sticky bit (01000)
2309
2310       fspec  files with access rights matching spec. This spec may be a octal
2311              number optionally preceded by a `=', a `+', or a `-'. If none of
2312              these  characters is given, the behavior is the same as for `='.
2313              The octal number describes the mode bits to be expected, if com‐
2314              bined  with a `=', the value given must match the file-modes ex‐
2315              actly, with a `+', at least the bits in the given number must be
2316              set  in  the  file-modes, and with a `-', the bits in the number
2317              must not be set. Giving a `?' instead of a octal digit  anywhere
2318              in  the  number  ensures  that  the  corresponding  bits  in the
2319              file-modes are not checked, this is only useful  in  combination
2320              with `='.
2321
2322              If the qualifier `f' is followed by any other character anything
2323              up to the next matching character (`[', `{', and `<' match  `]',
2324              `}',  and  `>' respectively, any other character matches itself)
2325              is taken as a list of comma-separated sub-specs.  Each  sub-spec
2326              may  be  either  an octal number as described above or a list of
2327              any of the characters `u', `g', `o', and `a', followed by a `=',
2328              a  `+',  or  a  `-', followed by a list of any of the characters
2329              `r', `w', `x', `s', and `t', or an octal digit. The  first  list
2330              of  characters specify which access rights are to be checked. If
2331              a `u' is given, those for the owner of the file are used,  if  a
2332              `g'  is  given,  those  of the group are checked, a `o' means to
2333              test those of other users, and the `a' says to  test  all  three
2334              groups. The `=', `+', and `-' again says how the modes are to be
2335              checked and have the same meaning as  described  for  the  first
2336              form above. The second list of characters finally says which ac‐
2337              cess rights are to be expected: `r' for  read  access,  `w'  for
2338              write  access,  `x'  for  the  right  to execute the file (or to
2339              search a directory), `s' for the setuid and setgid bits, and `t'
2340              for the sticky bit.
2341
2342              Thus,  `*(f70?)'  gives  the files for which the owner has read,
2343              write, and execute permission, and for which other group members
2344              have  no rights, independent of the permissions for other users.
2345              The pattern `*(f-100)' gives all files for which the owner  does
2346              not  have  execute  permission,  and `*(f:gu+w,o-rx:)' gives the
2347              files for which the owner and the other  members  of  the  group
2348              have  at least write permission, and for which other users don't
2349              have read or execute permission.
2350
2351       estring
2352       +cmd   The string will be executed as shell code.  The filename will be
2353              included in the list if and only if the code returns a zero sta‐
2354              tus (usually the status of the last command).
2355
2356              In the first form, the first character after  the  `e'  will  be
2357              used as a separator and anything up to the next matching separa‐
2358              tor will be taken  as the string; `[', `{', and `<'  match  `]',
2359              `}',  and  `>',  respectively, while any other character matches
2360              itself. Note that expansions must be quoted  in  the  string  to
2361              prevent  them  from  being  expanded  before  globbing  is done.
2362              string is then executed as shell code.  The string  globqual  is
2363              appended  to  the  array zsh_eval_context the duration of execu‐
2364              tion.
2365
2366              During the execution of  string  the  filename  currently  being
2367              tested is available in the parameter REPLY; the parameter may be
2368              altered to a string to be inserted into the list instead of  the
2369              original  filename.  In addition, the parameter reply may be set
2370              to an array or a string, which overrides the value of REPLY.  If
2371              set  to  an  array, the latter is inserted into the command line
2372              word by word.
2373
2374              For  example,  suppose  a  directory  contains  a  single   file
2375              `lonely'.   Then  the expression `*(e:'reply=(${REPLY}{1,2})':)'
2376              will cause the words `lonely1' and `lonely2' to be inserted into
2377              the command line.  Note the quoting of string.
2378
2379              The  form  +cmd  has  the  same effect, but no delimiters appear
2380              around cmd.  Instead, cmd is taken as the  longest  sequence  of
2381              characters  following the + that are alphanumeric or underscore.
2382              Typically cmd will be the name of a shell function that contains
2383              the appropriate test.  For example,
2384
2385                     nt() { [[ $REPLY -nt $NTREF ]] }
2386                     NTREF=reffile
2387                     ls -ld -- *(+nt)
2388
2389              lists  all  files  in the directory that have been modified more
2390              recently than reffile.
2391
2392       ddev   files on the device dev
2393
2394       l[-|+]ct
2395              files having a link count less than ct (-), greater than ct (+),
2396              or equal to ct
2397
2398       U      files owned by the effective user ID
2399
2400       G      files owned by the effective group ID
2401
2402       uid    files  owned  by  user ID id if that is a number.  Otherwise, id
2403              specifies a user name: the character after the `u' will be taken
2404              as  a  separator and the string between it and the next matching
2405              separator will be taken as a user name.  The starting separators
2406              `[',  `{', and `<' match the final separators `]', `}', and `>',
2407              respectively; any other character matches itself.  The  selected
2408              files  are  those  owned by this user.  For example, `u:foo:' or
2409              `u[foo]' selects files owned by user `foo'.
2410
2411       gid    like uid but with group IDs or names
2412
2413       a[Mwhms][-|+]n
2414              files accessed exactly n days ago.  Files  accessed  within  the
2415              last  n  days  are  selected  using a negative value for n (-n).
2416              Files accessed more than n days ago are selected by a positive n
2417              value  (+n).  Optional unit specifiers `M', `w', `h', `m' or `s'
2418              (e.g. `ah5') cause the check to be performed with months (of  30
2419              days), weeks, hours, minutes or seconds instead of days, respec‐
2420              tively.  An explicit `d' for days is also allowed.
2421
2422              Any fractional part of the difference between  the  access  time
2423              and  the current part in the appropriate units is ignored in the
2424              comparison.  For instance, `echo *(ah-5)' would echo  files  ac‐
2425              cessed  within  the  last five hours, while `echo *(ah+5)' would
2426              echo files accessed at least six hours ago,  as  times  strictly
2427              between five and six hours are treated as five hours.
2428
2429       m[Mwhms][-|+]n
2430              like  the  file  access  qualifier, except that it uses the file
2431              modification time.
2432
2433       c[Mwhms][-|+]n
2434              like the file access qualifier, except that it uses the file in‐
2435              ode change time.
2436
2437       L[+|-]n
2438              files less than n bytes (-), more than n bytes (+), or exactly n
2439              bytes in length.
2440
2441              If this flag is directly followed by a size specifier `k' (`K'),
2442              `m'  (`M'),  or  `p' (`P') (e.g. `Lk-50') the check is performed
2443              with kilobytes, megabytes, or blocks  (of  512  bytes)  instead.
2444              (On  some  systems additional specifiers are available for giga‐
2445              bytes, `g' or `G', and terabytes, `t' or `T'.) If a size  speci‐
2446              fier  is  used  a  file is regarded as "exactly" the size if the
2447              file size rounded up to the next unit is equal to the test size.
2448              Hence `*(Lm1)' matches files from 1 byte up to 1 Megabyte inclu‐
2449              sive.  Note also that the set of files "less than" the test size
2450              only  includes  files  that  would  not match the equality test;
2451              hence `*(Lm-1)' only matches files of zero size.
2452
2453       ^      negates all qualifiers following it
2454
2455       -      toggles between making the qualifiers  work  on  symbolic  links
2456              (the default) and the files they point to
2457
2458       M      sets the MARK_DIRS option for the current pattern
2459
2460       T      appends a trailing qualifier mark to the filenames, analogous to
2461              the LIST_TYPES option, for the current pattern (overrides M)
2462
2463       N      sets the NULL_GLOB option for the current pattern
2464
2465       D      sets the GLOB_DOTS option for the current pattern
2466
2467       n      sets the NUMERIC_GLOB_SORT option for the current pattern
2468
2469       Yn     enables short-circuit mode: the pattern will expand to at most n
2470              filenames.   If  more  than  n  matches  exist, only the first n
2471              matches in directory traversal order will be considered.
2472
2473              Implies oN when no oc qualifier is used.
2474
2475       oc     specifies how the names of the files should be sorted. If c is n
2476              they are sorted by name; if it is L they are sorted depending on
2477              the size (length) of the files; if l they are sorted by the num‐
2478              ber  of  links; if a, m, or c they are sorted by the time of the
2479              last access, modification, or inode change respectively;  if  d,
2480              files  in  subdirectories appear before those in the current di‐
2481              rectory at each level of the search --  this  is  best  combined
2482              with  other  criteria,  for  example `odon' to sort on names for
2483              files within the same directory; if N, no sorting is  performed.
2484              Note  that a, m, and c compare the age against the current time,
2485              hence the first name in the list is the youngest file. Also note
2486              that  the  modifiers ^ and - are used, so `*(^-oL)' gives a list
2487              of all files sorted by file size in descending order,  following
2488              any  symbolic  links.   Unless oN is used, multiple order speci‐
2489              fiers may occur to resolve ties.
2490
2491              The default sorting is n (by name) unless the Y  glob  qualifier
2492              is used, in which case it is N (unsorted).
2493
2494              oe  and  o+  are  special cases; they are each followed by shell
2495              code, delimited as for the e glob qualifier and the + glob qual‐
2496              ifier  respectively  (see above).  The code is executed for each
2497              matched file with the parameter REPLY set to  the  name  of  the
2498              file  on  entry  and globsort appended to zsh_eval_context.  The
2499              code should modify the parameter REPLY in some fashion.  On  re‐
2500              turn,  the  value  of  the parameter is used instead of the file
2501              name as the string on which to sort.  Unlike other  sort  opera‐
2502              tors,  oe and o+ may be repeated, but note that the maximum num‐
2503              ber of sort operators of any kind that may appear  in  any  glob
2504              expression is 12.
2505
2506       Oc     like  `o',  but  sorts in descending order; i.e. `*(^oc)' is the
2507              same as `*(Oc)' and `*(^Oc)' is the same as `*(oc)';  `Od'  puts
2508              files in the current directory before those in subdirectories at
2509              each level of the search.
2510
2511       [beg[,end]]
2512              specifies which of the matched filenames should be  included  in
2513              the  returned  list.  The  syntax  is the same as for array sub‐
2514              scripts. beg and the optional end may  be  mathematical  expres‐
2515              sions. As in parameter subscripting they may be negative to make
2516              them count from the last  match  backward.  E.g.:  `*(-OL[1,3])'
2517              gives a list of the names of the three largest files.
2518
2519       Pstring
2520              The  string  will  be prepended to each glob match as a separate
2521              word.  string is delimited in the same way as arguments to the e
2522              glob  qualifier described above.  The qualifier can be repeated;
2523              the words are prepended separately so that the resulting command
2524              line contains the words in the same order they were given in the
2525              list of glob qualifiers.
2526
2527              A typical use for this is to prepend an option before all occur‐
2528              rences  of a file name; for example, the pattern `*(P:-f:)' pro‐
2529              duces the command line arguments `-f file1 -f file2 ...'
2530
2531              If the modifier ^ is active, then string will  be  appended  in‐
2532              stead  of  prepended.  Prepending and appending is done indepen‐
2533              dently so both can be used on the same glob expression; for  ex‐
2534              ample  by  writing  `*(P:foo:^P:bar:^P:baz:)' which produces the
2535              command line arguments `foo baz file1 bar ...'
2536
2537       More than one of these lists can be combined, separated by commas.  The
2538       whole  list  matches  if at least one of the sublists matches (they are
2539       `or'ed, the qualifiers in the sublists are `and'ed).  Some  qualifiers,
2540       however,  affect  all  matches generated, independent of the sublist in
2541       which they are given.  These are the qualifiers  `M',  `T',  `N',  `D',
2542       `n', `o', `O' and the subscripts given in brackets (`[...]').
2543
2544       If  a  `:' appears in a qualifier list, the remainder of the expression
2545       in parenthesis is interpreted as a modifier  (see  the  section  `Modi‐
2546       fiers'  in the section `History Expansion').  Each modifier must be in‐
2547       troduced by a separate `:'.  Note also that the result after  modifica‐
2548       tion  does  not  have to be an existing file.  The name of any existing
2549       file can be followed by a modifier of the form `(:...)' even if no  ac‐
2550       tual  filename generation is performed, although note that the presence
2551       of the parentheses causes the entire expression to be subjected to  any
2552       global pattern matching options such as NULL_GLOB. Thus:
2553
2554              ls -ld -- *(-/)
2555
2556       lists all directories and symbolic links that point to directories, and
2557
2558              ls -ld -- *(-@)
2559
2560       lists all broken symbolic links, and
2561
2562              ls -ld -- *(%W)
2563
2564       lists all world-writable device files in the current directory, and
2565
2566              ls -ld -- *(W,X)
2567
2568       lists  all  files  in  the current directory that are world-writable or
2569       world-executable, and
2570
2571              print -rC1 /tmp/foo*(u0^@:t)
2572
2573       outputs the basename of all root-owned files beginning with the  string
2574       `foo' in /tmp, ignoring symlinks, and
2575
2576              ls -ld -- *.*~(lex|parse).[ch](^D^l1)
2577
2578       lists  all  files  having a link count of one whose names contain a dot
2579       (but not those starting with  a  dot,  since  GLOB_DOTS  is  explicitly
2580       switched off) except for lex.c, lex.h, parse.c and parse.h.
2581
2582              print -rC1 b*.pro(#q:s/pro/shmo/)(#q.:s/builtin/shmiltin/)
2583
2584       demonstrates  how  colon  modifiers and other qualifiers may be chained
2585       together.  The ordinary qualifier `.' is applied first, then the  colon
2586       modifiers  in order from left to right.  So if EXTENDED_GLOB is set and
2587       the base pattern matches the regular file builtin.pro, the  shell  will
2588       print `shmiltin.shmo'.
2589
2590
2591
2592zsh 5.8.1                      February 12, 2022                    ZSHEXPN(1)
Impressum