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 one step in left-to-right fashion.
25              After these expansions, all unquoted occurrences of the  charac‐
26              ters `\', `'' and `"' are removed.
27
28       Filename Expansion
29              If  the  SH_FILE_EXPANSION option is set, the order of expansion
30              is modified for compatibility with sh and  ksh.   In  that  case
31              filename  expansion  is performed immediately after alias expan‐
32              sion, preceding the set of five expansions mentioned above.
33
34       Filename Generation
35              This expansion, commonly referred to as globbing, is always done
36              last.
37
38       The following sections explain the types of expansion in detail.
39

HISTORY EXPANSION

41       History  expansion  allows you to use words from previous command lines
42       in the command line you are typing.  This simplifies  spelling  correc‐
43       tions and the repetition of complicated commands or arguments.  Immedi‐
44       ately before execution, each command is saved in the history list,  the
45       size  of  which  is controlled by the HISTSIZE parameter.  The one most
46       recent command is always retained in any case.  Each saved  command  in
47       the  history  list  is called a history event and is assigned a number,
48       beginning with 1 (one) when the shell starts up.   The  history  number
49       that  you  may see in your prompt (see EXPANSION OF PROMPT SEQUENCES in
50       zshmisc(1)) is the number that is to be assigned to the next command.
51
52   Overview
53       A history expansion begins with the first character  of  the  histchars
54       parameter,  which is `!' by default, and may occur anywhere on the com‐
55       mand line; history expansions do not nest.  The `!' can be escaped with
56       `\' or can be enclosed between a pair of single quotes ('') to suppress
57       its special meaning.  Double quotes will not work for this.   Following
58       this history character is an optional event designator (see the section
59       `Event Designators') and then an optional word designator (the  section
60       `Word  Designators');  if  neither  of these designators is present, no
61       history expansion occurs.
62
63       Input lines  containing  history  expansions  are  echoed  after  being
64       expanded,  but  before  any  other expansions take place and before the
65       command is executed.  It is this expanded form that is recorded as  the
66       history event for later references.
67
68       By  default, a history reference with no event designator refers to the
69       same event as any preceding history reference on that command line;  if
70       it  is the only history reference in a command, it refers to the previ‐
71       ous command.  However, if the option CSH_JUNKIE_HISTORY  is  set,  then
72       every  history  reference  with no event specification always refers to
73       the previous command.
74
75       For example, `!' is the event designator for the previous  command,  so
76       `!!:1'  always  refers  to  the first word of the previous command, and
77       `!!$' always refers to the last word of  the  previous  command.   With
78       CSH_JUNKIE_HISTORY set, then `!:1' and `!$' function in the same manner
79       as `!!:1' and `!!$', respectively.  Conversely,  if  CSH_JUNKIE_HISTORY
80       is  unset,  then  `!:1'  and  `!$'  refer  to the first and last words,
81       respectively, of the same event referenced by the nearest other history
82       reference  preceding them on the current command line, or to the previ‐
83       ous command if there is no preceding reference.
84
85       The character sequence `^foo^bar' (where `^'  is  actually  the  second
86       character of the histchars parameter) repeats the last command, replac‐
87       ing the string foo with bar.  More precisely, the sequence  `^foo^bar^'
88       is synonymous with `!!:s^foo^bar^', hence other modifiers (see the sec‐
89       tion  `Modifiers')  may  follow  the   final   `^'.    In   particular,
90       `^foo^bar:G' performs a global substitution.
91
92       If  the  shell encounters the character sequence `!"' in the input, the
93       history mechanism is temporarily disabled until the current  list  (see
94       zshmisc(1))  is  fully parsed.  The `!"' is removed from the input, and
95       any subsequent `!' characters have no special significance.
96
97       A less convenient but more comprehensible form of command history  sup‐
98       port is provided by the fc builtin.
99
100   Event Designators
101       An  event designator is a reference to a command-line entry in the his‐
102       tory list.  In the list below, remember that the initial  `!'  in  each
103       item  may  be  changed  to  another  character by setting the histchars
104       parameter.
105
106       !      Start a history expansion, except when followed by a blank, new‐
107              line,  `=' or `('.  If followed immediately by a word designator
108              (see the section `Word Designators'), this forms a history  ref‐
109              erence with no event designator (see the section `Overview').
110
111       !!     Refer  to  the  previous  command.   By  itself,  this expansion
112              repeats the previous command.
113
114       !n     Refer to command-line n.
115
116       !-n    Refer to the current command-line minus n.
117
118       !str   Refer to the most recent command starting with str.
119
120       !?str[?]
121              Refer to the most recent command containing str.   The  trailing
122              `?'  is necessary if this reference is to be followed by a modi‐
123              fier or followed by any text that is not to be  considered  part
124              of str.
125
126       !#     Refer  to the current command line typed in so far.  The line is
127              treated as if it were complete up  to  and  including  the  word
128              before the one with the `!#' reference.
129
130       !{...} Insulate a history reference from adjacent characters (if neces‐
131              sary).
132
133   Word Designators
134       A word designator indicates which word or words of a given command line
135       are to be included in a history reference.  A `:' usually separates the
136       event specification from the word designator.  It may be  omitted  only
137       if  the  word designator begins with a `^', `$', `*', `-' or `%'.  Word
138       designators include:
139
140       0      The first input word (command).
141       n      The nth argument.
142       ^      The first argument.  That is, 1.
143       $      The last argument.
144       %      The word matched by (the most recent) ?str search.
145       x-y    A range of words; x defaults to 0.
146       *      All the arguments, or a null value if there are none.
147       x*     Abbreviates `x-$'.
148       x-     Like `x*' but omitting word $.
149
150       Note that a `%' word designator works only when used in  one  of  `!%',
151       `!:%'  or `!?str?:%', and only when used after a !? expansion (possibly
152       in an earlier command).  Anything else results in  an  error,  although
153       the error may not be the most obvious one.
154
155   Modifiers
156       After  the  optional  word designator, you can add a sequence of one or
157       more of the following modifiers, each preceded by a `:'.   These  modi‐
158       fiers  also  work  on  the  result of filename generation and parameter
159       expansion, except where noted.
160
161       a      Turn a file name into an absolute path:   prepends  the  current
162              directory, if necessary, and resolves any use of `..' and `.' in
163              the path.  Note that the transformation takes place even if  the
164              file or any intervening directories do not exist.
165
166       A      As  `a',  but also resolve use of symbolic links where possible.
167              Note that resolution of `..' occurs before  resolution  of  sym‐
168              bolic  links.   This  call is equivalent to a unless your system
169              has the realpath system call (modern systems do).
170
171       c      Resolve a command name into an absolute path  by  searching  the
172              command path given by the PATH variable.  This does not work for
173              commands containing directory parts.  Note also that  this  does
174              not  usually  work as a glob qualifier unless a file of the same
175              name is found in the current directory.
176
177       e      Remove all but the extension.
178
179       h      Remove a trailing pathname component, leaving  the  head.   This
180              works like `dirname'.
181
182       l      Convert the words to all lowercase.
183
184       p      Print  the  new  command but do not execute it.  Only works with
185              history expansion.
186
187       q      Quote the substituted  words,  escaping  further  substitutions.
188              Works with history expansion and parameter expansion, though for
189              parameters it is only useful if the  resulting  text  is  to  be
190              re-evaluated such as by eval.
191
192       Q      Remove one level of quotes from the substituted words.
193
194       r      Remove a filename extension of the form `.xxx', leaving the root
195              name.
196
197       s/l/r[/]
198              Substitute r for l as described below.  The substitution is done
199              only  for  the  first string that matches l.  For arrays and for
200              filename generation, this applies to each word of  the  expanded
201              text.  See below for further notes on substitutions.
202
203              The  forms  `gs/l/r' and `s/l/r/:G' perform global substitution,
204              i.e. substitute every occurrence of r for l.  Note that the g or
205              :G must appear in exactly the position shown.
206
207       &      Repeat  the  previous  s  substitution.  Like s, may be preceded
208              immediately by a g.  In parameter expansion the  &  must  appear
209              inside braces, and in filename generation it must be quoted with
210              a backslash.
211
212       t      Remove all leading pathname components, leaving the tail.   This
213              works like `basename'.
214
215       u      Convert the words to all uppercase.
216
217       x      Like  q, but break into words at whitespace.  Does not work with
218              parameter expansion.
219
220       The s/l/r/ substitution works as follows.   By  default  the  left-hand
221       side  of  substitutions  are  not patterns, but character strings.  Any
222       character can be used as the delimiter in place of  `/'.   A  backslash
223       quotes   the   delimiter   character.    The   character  `&',  in  the
224       right-hand-side r, is replaced by the text from the  left-hand-side  l.
225       The  `&'  can  be  quoted with a backslash.  A null l uses the previous
226       string either from the previous l or from the contextual scan string  s
227       from  `!?s'.  You can omit the rightmost delimiter if a newline immedi‐
228       ately follows r; the rightmost `?' in a context scan can  similarly  be
229       omitted.  Note the same record of the last l and r is maintained across
230       all forms of expansion.
231
232       If the option HIST_SUBST_PATTERN is set, l is treated as a  pattern  of
233       the  usual  form  described  in  the section FILENAME GENERATION below.
234       This can be used in all the places where modifiers are available; note,
235       however, that in globbing qualifiers parameter substitution has already
236       taken place, so parameters in the replacement string should  be  quoted
237       to  ensure  they are replaced at the correct time.  Note also that com‐
238       plicated patterns used in globbing qualifiers  may  need  the  extended
239       glob  qualifier notation (#q:s/.../.../) in order for the shell to rec‐
240       ognize the expression as a glob qualifier.  Further, note that bad pat‐
241       terns  in the substitution are not subject to the NO_BAD_PATTERN option
242       so will cause an error.
243
244       When HIST_SUBST_PATTERN is set, l may start with a # to  indicate  that
245       the  pattern  must  match at the start of the string to be substituted,
246       and a % may appear at the start or after an # to indicate that the pat‐
247       tern must match at the end of the string to be substituted.  The % or #
248       may be quoted with two backslashes.
249
250       For example, the following piece of filename generation code  with  the
251       EXTENDED_GLOB option:
252
253              print *.c(#q:s/#%(#b)s(*).c/'S${match[1]}.C'/)
254
255       takes  the  expansion  of  *.c  and  applies the glob qualifiers in the
256       (#q...) expression, which consists of a substitution modifier  anchored
257       to  the  start and end of each word (#%).  This turns on backreferences
258       ((#b)), so that the parenthesised subexpression  is  available  in  the
259       replacement string as ${match[1]}.  The replacement string is quoted so
260       that the parameter is not substituted before the start of filename gen‐
261       eration.
262
263       The  following  f, F, w and W modifiers work only with parameter expan‐
264       sion and filename generation.  They are listed here to provide a single
265       point of reference for all modifiers.
266
267       f      Repeats  the  immediately  (without  a colon) following modifier
268              until the resulting word doesn't change any more.
269
270       F:expr:
271              Like f, but repeats only n times if the expression  expr  evalu‐
272              ates  to  n.   Any  character can be used instead of the `:'; if
273              `(', `[', or `{' is used as the opening delimiter,  the  closing
274              delimiter should be ')', `]', or `}', respectively.
275
276       w      Makes  the  immediately  following modifier work on each word in
277              the string.
278
279       W:sep: Like w but words are considered to be the parts  of  the  string
280              that  are separated by sep. Any character can be used instead of
281              the `:'; opening parentheses are handled specially, see above.
282

PROCESS SUBSTITUTION

284       Each part  of  a  command  argument  that  takes  the  form  `<(list)',
285       `>(list)' or `=(list)' is subject to process substitution.  The expres‐
286       sion may be preceeded or followed by other strings except that, to pre‐
287       vent  clashes  with  commonly  occurring strings and patterns, the last
288       form must occur at the start of a command argument, and the  forms  are
289       only  expanded  when  first  parsing  command  or assignment arguments.
290       Process substitutions may be used following redirection  operators;  in
291       this case, the substitution must appear with no trailing string.
292
293       In  the  case  of the < or > forms, the shell runs the commands in list
294       asynchronously.  If the system supports the /dev/fd mechanism, the com‐
295       mand  argument  is  the name of the device file corresponding to a file
296       descriptor; otherwise, if the system supports named pipes (FIFOs),  the
297       command  argument will be a named pipe.  If the form with > is selected
298       then writing on this special file will provide input for list.  If < is
299       used, then the file passed as an argument will be connected to the out‐
300       put of the list process.  For example,
301
302              paste <(cut -f1 file1) <(cut -f3 file2) |
303              tee >(process1) >(process2) >/dev/null
304
305       cuts fields 1 and 3 from the files file1 and file2 respectively, pastes
306       the  results  together,  and  sends  it  to  the processes process1 and
307       process2.
308
309       If =(...) is used instead of <(...), then the file passed as  an  argu‐
310       ment  will be the name of a temporary file containing the output of the
311       list process.  This may be used instead of the <  form  for  a  program
312       that expects to lseek (see lseek(2)) on the input file.
313
314       There is an optimisation for substitutions of the form =(<<<arg), where
315       arg is a single-word argument to the here-string redirection <<<.  This
316       form produces a file name containing the value of arg after any substi‐
317       tutions have been performed.  This is handled entirely within the  cur‐
318       rent  shell.   This  is  effectively  the  reverse  of the special form
319       $(<arg) which treats arg as a file name and replaces it with the file's
320       contents.
321
322       The = form is useful as both the /dev/fd and the named pipe implementa‐
323       tion of <(...) have drawbacks.  In the former case, some programmes may
324       automatically  close  the  file descriptor in question before examining
325       the file on the command line, particularly if  this  is  necessary  for
326       security  reasons such as when the programme is running setuid.  In the
327       second case, if the programme does not actually open the file, the sub‐
328       shell  attempting  to read from or write to the pipe will (in a typical
329       implementation, different operating systems may have  different  behav‐
330       iour)  block for ever and have to be killed explicitly.  In both cases,
331       the shell actually supplies the information using a pipe, so that  pro‐
332       grammes that expect to lseek (see lseek(2)) on the file will not work.
333
334       Also  note  that  the  previous example can be more compactly and effi‐
335       ciently written (provided the MULTIOS option is set) as:
336
337              paste <(cut -f1 file1) <(cut -f3 file2) \
338              > >(process1) > >(process2)
339
340       The shell uses pipes instead of  FIFOs  to  implement  the  latter  two
341       process substitutions in the above example.
342
343       There  is  an additional problem with >(process); when this is attached
344       to an external command, the parent shell does not wait for  process  to
345       finish  and  hence  an immediately following command cannot rely on the
346       results being complete.  The problem  and  solution  are  the  same  as
347       described  in the section MULTIOS in zshmisc(1).  Hence in a simplified
348       version of the example above:
349
350              paste <(cut -f1 file1) <(cut -f3 file2) > >(process)
351
352       (note that  no  MULTIOS  are  involved),  process  will  be  run  asyn‐
353       chronously.  The workaround is:
354
355              { paste <(cut -f1 file1) <(cut -f3 file2) } > >(process)
356
357       The  extra  processes here are spawned from the parent shell which will
358       wait for their completion.
359

PARAMETER EXPANSION

361       The character `$' is used to introduce parameter expansions.  See  zsh‐
362       param(1) for a description of parameters, including arrays, associative
363       arrays, and subscript notation to access individual array elements.
364
365       Note in particular the fact that words of unquoted parameters  are  not
366       automatically  split  on  whitespace unless the option SH_WORD_SPLIT is
367       set; see references to this option below for more details.  This is  an
368       important difference from other shells.
369
370       In  the  expansions discussed below that require a pattern, the form of
371       the pattern is the same as that used for filename generation;  see  the
372       section  `Filename  Generation'.   Note that these patterns, along with
373       the replacement text of any substitutions, are  themselves  subject  to
374       parameter  expansion,  command  substitution, and arithmetic expansion.
375       In addition to the following operations, the colon modifiers  described
376       in  the  section  `Modifiers' in the section `History Expansion' can be
377       applied:  for example, ${i:s/foo/bar/} performs string substitution  on
378       the expansion of parameter $i.
379
380       ${name}
381              The  value,  if  any, of the parameter name is substituted.  The
382              braces are required if the expansion is to be followed by a let‐
383              ter,  digit, or underscore that is not to be interpreted as part
384              of name.  In addition, more complicated  forms  of  substitution
385              usually require the braces to be present; exceptions, which only
386              apply if the option KSH_ARRAYS is not set,  are  a  single  sub‐
387              script  or  any colon modifiers appearing after the name, or any
388              of the characters `^', `=', `~', `#' or `+' appearing before the
389              name, all of which work with or without braces.
390
391              If  name is an array parameter, and the KSH_ARRAYS option is not
392              set, then the value of each element of name is substituted,  one
393              element  per word.  Otherwise, the expansion results in one word
394              only; with KSH_ARRAYS, this is the first element  of  an  array.
395              No   field   splitting   is   done  on  the  result  unless  the
396              SH_WORD_SPLIT  option  is  set.   See  also  the  flags  =   and
397              s:string:.
398
399       ${+name}
400              If  name is the name of a set parameter `1' is substituted, oth‐
401              erwise `0' is substituted.
402
403       ${name-word}
404       ${name:-word}
405              If name is set, or in the second form is non-null, then  substi‐
406              tute  its  value; otherwise substitute word.  In the second form
407              name may be omitted, in which case word is always substituted.
408
409       ${name+word}
410       ${name:+word}
411              If name is set, or in the second form is non-null, then  substi‐
412              tute word; otherwise substitute nothing.
413
414       ${name=word}
415       ${name:=word}
416       ${name::=word}
417              In  the first form, if name is unset then set it to word; in the
418              second form, if name is unset or null then set it to  word;  and
419              in  the  third  form,  unconditionally set name to word.  In all
420              forms, the value of the parameter is then substituted.
421
422       ${name?word}
423       ${name:?word}
424              In the first form, if name is set, or in the second form if name
425              is  both set and non-null, then substitute its value; otherwise,
426              print word and exit from the shell.  Interactive shells  instead
427              return  to the prompt.  If word is omitted, then a standard mes‐
428              sage is printed.
429
430       In any of the above expressions that test a variable and substitute  an
431       alternate  word,  note  that  you can use standard shell quoting in the
432       word  value  to  selectively  override  the  splitting  done   by   the
433       SH_WORD_SPLIT option and the = flag, but not splitting by the s:string:
434       flag.
435
436       In the following expressions, when name is an array and  the  substitu‐
437       tion is not quoted, or if the `(@)' flag or the name[@] syntax is used,
438       matching and replacement is performed on each array element separately.
439
440       ${name#pattern}
441       ${name##pattern}
442              If the pattern matches the beginning of the value of name,  then
443              substitute  the  value of name with the matched portion deleted;
444              otherwise, just substitute the value  of  name.   In  the  first
445              form,  the smallest matching pattern is preferred; in the second
446              form, the largest matching pattern is preferred.
447
448       ${name%pattern}
449       ${name%%pattern}
450              If the pattern matches the end of the value of name,  then  sub‐
451              stitute the value of name with the matched portion deleted; oth‐
452              erwise, just substitute the value of name.  In the  first  form,
453              the  smallest matching pattern is preferred; in the second form,
454              the largest matching pattern is preferred.
455
456       ${name:#pattern}
457              If the pattern matches the value of name,  then  substitute  the
458              empty  string; otherwise, just substitute the value of name.  If
459              name is an array the matching array elements  are  removed  (use
460              the `(M)' flag to remove the non-matched elements).
461
462       ${name/pattern/repl}
463       ${name//pattern/repl}
464              Replace  the  longest possible match of pattern in the expansion
465              of parameter name by string repl.  The first form replaces  just
466              the  first  occurrence,  the  second form all occurrences.  Both
467              pattern and repl are subject to double-quoted  substitution,  so
468              that  expressions  like  ${name/$opat/$npat} will work, but note
469              the usual rule that pattern characters in $opat are not  treated
470              specially  unless  either the option GLOB_SUBST is set, or $opat
471              is instead substituted as ${~opat}.
472
473              The pattern may begin with a `#', in which case the pattern must
474              match  at the start of the string, or `%', in which case it must
475              match at the end of the string, or `#%' in which case  the  pat‐
476              tern  must  match  the  entire string.  The repl may be an empty
477              string, in which case the final `/' may  also  be  omitted.   To
478              quote  the  final  `/' in other cases it should be preceded by a
479              single backslash; this is not necessary if the `/' occurs inside
480              a  substituted  parameter.   Note also that the `#', `%' and `#%
481              are not active if they occur  inside  a  substituted  parameter,
482              even at the start.
483
484              The  first `/' may be preceded by a `:', in which case the match
485              will only succeed if it matches the entire word.  Note also  the
486              effect  of the I and S parameter expansion flags below; however,
487              the flags M, R, B, E and N are not useful.
488
489              For example,
490
491                     foo="twinkle twinkle little star" sub="t*e" rep="spy"
492                     print ${foo//${~sub}/$rep}
493                     print ${(S)foo//${~sub}/$rep}
494
495              Here, the `~' ensures that the text of $sub is treated as a pat‐
496              tern rather than a plain string.  In the first case, the longest
497              match for t*e is substituted and the result is `spy star', while
498              in  the  second  case,  the  shortest  matches are taken and the
499              result is `spy spy lispy star'.
500
501       ${#spec}
502              If spec is one of the above substitutions, substitute the length
503              in  characters  of  the result instead of the result itself.  If
504              spec is an array expression, substitute the number  of  elements
505              of  the result.  Note that `^', `=', and `~', below, must appear
506              to the left of `#' when these forms are combined.
507
508       ${^spec}
509              Turn on the RC_EXPAND_PARAM option for the evaluation  of  spec;
510              if  the  `^'  is doubled, turn it off.  When this option is set,
511              array expansions of the form foo${xx}bar, where the parameter xx
512              is  set  to  (a  b  c),  are  substituted  with `fooabar foobbar
513              foocbar' instead of the default `fooa b  cbar'.   Note  that  an
514              empty array will therefore cause all arguments to be removed.
515
516              Internally, each such expansion is converted into the equivalent
517              list   for   brace    expansion.     E.g.,    ${^var}    becomes
518              {$var[1],$var[2],...}, and is processed as described in the sec‐
519              tion `Brace Expansion' below.  If  word  splitting  is  also  in
520              effect  the  $var[N] may themselves be split into different list
521              elements.
522
523       ${=spec}
524              Perform word splitting using the rules for SH_WORD_SPLIT  during
525              the  evaluation of spec, but regardless of whether the parameter
526              appears in double quotes; if the `=' is doubled,  turn  it  off.
527              This forces parameter expansions to be split into separate words
528              before substitution, using IFS as a delimiter.  This is done  by
529              default in most other shells.
530
531              Note  that  splitting is applied to word in the assignment forms
532              of spec before  the  assignment  to  name  is  performed.   This
533              affects the result of array assignments with the A flag.
534
535       ${~spec}
536              Turn on the GLOB_SUBST option for the evaluation of spec; if the
537              `~' is doubled, turn it off.   When  this  option  is  set,  the
538              string  resulting  from  the  expansion will be interpreted as a
539              pattern anywhere that is possible, such as in filename expansion
540              and  filename  generation and pattern-matching contexts like the
541              right hand side of the `=' and `!=' operators in conditions.
542
543              In nested substitutions, note that the effect of the  ~  applies
544              to the result of the current level of substitution.  A surround‐
545              ing pattern operation on the result may cancel it.   Hence,  for
546              example,  if  the  parameter foo is set to *, ${~foo//\*/*.c} is
547              substituted by the pattern *.c, which may be expanded  by  file‐
548              name  generation,  but  ${${~foo}//\*/*.c}  substitutes  to  the
549              string *.c, which will not be further expanded.
550
551       If a ${...} type parameter expression or a $(...) type command  substi‐
552       tution  is  used  in  place of name above, it is expanded first and the
553       result is used as if it were the value of name.  Thus it is possible to
554       perform  nested  operations:  ${${foo#head}%tail} substitutes the value
555       of $foo with both `head' and `tail' deleted.  The form with  $(...)  is
556       often  useful  in  combination  with  the flags described next; see the
557       examples below.  Each name or nested ${...} in  a  parameter  expansion
558       may  also  be  followed by a subscript expression as described in Array
559       Parameters in zshparam(1).
560
561       Note that double quotes may appear around nested expressions, in  which
562       case   only  the  part  inside  is  treated  as  quoted;  for  example,
563       ${(f)"$(foo)"} quotes the result of $(foo), but  the  flag  `(f)'  (see
564       below)  is  applied using the rules for unquoted expansions.  Note fur‐
565       ther that quotes are themselves nested in this context; for example, in
566       "${(@f)"$(foo)"}",  there  are  two sets of quotes, one surrounding the
567       whole expression, the  other  (redundant)  surrounding  the  $(foo)  as
568       before.
569
570   Parameter Expansion Flags
571       If  the  opening  brace is directly followed by an opening parenthesis,
572       the string up to the matching closing parenthesis will be  taken  as  a
573       list of flags.  In cases where repeating a flag is meaningful, the rep‐
574       etitions need not be consecutive; for example, `(q%q%q)' means the same
575       thing  as  the  more  readable `(%%qqq)'.  The following flags are sup‐
576       ported:
577
578       #      Evaluate the resulting words as numeric expressions  and  output
579              the  characters  corresponding  to  the resulting integer.  Note
580              that this form is entirely distinct from use of  the  #  without
581              parentheses.
582
583              If  the  MULTIBYTE  option is set and the number is greater than
584              127 (i.e. not an ASCII character) it is  treated  as  a  Unicode
585              character.
586
587       %      Expand  all  % escapes in the resulting words in the same way as
588              in prompts (see EXPANSION OF PROMPT SEQUENCES in zshmisc(1)). If
589              this  flag  is given twice, full prompt expansion is done on the
590              resulting words, depending on the setting of the PROMPT_PERCENT,
591              PROMPT_SUBST and PROMPT_BANG options.
592
593       @      In  double  quotes,  array elements are put into separate words.
594              E.g.,  `"${(@)foo}"'  is   equivalent   to   `"${foo[@]}"'   and
595              `"${(@)foo[1,2]}"'  is  the same as `"$foo[1]" "$foo[2]"'.  This
596              is distinct from field splitting by the the f,  s  or  z  flags,
597              which still applies within each array element.
598
599       A      Create  an  array  parameter with `${...=...}', `${...:=...}' or
600              `${...::=...}'.  If this flag is repeated (as in  `AA'),  create
601              an associative array parameter.  Assignment is made before sort‐
602              ing or padding.  The name part may be a  subscripted  range  for
603              ordinary  arrays;  the  word part must be converted to an array,
604              for example by using `${(AA)=name=...}' to activate field split‐
605              ting, when creating an associative array.
606
607       a      Sort  in  array  index  order;  when  combined  with `O' sort in
608              reverse array index order.  Note that `a' is  therefore  equiva‐
609              lent  to the default but `Oa' is useful for obtaining an array's
610              elements in reverse order.
611
612       c      With ${#name}, count the total number of characters in an array,
613              as if the elements were concatenated with spaces between them.
614
615       C      Capitalize  the resulting words.  `Words' in this case refers to
616              sequences of alphanumeric characters separated  by  non-alphanu‐
617              merics, not to words that result from field splitting.
618
619       e      Perform parameter expansion, command substitution and arithmetic
620              expansion on the result. Such expansions can be nested  but  too
621              deep recursion may have unpredictable effects.
622
623       f      Split  the result of the expansion to lines. This is a shorthand
624              for `ps:\n:'.
625
626       F      Join the words of arrays together using newline as a  separator.
627              This is a shorthand for `pj:\n:'.
628
629       i      Sort case-insensitively.  May be combined with `n' or `O'.
630
631       k      If  name  refers  to  an  associative array, substitute the keys
632              (element names) rather than the values of  the  elements.   Used
633              with  subscripts  (including  ordinary arrays), force indices or
634              keys to be substituted even if the subscript form refers to val‐
635              ues.   However,  this  flag  may  not be combined with subscript
636              ranges.
637
638       L      Convert all letters in the result to lower case.
639
640       n      Sort decimal integers numerically; if the first differing  char‐
641              acters  of  two test strings are not digits, sorting is lexical.
642              Integers with more initial zeroes are sorted before  those  with
643              fewer  or  none.   Hence  the  array `foo1 foo02 foo2 foo3 foo20
644              foo23' is sorted into the order shown.  May be combined with `i'
645              or `O'.
646
647       o      Sort  the resulting words in ascending order; if this appears on
648              its own the sorting is lexical and  case-sensitive  (unless  the
649              locale renders it case-insensitive).  Sorting in ascending order
650              is the default for other forms of sorting, so this is ignored if
651              combined with `a', `i' or `n'.
652
653       O      Sort  the  resulting words in descending order; `O' without `a',
654              `i' or `n' sorts in reverse lexical order.  May be combined with
655              `a', `i' or `n' to reverse the order of sorting.
656
657       P      This forces the value of the parameter name to be interpreted as
658              a further parameter name, whose value will be used where  appro‐
659              priate.   Note  that flags set with one of the typeset family of
660              commands (in particular case transformations) are not applied to
661              the value of name used in this fashion.
662
663              If  used  with  a  nested parameter or command substitution, the
664              result of that will be taken as a parameter  name  in  the  same
665              way.   For  example,  if  you  have `foo=bar' and `bar=baz', the
666              strings ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo bar)}  will  be
667              expanded to `baz'.
668
669       q      Quote  the  resulting  words  with  backslashes;  unprintable or
670              invalid characters are quoted using the $'\NNN' form, with sepa‐
671              rate  quotes  for  each octet.  If this flag is given twice, the
672              resulting words are quoted in single quotes and if it  is  given
673              three  times,  the  words  are quoted in double quotes; in these
674              forms no special handling of unprintable or  invalid  characters
675              is  attempted.   If  the flag is given four times, the words are
676              quoted in single quotes preceded by a $.
677
678       Q      Remove one level of quotes from the resulting words.
679
680       t      Use a string describing the type  of  the  parameter  where  the
681              value  of  the  parameter would usually appear. This string con‐
682              sists of keywords separated by hyphens (`-'). The first  keyword
683              in  the  string  describes  the  main  type,  it  can  be one of
684              `scalar', `array',  `integer',  `float'  or  `association'.  The
685              other keywords describe the type in more detail:
686
687              local  for local parameters
688
689              left   for left justified parameters
690
691              right_blanks
692                     for right justified parameters with leading blanks
693
694              right_zeros
695                     for right justified parameters with leading zeros
696
697              lower  for parameters whose value is converted to all lower case
698                     when it is expanded
699
700              upper  for parameters whose value is converted to all upper case
701                     when it is expanded
702
703              readonly
704                     for readonly parameters
705
706              tag    for tagged parameters
707
708              export for exported parameters
709
710              unique for arrays which keep only the first occurrence of dupli‐
711                     cated values
712
713              hide   for parameters with the `hide' flag
714
715              special
716                     for special parameters defined by the shell
717
718       u      Expand only the first occurrence of each unique word.
719
720       U      Convert all letters in the result to upper case.
721
722       v      Used with k, substitute (as two consecutive words) both the  key
723              and the value of each associative array element.  Used with sub‐
724              scripts, force values to be substituted even  if  the  subscript
725              form refers to indices or keys.
726
727       V      Make any special characters in the resulting words visible.
728
729       w      With  ${#name}, count words in arrays or strings; the s flag may
730              be used to set a word delimiter.
731
732       W      Similar to w  with  the  difference  that  empty  words  between
733              repeated delimiters are also counted.
734
735       X      With  this  flag,  parsing  errors occurring with the Q, e and #
736              flags or the pattern matching forms  such  as  `${name#pattern}'
737              are reported.  Without the flag, errors are silently ignored.
738
739       z      Split the result of the expansion into words using shell parsing
740              to find the words, i.e. taking into account any quoting  in  the
741              value.
742
743              Note  that  this is done very late, as for the `(s)' flag. So to
744              access single words in the result, one has to use nested  expan‐
745              sions as in `${${(z)foo}[2]}'. Likewise, to remove the quotes in
746              the resulting words one would do: `${(Q)${(z)foo}}'.
747
748       0      Split the result of the expansion on  null  bytes.   This  is  a
749              shorthand for `ps:\0:'.
750
751       The following flags (except p) are followed by one or more arguments as
752       shown.  Any character, or the matching pairs `(...)', `{...}', `[...]',
753       or  `<...>',  may  be  used in place of a colon as delimiters, but note
754       that when a flag takes more than one argument, a matched pair of delim‐
755       iters must surround each argument.
756
757       p      Recognize  the  same  escape  sequences  as the print builtin in
758              string arguments to any of the flags described below that follow
759              this argument.
760
761       ~      Force  string  arguments  to  any of the flags below that follow
762              within the parentheses to be treated as patterns.  Compare  with
763              a  ~  outside  parentheses,  which forces the entire substituted
764              string to be treated as a pattern.  Hence, for example,
765              [[ "?" = ${(~j.|.)array} ]]
766       with the EXTENDED_GLOB option set succeeds if and only if  $array  con‐
767       tains  the  string  `?' as an element.  The argument may be repeated to
768       toggle the behaviour; its effect only lasts to the end of the parenthe‐
769       sised group.
770
771       j:string:
772              Join  the  words of arrays together using string as a separator.
773              Note that this occurs before field splitting  by  the  s:string:
774              flag or the SH_WORD_SPLIT option.
775
776       l:expr::string1::string2:
777              Pad  the  resulting  words on the left.  Each word will be trun‐
778              cated if required and placed in a field expr characters wide.
779
780              The arguments :string1: and :string2: are optional; neither, the
781              first, or both may be given.  Note that the same pairs of delim‐
782              iters must be used for each of the three arguments.   The  space
783              to  the  left will be filled with string1 (concatenated as often
784              as needed) or spaces if string1 is not given.  If  both  string1
785              and  string2 are given, string2 is inserted once directly to the
786              left of each word, truncated if  necessary,  before  string1  is
787              used to produce any remaining padding.
788
789              If  the  MULTIBYTE  option  is in effect, the flag m may also be
790              given, in which case widths will be used for the calculation  of
791              padding;  otherwise  individual multibyte characters are treated
792              as occupying one unit of width.
793
794              IF the MULTIBYTE option is not  in  effect,  each  byte  in  the
795              string is treated as occupying one unit of width.
796
797              Control  characters are always assumed to be one unit wide; this
798              allows the mechanism to be used for  generating  repetitions  of
799              control characters.
800
801       m      Only  useful together with one of the flags l or r or with the #
802              length operator when the MULTIBYTE option is in effect.  Use the
803              character  width  reported  by the system in calculating the how
804              much of the string it occupies or  the  overall  length  of  the
805              string.   Most  printable  characters  have a width of one unit,
806              however certain Asian character sets and certain special effects
807              use wider characters; combining characters have zero width.
808
809       r:expr::string1::string2:
810              As  l, but pad the words on the right and insert string2 immedi‐
811              ately to the right of the string to be padded.
812
813              Left and right padding may be used together.  In this  case  the
814              strategy  is  to  apply  left padding to the first half width of
815              each of the resulting words, and right  padding  to  the  second
816              half.   If  the string to be padded has odd width the extra pad‐
817              ding is applied on the left.
818
819       s:string:
820              Force field splitting at the  separator  string.   Note  that  a
821              string  of  two  or  more characters means that all of them must
822              match in sequence; this differs from the  treatment  of  two  or
823              more  characters  in the IFS parameter.  See also the = flag and
824              the SH_WORD_SPLIT option.
825
826              For historical reasons, the usual  behaviour  that  empty  array
827              elements  are  retained  inside  double  quotes  is disabled for
828              arrays generated by splitting; hence the following:
829
830                     line="one::three"
831                     print -l "${(s.:.)line}"
832
833              produces two lines of output for one and three  and  elides  the
834              empty  field.  To override this behaviour, supply the "(@)" flag
835              as well, i.e.  "${(@s.:.)line}".
836
837       The following flags are meaningful with the  ${...#...}  or  ${...%...}
838       forms.  The S and I flags may also be used with the ${.../...} forms.
839
840       S      Search  substrings  as  well as beginnings or ends; with # start
841              from the beginning and with % start from the end of the  string.
842              With  substitution  via  ${.../...}  or  ${...//...},  specifies
843              non-greedy matching, i.e. that the shortest instead of the long‐
844              est match should be replaced.
845
846       I:expr:
847              Search  the  exprth  match  (where  expr evaluates to a number).
848              This only applies when searching for substrings, either with the
849              S  flag,  or  with  ${.../...} (only the exprth match is substi‐
850              tuted) or ${...//...} (all matches from the exprth on  are  sub‐
851              stituted).  The default is to take the first match.
852
853              The  exprth  match  is  counted such that there is either one or
854              zero matches from each starting position in the string, although
855              for  global  substitution  matches overlapping previous replace‐
856              ments are ignored.  With the ${...%...} and  ${...%%...}  forms,
857              the starting position for the match moves backwards from the end
858              as the index increases, while with the other forms it moves for‐
859              ward from the start.
860
861              Hence with the string
862                     which switch is the right switch for Ipswich?
863              substitutions  of  the form ${(SI:N:)string#w*ch} as N increases
864              from 1 will match  and  remove  `which',  `witch',  `witch'  and
865              `wich';  the form using `##' will match and remove `which switch
866              is the right switch for Ipswich', `witch is the right switch for
867              Ipswich',  `witch  for  Ipswich'  and `wich'. The form using `%'
868              will remove the same matches as for `#', but in  reverse  order,
869              and the form using `%%' will remove the same matches as for `##'
870              in reverse order.
871
872       B      Include the index of the beginning of the match in the result.
873
874       E      Include the index of the end of the match in the result.
875
876       M      Include the matched portion in the result.
877
878       N      Include the length of the match in the result.
879
880       R      Include the unmatched portion in the result (the Rest).
881
882   Rules
883       Here is a summary of the rules  for  substitution;  this  assumes  that
884       braces are present around the substitution, i.e. ${...}.  Some particu‐
885       lar examples are given below.  Note  that  the  Zsh  Development  Group
886       accepts  no  responsibility for any brain damage which may occur during
887       the reading of the following rules.
888
889       1. Nested Substitution
890              If multiple nested ${...} forms  are  present,  substitution  is
891              performed  from the inside outwards.  At each level, the substi‐
892              tution takes account of whether the current value is a scalar or
893              an  array,  whether  the whole substitution is in double quotes,
894              and what flags are supplied to the current  level  of  substitu‐
895              tion,  just  as  if  the nested substitution were the outermost.
896              The flags are not propagated up to enclosing substitutions;  the
897              nested  substitution  will return either a scalar or an array as
898              determined by the flags, possibly adjusted for quoting.  All the
899              following  steps  take  place  where applicable at all levels of
900              substitution.  Note that, unless the `(P)' flag is present,  the
901              flags  and  any  subscripts  apply  directly to the value of the
902              nested  substitution;  for  example,  the  expansion   ${${foo}}
903              behaves exactly the same as ${foo}.
904
905              At  each  nested  level  of  substitution, the substituted words
906              undergo all forms of single-word substitution (i.e. not filename
907              generation),  including  command substitution, arithmetic expan‐
908              sion and filename expansion (i.e. leading ~ and =).   Thus,  for
909              example,  ${${:-=cat}:h}  expands to the directory where the cat
910              program resides.  (Explanation: the internal substitution has no
911              parameter  but  a default value =cat, which is expanded by file‐
912              name expansion to a  full  path;  the  outer  substitution  then
913              applies  the  modifier  :h  and  takes the directory part of the
914              path.)
915
916       2. Internal Parameter Flags
917              Any parameter flags set by one of the  typeset  family  of  com‐
918              mands,  in particular the L, R, Z, u and l flags for padding and
919              capitalization, are applied directly to the parameter value.
920
921       3. Parameter Subscripting
922              If the value is a raw parameter reference with a subscript, such
923              as  ${var[3]}, the effect of subscripting is applied directly to
924              the parameter.  Subscripts are evaluated left to  right;  subse‐
925              quent  subscripts  apply to the scalar or array value yielded by
926              the previous subscript.  Thus if var is an  array,  ${var[1][2]}
927              is the second character of the first word, but ${var[2,4][2]} is
928              the entire third word (the second word of the range of words two
929              through  four  of the original array).  Any number of subscripts
930              may appear.
931
932       4. Parameter Name Replacement
933              The effect of any (P) flag, which treats the value so far  as  a
934              parameter  name and replaces it with the corresponding value, is
935              applied.
936
937       5. Double-Quoted Joining
938              If the value after this process is an array, and  the  substitu‐
939              tion appears in double quotes, and no (@) flag is present at the
940              current level, the words of the value are joined with the  first
941              character  of  the  parameter  $IFS, by default a space, between
942              each word (single word arrays are not  modified).   If  the  (j)
943              flag is present, that is used for joining instead of $IFS.
944
945       6. Nested Subscripting
946              Any  remaining  subscripts  (i.e.  of a nested substitution) are
947              evaluated at this point, based on whether the value is an  array
948              or  a scalar.  As with 2., multiple subscripts can appear.  Note
949              that ${foo[2,4][2]} is thus equivalent to ${${foo[2,4]}[2]}  and
950              also  to "${${(@)foo[2,4]}[2]}" (the nested substitution returns
951              an array in both cases), but  not  to  "${${foo[2,4]}[2]}"  (the
952              nested substitution returns a scalar because of the quotes).
953
954       7. Modifiers
955              Any  modifiers, as specified by a trailing `#', `%', `/' (possi‐
956              bly doubled) or by a set of modifiers of the form :... (see  the
957              section  `Modifiers'  in  the  section `History Expansion'), are
958              applied to the words of the value at this level.
959
960       8. Forced Joining
961              If the `(j)' flag is present, or no `(j)' flag  is  present  but
962              the  string is to be split as given by rules 8. or 9., and join‐
963              ing did not take place at step 4., any words in  the  value  are
964              joined together using the given string or the first character of
965              $IFS if none.  Note that the `(F)' flag  implicitly  supplies  a
966              string for joining in this manner.
967
968       9. Forced Splitting
969              If  one  of  the `(s)', `(f)' or `(z)' flags are present, or the
970              `=' specifier was present (e.g. ${=var}), the word is  split  on
971              occurrences  of  the specified string, or (for = with neither of
972              the two flags present) any of the characters in $IFS.
973
974       10. Shell Word Splitting
975              If no `(s)', `(f)' or `=' was given, but the word is not  quoted
976              and the option SH_WORD_SPLIT is set, the word is split on occur‐
977              rences of any of the characters in $IFS.  Note this  step,  too,
978              takes place at all levels of a nested substitution.
979
980       11. Uniqueness
981              If the result is an array and the `(u)' flag was present, dupli‐
982              cate elements are removed from the array.
983
984       12. Ordering
985              If the result is still an array and one of the  `(o)'  or  `(O)'
986              flags was present, the array is reordered.
987
988       13. Re-Evaluation
989              Any  `(e)'  flag  is  applied  to  the  value,  forcing it to be
990              re-examined for new parameter substitutions, but also  for  com‐
991              mand and arithmetic substitutions.
992
993       14. Padding
994              Any padding of the value by the `(l.fill.)' or `(r.fill.)' flags
995              is applied.
996
997       15. Semantic Joining
998              In contexts where expansion semantics requires a single word  to
999              result,  all  words are rejoined with the first character of IFS
1000              between.  So in `${(P)${(f)lines}}' the  value  of  ${lines}  is
1001              split  at  newlines,  but then must be joined again before the P
1002              flag can be applied.
1003
1004              If a single word is not required, this rule is skipped.
1005
1006   Examples
1007       The flag f is useful to split  a  double-quoted  substitution  line  by
1008       line.   For  example, ${(f)"$(<file)"} substitutes the contents of file
1009       divided so that each line is an element of the resulting  array.   Com‐
1010       pare  this with the effect of $(<file) alone, which divides the file up
1011       by words, or the same inside double quotes, which makes the entire con‐
1012       tent of the file a single string.
1013
1014       The  following  illustrates  the rules for nested parameter expansions.
1015       Suppose that $foo contains the array (bar baz):
1016
1017       "${(@)${foo}[1]}"
1018              This produces the  result  b.   First,  the  inner  substitution
1019              "${foo}",  which  has  no array (@) flag, produces a single word
1020              result "bar baz".  The outer substitution "${(@)...[1]}" detects
1021              that this is a scalar, so that (despite the `(@)' flag) the sub‐
1022              script picks the first character.
1023
1024       "${${(@)foo}[1]}"
1025              This produces the result `bar'.  In this case, the inner substi‐
1026              tution  "${(@)foo}"  produces  the array `(bar baz)'.  The outer
1027              substitution "${...[1]}" detects that this is an array and picks
1028              the first word.  This is similar to the simple case "${foo[1]}".
1029
1030       As an example of the rules for word splitting and joining, suppose $foo
1031       contains the array `(ax1 bx1)'.  Then
1032
1033       ${(s/x/)foo}
1034              produces the words `a', `1 b' and `1'.
1035
1036       ${(j/x/s/x/)foo}
1037              produces `a', `1', `b' and `1'.
1038
1039       ${(s/x/)foo%%1*}
1040              produces `a' and ` b' (note the extra space).   As  substitution
1041              occurs  before either joining or splitting, the operation  first
1042              generates the modified array (ax bx), which is  joined  to  give
1043              "ax  bx",  and  then  split to give `a', ` b' and `'.  The final
1044              empty string will then be elided, as it is not in double quotes.
1045

COMMAND SUBSTITUTION

1047       A command enclosed in parentheses  preceded  by  a  dollar  sign,  like
1048       `$(...)',  or quoted with grave accents, like ``...`', is replaced with
1049       its standard output, with any trailing newlines deleted.  If  the  sub‐
1050       stitution  is  not enclosed in double quotes, the output is broken into
1051       words using the IFS parameter.  The substitution `$(cat  foo)'  may  be
1052       replaced  by  the  equivalent but faster `$(<foo)'.  In either case, if
1053       the option GLOB_SUBST is set, the output is eligible for filename  gen‐
1054       eration.
1055

ARITHMETIC EXPANSION

1057       A  string  of  the  form `$[exp]' or `$((exp))' is substituted with the
1058       value of the arithmetic expression exp.  exp is subjected to  parameter
1059       expansion,  command  substitution and arithmetic expansion before it is
1060       evaluated.  See the section `Arithmetic Evaluation'.
1061

BRACE EXPANSION

1063       A string of the form `foo{xx,yy,zz}bar' is expanded to  the  individual
1064       words  `fooxxbar',  `fooyybar'  and `foozzbar'.  Left-to-right order is
1065       preserved.  This construct may be nested.   Commas  may  be  quoted  in
1066       order to include them literally in a word.
1067
1068       An  expression of the form `{n1..n2}', where n1 and n2 are integers, is
1069       expanded to every number between n1 and n2 inclusive.  If either number
1070       begins with a zero, all the resulting numbers will be padded with lead‐
1071       ing zeroes to that minimum width.  If the  numbers  are  in  decreasing
1072       order the resulting sequence will also be in decreasing order.
1073
1074       If  a  brace  expression  matches  none  of the above forms, it is left
1075       unchanged, unless the option  BRACE_CCL  (an  abbreviation  for  `brace
1076       character  class')  is  set.  In that case, it is expanded to a list of
1077       the individual characters between the braces sorted into the  order  of
1078       the characters in the ASCII character set (multibyte characters are not
1079       currently handled).  The syntax is similar to  a  [...]  expression  in
1080       filename  generation:  `-'  is  treated  specially to denote a range of
1081       characters, but `^' or `!' as the first character is treated  normally.
1082       For  example, `{abcdef0-9}' expands to 16 words 0 1 2 3 4 5 6 7 8 9 a b
1083       c d e f.
1084
1085       Note that brace expansion is not part  of  filename  generation  (glob‐
1086       bing);  an  expression  such  as */{foo,bar} is split into two separate
1087       words */foo and */bar before filename generation takes place.  In  par‐
1088       ticular,  note  that  this  is  liable to produce a `no match' error if
1089       either of the two expressions does not match; this is to be  contrasted
1090       with  */(foo|bar),  which  is treated as a single pattern but otherwise
1091       has similar effects.
1092
1093       To combine brace expansion with array expansion, see the ${^spec}  form
1094       described in the section Parameter Expansion above.
1095

FILENAME EXPANSION

1097       Each  word  is checked to see if it begins with an unquoted `~'.  If it
1098       does, then the word up to a `/', or the end of the word if there is  no
1099       `/',  is  checked  to  see  if it can be substituted in one of the ways
1100       described here.  If so, then  the  `~'  and  the  checked  portion  are
1101       replaced with the appropriate substitute value.
1102
1103       A `~' by itself is replaced by the value of $HOME.  A `~' followed by a
1104       `+' or a `-' is replaced by the value of $PWD or $OLDPWD, respectively.
1105
1106       A `~' followed by a number is replaced by the directory at  that  posi‐
1107       tion  in  the directory stack.  `~0' is equivalent to `~+', and `~1' is
1108       the top of the stack.  `~+' followed by a number  is  replaced  by  the
1109       directory at that position in the directory stack.  `~+0' is equivalent
1110       to `~+', and `~+1' is the top of the stack.  `~-' followed by a  number
1111       is replaced by the directory that many positions from the bottom of the
1112       stack.  `~-0' is the bottom  of  the  stack.   The  PUSHD_MINUS  option
1113       exchanges  the  effects  of  `~+' and `~-' where they are followed by a
1114       number.
1115
1116   Dynamic named directories
1117       The feature described here is only  available  if  the  shell  function
1118       zsh_directory_name exists.
1119
1120       A  `~'  followed  by  a  string  namstr  in unquoted square brackets is
1121       treated specially as a dynamic directory name.   Note  that  the  first
1122       unquoted  closing  square  bracket always terminates namstr.  The shell
1123       function is passed two arguments: the string n (for name)  and  namstr.
1124       It  should  either set the array reply to a single element which is the
1125       directory corresponding to the name and return status  zero  (executing
1126       an  assignment  as  the  last  statement  is usually sufficient), or it
1127       should return status non-zero.  In the former case the element of reply
1128       is used as the directory; in the latter case the substitution is deemed
1129       to have failed and NOMATCH handling is applied if the option is set.
1130
1131       The function zsh_directory_name is also used to see if a directory  can
1132       be turned into a name, for example when printing the directory stack or
1133       when expanding %~ in prompts.  In this case the function is passed  two
1134       arguments:  the  string d (for directory) and the candidate for dynamic
1135       naming.  The function should either  return  non-zero  status,  if  the
1136       directory  cannot  be named by the function, or it should set the array
1137       reply to consist of two elements: the first is the dynamic name for the
1138       directory (as would appear within `~[...]'), and the second is the pre‐
1139       fix length of the directory to be replaced.  For example, if the  trial
1140       directory   is   /home/myname/src/zsh   and   the   dynamic   name  for
1141       /home/myname/src (which has 16 characters) is s, then the function sets
1142
1143              reply=(s 16)
1144
1145       The directory name so returned is compared with possible  static  names
1146       for  parts of the directory path, as described below; it is used if the
1147       prefix length matched (16 in the example) is longer than  that  matched
1148       by any static name.
1149
1150       As a working example, here is a function that expands any dynamic names
1151       beginning with the string p: to directories  below  /home/pws/perforce.
1152       In  this  simple  case a static name for the directory would be just as
1153       effective.
1154
1155              zsh_directory_name() {
1156                emulate -L zsh
1157                setopt extendedglob
1158                local -a match mbegin mend
1159                if [[ $1 = d ]]; then
1160                  if [[ $2 = (#b)(/home/pws/perforce/)([^/]##)* ]]; then
1161                    typeset -ga reply
1162                    reply=(p:$match[2] $(( ${#match[1]} + ${#match[2]} )) )
1163                  else
1164                    return 1
1165                  fi
1166                else
1167                  [[ $2 != (#b)p:(?*) ]] && return 1
1168                  typeset -ga reply
1169                  reply=(/home/pws/perforce/$match[1])
1170                fi
1171                return 0
1172              }
1173
1174   Static named directories
1175       A `~' followed by anything not already covered consisting of any number
1176       of  alphanumeric  characters  or underscore (`_'), hyphen (`-'), or dot
1177       (`.') is looked up as a named directory, and replaced by the  value  of
1178       that  named  directory  if found.  Named directories are typically home
1179       directories for users on the system.  They may also be defined  if  the
1180       text  after the `~' is the name of a string shell parameter whose value
1181       begins with a `/'.  Note that trailing slashes will be removed from the
1182       path to the directory (though the original parameter is not modified).
1183
1184       It  is  also  possible to define directory names using the -d option to
1185       the hash builtin.
1186
1187       In certain circumstances (in prompts, for  instance),  when  the  shell
1188       prints  a  path, the path is checked to see if it has a named directory
1189       as its prefix.  If so, then the prefix portion is replaced with  a  `~'
1190       followed  by  the name of the directory.  The shortest way of referring
1191       to the directory is used, with ties broken in favour of using  a  named
1192       directory,  except when the directory is / itself.  The parameters $PWD
1193       and $OLDPWD are never abbreviated in this fashion.
1194
1195   `=' expansion
1196       If a word begins with an unquoted `=' and the EQUALS option is set, the
1197       remainder  of the word is taken as the name of a command.  If a command
1198       exists by that name, the word is replaced by the full pathname  of  the
1199       command.
1200
1201   Notes
1202       Filename  expansion  is performed on the right hand side of a parameter
1203       assignment, including those appearing after  commands  of  the  typeset
1204       family.   In  this  case,  the  right  hand  side  will be treated as a
1205       colon-separated list in the manner of the PATH parameter, so that a `~'
1206       or  an  `=' following a `:' is eligible for expansion.  All such behav‐
1207       iour can be disabled by quoting the `~', the `=', or the whole  expres‐
1208       sion (but not simply the colon); the EQUALS option is also respected.
1209
1210       If  the option MAGIC_EQUAL_SUBST is set, any unquoted shell argument in
1211       the form `identifier=expression' becomes eligible for file expansion as
1212       described  in  the  previous  paragraph.   Quoting  the  first `=' also
1213       inhibits this.
1214

FILENAME GENERATION

1216       If a word contains an unquoted instance of one of the  characters  `*',
1217       `(',  `|',  `<',  `[', or `?', it is regarded as a pattern for filename
1218       generation, unless the GLOB option  is  unset.   If  the  EXTENDED_GLOB
1219       option is set, the `^' and `#' characters also denote a pattern; other‐
1220       wise they are not treated specially by the shell.
1221
1222       The word is replaced with a list of sorted  filenames  that  match  the
1223       pattern.   If  no  matching  pattern is found, the shell gives an error
1224       message, unless the NULL_GLOB option is set, in which case the word  is
1225       deleted;  or unless the NOMATCH option is unset, in which case the word
1226       is left unchanged.
1227
1228       In filename generation, the character `/' must be  matched  explicitly;
1229       also, a `.' must be matched explicitly at the beginning of a pattern or
1230       after a `/', unless the GLOB_DOTS option is set.  No  filename  genera‐
1231       tion pattern matches the files `.' or `..'.  In other instances of pat‐
1232       tern matching, the `/' and `.' are not treated specially.
1233
1234   Glob Operators
1235       *      Matches any string, including the null string.
1236
1237       ?      Matches any character.
1238
1239       [...]  Matches any of the enclosed characters.   Ranges  of  characters
1240              can  be  specified by separating two characters by a `-'.  A `-'
1241              or `]' may be matched by including it as the first character  in
1242              the  list.   There are also several named classes of characters,
1243              in the form `[:name:]' with the following meanings.   The  first
1244              set  use the macros provided by the operating system to test for
1245              the given character combinations,  including  any  modifications
1246              due to local language settings, see ctype(3):
1247
1248              [:alnum:]
1249                     The character is alphanumeric
1250
1251              [:alpha:]
1252                     The character is alphabetic
1253
1254              [:ascii:]
1255                     The  character  is 7-bit, i.e. is a single-byte character
1256                     without the top bit set.
1257
1258              [:blank:]
1259                     The character is either space or tab
1260
1261              [:cntrl:]
1262                     The character is a control character
1263
1264              [:digit:]
1265                     The character is a decimal digit
1266
1267              [:graph:]
1268                     The character is a printable character other than  white‐
1269                     space
1270
1271              [:lower:]
1272                     The character is a lowercase letter
1273
1274              [:print:]
1275                     The character is printable
1276
1277              [:punct:]
1278                     The  character  is printable but neither alphanumeric nor
1279                     whitespace
1280
1281              [:space:]
1282                     The character is whitespace
1283
1284              [:upper:]
1285                     The character is an uppercase letter
1286
1287              [:xdigit:]
1288                     The character is a hexadecimal digit
1289
1290              Another set of named classes is handled internally by the  shell
1291              and is not sensitive to the locale:
1292
1293              [:IDENT:]
1294                     The  character is allowed to form part of a shell identi‐
1295                     fier, such as a parameter name
1296
1297              [:IFS:]
1298                     The character is used as an input field  separator,  i.e.
1299                     is contained in the IFS parameter
1300
1301              [:IFSSPACE:]
1302                     The  character  is  an IFS white space character; see the
1303                     documentation for IFS in the zshparam(1) manual page.
1304
1305              [:WORD:]
1306                     The character is treated as part of a word; this test  is
1307                     sensitive to the value of the WORDCHARS parameter
1308
1309              Note  that the square brackets are additional to those enclosing
1310              the whole set of characters, so to test for  a  single  alphanu‐
1311              meric  character  you  need `[[:alnum:]]'.  Named character sets
1312              can be used alongside other types, e.g. `[[:alpha:]0-9]'.
1313
1314       [^...]
1315       [!...] Like [...], except that it matches any character which is not in
1316              the given set.
1317
1318       <[x]-[y]>
1319              Matches  any  number  in the range x to y, inclusive.  Either of
1320              the numbers may be omitted to make the range  open-ended;  hence
1321              `<->' matches any number.  To match individual digits, the [...]
1322              form is more efficient.
1323
1324              Be careful when using other wildcards adjacent  to  patterns  of
1325              this  form;  for  example, <0-9>* will actually match any number
1326              whatsoever at the start of the string, since  the  `<0-9>'  will
1327              match  the first digit, and the `*' will match any others.  This
1328              is a trap for the unwary, but is in fact  an  inevitable  conse‐
1329              quence  of  the rule that the longest possible match always suc‐
1330              ceeds.  Expressions such as  `<0-9>[^[:digit:]]*'  can  be  used
1331              instead.
1332
1333       (...)  Matches  the  enclosed  pattern.  This is used for grouping.  If
1334              the KSH_GLOB option is set, then a `@', `*',  `+',  `?'  or  `!'
1335              immediately  preceding the `(' is treated specially, as detailed
1336              below. The option SH_GLOB prevents bare parentheses  from  being
1337              used in this way, though the KSH_GLOB option is still available.
1338
1339              Note  that  grouping cannot extend over multiple directories: it
1340              is an error to have a `/' within a group (this only applies  for
1341              patterns  used in filename generation).  There is one exception:
1342              a group of the form (pat/)# appearing as a complete path segment
1343              can match a sequence of directories.  For example, foo/(a*/)#bar
1344              matches foo/bar, foo/any/bar, foo/any/anyother/bar, and so on.
1345
1346       x|y    Matches either x or y.  This operator has lower precedence  than
1347              any  other.   The  `|'  character must be within parentheses, to
1348              avoid interpretation as a pipeline.
1349
1350       ^x     (Requires EXTENDED_GLOB to be set.)  Matches anything except the
1351              pattern x.  This has a higher precedence than `/', so `^foo/bar'
1352              will search directories in `.' except `./foo' for a  file  named
1353              `bar'.
1354
1355       x~y    (Requires EXTENDED_GLOB to be set.)  Match anything that matches
1356              the pattern x but does not match y.  This has  lower  precedence
1357              than  any  operator except `|', so `*/*~foo/bar' will search for
1358              all files in all directories in `.'  and then exclude  `foo/bar'
1359              if there was such a match.  Multiple patterns can be excluded by
1360              `foo~bar~baz'.  In the exclusion pattern (y), `/'  and  `.'  are
1361              not treated specially the way they usually are in globbing.
1362
1363       x#     (Requires EXTENDED_GLOB to be set.)  Matches zero or more occur‐
1364              rences of the pattern x.  This  operator  has  high  precedence;
1365              `12#'  is  equivalent to `1(2#)', rather than `(12)#'.  It is an
1366              error for an unquoted `#' to follow something  which  cannot  be
1367              repeated;  this includes an empty string, a pattern already fol‐
1368              lowed by `##', or parentheses when part of  a  KSH_GLOB  pattern
1369              (for  example,  `!(foo)#'  is  invalid  and  must be replaced by
1370              `*(!(foo))').
1371
1372       x##    (Requires EXTENDED_GLOB to be set.)  Matches one or more  occur‐
1373              rences  of  the  pattern  x.  This operator has high precedence;
1374              `12##' is equivalent to `1(2##)', rather than `(12)##'.  No more
1375              than  two  active `#' characters may appear together.  (Note the
1376              potential clash with glob qualifiers in the form `1(2##)'  which
1377              should therefore be avoided.)
1378
1379   ksh-like Glob Operators
1380       If  the KSH_GLOB option is set, the effects of parentheses can be modi‐
1381       fied by a preceding `@', `*', `+', `?' or `!'.  This character need not
1382       be unquoted to have special effects, but the `(' must be.
1383
1384       @(...) Match the pattern in the parentheses.  (Like `(...)'.)
1385
1386       *(...) Match any number of occurrences.  (Like `(...)#'.)
1387
1388       +(...) Match at least one occurrence.  (Like `(...)##'.)
1389
1390       ?(...) Match zero or one occurrence.  (Like `(|...)'.)
1391
1392       !(...) Match   anything  but  the  expression  in  parentheses.   (Like
1393              `(^(...))'.)
1394
1395   Precedence
1396       The precedence of the operators given above is (highest) `^', `/', `~',
1397       `|'  (lowest);  the remaining operators are simply treated from left to
1398       right as part of a string, with `#' and `##' applying to  the  shortest
1399       possible  preceding unit (i.e. a character, `?', `[...]', `<...>', or a
1400       parenthesised expression).  As mentioned above, a `/' used as a  direc‐
1401       tory  separator  may not appear inside parentheses, while a `|' must do
1402       so; in patterns used in other contexts than  filename  generation  (for
1403       example,  in  case statements and tests within `[[...]]'), a `/' is not
1404       special; and `/' is also not special  after  a  `~'  appearing  outside
1405       parentheses in a filename pattern.
1406
1407   Globbing Flags
1408       There  are various flags which affect any text to their right up to the
1409       end of the enclosing group or to the end of the pattern;  they  require
1410       the  EXTENDED_GLOB  option. All take the form (#X) where X may have one
1411       of the following forms:
1412
1413       i      Case insensitive:  upper or lower case characters in the pattern
1414              match upper or lower case characters.
1415
1416       l      Lower  case  characters in the pattern match upper or lower case
1417              characters; upper case characters  in  the  pattern  still  only
1418              match upper case characters.
1419
1420       I      Case  sensitive:  locally negates the effect of i or l from that
1421              point on.
1422
1423       b      Activate backreferences for parenthesised groups in the pattern;
1424              this  does not work in filename generation.  When a pattern with
1425              a set of active parentheses is matched, the strings  matched  by
1426              the  groups  are  stored in the array $match, the indices of the
1427              beginning of the matched parentheses in the array  $mbegin,  and
1428              the  indices  of the end in the array $mend, with the first ele‐
1429              ment of each array  corresponding  to  the  first  parenthesised
1430              group, and so on.  These arrays are not otherwise special to the
1431              shell.  The indices use the same convention  as  does  parameter
1432              substitution,  so that elements of $mend and $mbegin may be used
1433              in subscripts; the KSH_ARRAYS  option  is  respected.   Sets  of
1434              globbing flags are not considered parenthesised groups; only the
1435              first nine active parentheses can be referenced.
1436
1437              For example,
1438
1439                     foo="a string with a message"
1440                     if [[ $foo = (a|an)' '(#b)(*)' '* ]]; then
1441                       print ${foo[$mbegin[1],$mend[1]]}
1442                     fi
1443
1444              prints `string with a'.  Note  that  the  first  parenthesis  is
1445              before the (#b) and does not create a backreference.
1446
1447              Backreferences  work  with  all  forms of pattern matching other
1448              than filename generation, but note that when performing  matches
1449              on  an  entire array, such as ${array#pattern}, or a global sub‐
1450              stitution, such as ${param//pat/repl}, only  the  data  for  the
1451              last  match  remains  available.  In the case of global replace‐
1452              ments this may still be useful.  See the example for the m  flag
1453              below.
1454
1455              The  numbering  of  backreferences strictly follows the order of
1456              the opening parentheses  from  left  to  right  in  the  pattern
1457              string,  although  sets of parentheses may be nested.  There are
1458              special rules for parentheses followed by `#' or `##'.  Only the
1459              last match of the parenthesis is remembered: for example, in `[[
1460              abab =  (#b)([ab])#  ]]',  only  the  final  `b'  is  stored  in
1461              match[1].   Thus extra parentheses may be necessary to match the
1462              complete segment: for example, use  `X((ab|cd)#)Y'  to  match  a
1463              whole  string  of either `ab' or `cd' between `X' and `Y', using
1464              the value of $match[1] rather than $match[2].
1465
1466              If the match fails none of the parameters is altered, so in some
1467              cases  it  may  be  necessary to initialise them beforehand.  If
1468              some of the backreferences fail to match  --  which  happens  if
1469              they are in an alternate branch which fails to match, or if they
1470              are followed by # and matched zero times  --  then  the  matched
1471              string is set to the empty string, and the start and end indices
1472              are set to -1.
1473
1474              Pattern matching with backreferences  is  slightly  slower  than
1475              without.
1476
1477       B      Deactivate  backreferences,  negating  the  effect of the b flag
1478              from that point on.
1479
1480       cN,M   The flag (#cN,M) can be used anywhere that the # or ## operators
1481              can be used; it cannot be combined with other globbing flags and
1482              a bad pattern error occurs if it is misplaced.  It is equivalent
1483              to  the form {N,M} in regular expressions.  The previous charac‐
1484              ter or group is required to match between N and M times,  inclu‐
1485              sive.   The  form  (#cN)  requires  exactly N matches; (#c,M) is
1486              equivalent to specifying N as 0; (#cN,) specifies that there  is
1487              no maximum limit on the number of matches.
1488
1489       m      Set  references to the match data for the entire string matched;
1490              this is similar to backreferencing and does not work in filename
1491              generation.   The  flag must be in effect at the end of the pat‐
1492              tern, i.e. not local to a group. The parameters $MATCH,  $MBEGIN
1493              and  $MEND  will be set to the string matched and to the indices
1494              of the beginning and end of the string, respectively.   This  is
1495              most  useful in parameter substitutions, as otherwise the string
1496              matched is obvious.
1497
1498              For example,
1499
1500                     arr=(veldt jynx grimps waqf zho buck)
1501                     print ${arr//(#m)[aeiou]/${(U)MATCH}}
1502
1503              forces all the matches (i.e. all vowels) into uppercase,  print‐
1504              ing `vEldt jynx grImps wAqf zhO bUck'.
1505
1506              Unlike backreferences, there is no speed penalty for using match
1507              references, other than the extra substitutions required for  the
1508              replacement strings in cases such as the example shown.
1509
1510       M      Deactivate the m flag, hence no references to match data will be
1511              created.
1512
1513       anum   Approximate matching: num  errors  are  allowed  in  the  string
1514              matched by the pattern.  The rules for this are described in the
1515              next subsection.
1516
1517       s, e   Unlike the other flags, these have only a local effect, and each
1518              must  appear  on  its own:  `(#s)' and `(#e)' are the only valid
1519              forms.  The `(#s)' flag succeeds only at the start of  the  test
1520              string, and the `(#e)' flag succeeds only at the end of the test
1521              string; they correspond to  `^'  and  `$'  in  standard  regular
1522              expressions.  They are useful for matching path segments in pat‐
1523              terns other than those in filename generation (where  path  seg‐
1524              ments  are  in  any  case  treated  separately).   For  example,
1525              `*((#s)|/)test((#e)|/)*' matches a path segment `test' in any of
1526              the   following   strings:   test,  test/at/start,  at/end/test,
1527              in/test/middle.
1528
1529              Another  use  is  in   parameter   substitution;   for   example
1530              `${array/(#s)A*Z(#e)}'  will  remove  only  elements of an array
1531              which match the complete pattern `A*Z'.  There are other ways of
1532              performing many operations of this type, however the combination
1533              of the substitution operations `/' and `//' with the `(#s)'  and
1534              `(#e)' flags provides a single simple and memorable method.
1535
1536              Note that assertions of the form `(^(#s))' also work, i.e. match
1537              anywhere except at the start of the string, although this  actu‐
1538              ally  means  `anything except a zero-length portion at the start
1539              of  the  string';  you  need  to  use  `(""~(#s))'  to  match  a
1540              zero-length portion of the string not at the start.
1541
1542       q      A  `q' and everything up to the closing parenthesis of the glob‐
1543              bing flags are ignored by the pattern matching  code.   This  is
1544              intended  to support the use of glob qualifiers, see below.  The
1545              result is that the pattern `(#b)(*).c(#q.)' can be used both for
1546              globbing and for matching against a string.  In the former case,
1547              the `(#q.)' will be treated as a glob qualifier and  the  `(#b)'
1548              will  not be useful, while in the latter case the `(#b)' is use‐
1549              ful for backreferences and the `(#q.)' will  be  ignored.   Note
1550              that colon modifiers in the glob qualifiers are also not applied
1551              in ordinary pattern matching.
1552
1553       u      Respect the current locale in determining the presence of multi‐
1554              byte  characters  in  a pattern, provided the shell was compiled
1555              with MULTIBYTE_SUPPORT.  This overrides  the  MULTIBYTE  option;
1556              the  default  behaviour  is  taken  from the option.  Compare U.
1557              (Mnemonic: typically multibyte characters are  from  Unicode  in
1558              the UTF-8 encoding, although any extension of ASCII supported by
1559              the system library may be used.)
1560
1561       U      All characters are considered to be a  single  byte  long.   The
1562              opposite of u.  This overrides the MULTIBYTE option.
1563
1564       For  example,  the  test  string  fooxx  can  be matched by the pattern
1565       (#i)FOOXX, but not by (#l)FOOXX,  (#i)FOO(#I)XX  or  ((#i)FOOX)X.   The
1566       string  (#ia2)readme specifies case-insensitive matching of readme with
1567       up to two errors.
1568
1569       When using the ksh syntax for grouping both KSH_GLOB and  EXTENDED_GLOB
1570       must  be  set  and  the left parenthesis should be preceded by @.  Note
1571       also that the flags do not affect letters inside [...] groups, in other
1572       words  (#i)[a-z]  still  matches only lowercase letters.  Finally, note
1573       that when examining whole paths case-insensitively every directory must
1574       be  searched  for  all files which match, so that a pattern of the form
1575       (#i)/foo/bar/... is potentially slow.
1576
1577   Approximate Matching
1578       When matching approximately, the shell keeps  a  count  of  the  errors
1579       found,  which  cannot exceed the number specified in the (#anum) flags.
1580       Four types of error are recognised:
1581
1582       1.     Different characters, as in fooxbar and fooybar.
1583
1584       2.     Transposition of characters, as in banana and abnana.
1585
1586       3.     A character missing in the target string, as  with  the  pattern
1587              road and target string rod.
1588
1589       4.     An extra character appearing in the target string, as with stove
1590              and strove.
1591
1592       Thus, the pattern (#a3)abcd matches dcba, with the errors occurring  by
1593       using  the first rule twice and the second once, grouping the string as
1594       [d][cb][a] and [a][bc][d].
1595
1596       Non-literal parts of the pattern must match exactly, including  charac‐
1597       ters  in  character  ranges:  hence (#a1)???  matches strings of length
1598       four, by applying rule 4 to an empty  part  of  the  pattern,  but  not
1599       strings  of  length  two, since all the ? must match.  Other characters
1600       which must match exactly are initial  dots  in  filenames  (unless  the
1601       GLOB_DOTS option is set), and all slashes in filenames, so that a/bc is
1602       two errors from ab/c (the slash cannot be transposed with another char‐
1603       acter).   Similarly,  errors  are counted separately for non-contiguous
1604       strings in the pattern, so that (ab|cd)ef is two errors from aebf.
1605
1606       When using exclusion  via  the  ~  operator,  approximate  matching  is
1607       treated entirely separately for the excluded part and must be activated
1608       separately.  Thus, (#a1)README~READ_ME matches READ.ME but not READ_ME,
1609       as  the  trailing  READ_ME  is matched without approximation.  However,
1610       (#a1)README~(#a1)READ_ME does not match any pattern of the form READ?ME
1611       as all such forms are now excluded.
1612
1613       Apart  from exclusions, there is only one overall error count; however,
1614       the maximum errors allowed may be altered  locally,  and  this  can  be
1615       delimited  by  grouping.  For example, (#a1)cat((#a0)dog)fox allows one
1616       error in total, which may not occur in the dog section, and the pattern
1617       (#a1)cat(#a0)dog(#a1)fox  is  equivalent.  Note that the point at which
1618       an error is first found is the crucial one for establishing whether  to
1619       use   approximation;  for  example,  (#a1)abc(#a0)xyz  will  not  match
1620       abcdxyz, because the error occurs at the `x',  where  approximation  is
1621       turned off.
1622
1623       Entire   path   segments   may   be   matched  approximately,  so  that
1624       `(#a1)/foo/d/is/available/at/the/bar' allows one error in any path seg‐
1625       ment.   This  is  much  less efficient than without the (#a1), however,
1626       since every directory in the  path  must  be  scanned  for  a  possible
1627       approximate  match.   It is best to place the (#a1) after any path seg‐
1628       ments which are known to be correct.
1629
1630   Recursive Globbing
1631       A pathname component of the form `(foo/)#' matches a path consisting of
1632       zero or more directories matching the pattern foo.
1633
1634       As  a  shorthand, `**/' is equivalent to `(*/)#'; note that this there‐
1635       fore matches files in the current directory as well as  subdirectories.
1636       Thus:
1637
1638              ls (*/)#bar
1639
1640       or
1641
1642              ls **/bar
1643
1644       does  a  recursive  directory search for files named `bar' (potentially
1645       including the file `bar' in the current directory).  This form does not
1646       follow  symbolic links; the alternative form `***/' does, but is other‐
1647       wise identical.  Neither of these can be combined with other  forms  of
1648       globbing  within the same path segment; in that case, the `*' operators
1649       revert to their usual effect.
1650
1651   Glob Qualifiers
1652       Patterns used for filename generation may end in a list  of  qualifiers
1653       enclosed  in  parentheses.  The qualifiers specify which filenames that
1654       otherwise match the given pattern will  be  inserted  in  the  argument
1655       list.
1656
1657       If the option BARE_GLOB_QUAL is set, then a trailing set of parentheses
1658       containing no `|' or `(' characters (or `~' if it is special) is  taken
1659       as  a set of glob qualifiers.  A glob subexpression that would normally
1660       be taken as glob qualifiers, for example `(^x)', can be  forced  to  be
1661       treated  as  part  of  the glob pattern by doubling the parentheses, in
1662       this case producing `((^x))'.
1663
1664       If the option EXTENDED_GLOB is set, a different syntax for glob  quali‐
1665       fiers  is  available,  namely  `(#qx)'  where x is any of the same glob
1666       qualifiers used in the other format.  The qualifiers must still  appear
1667       at  the  end  of  the pattern.  However, with this syntax multiple glob
1668       qualifiers may be chained together.  They are treated as a logical  AND
1669       of  the  individual sets of flags.  Also, as the syntax is unambiguous,
1670       the expression will be treated as glob  qualifiers  just  as  long  any
1671       parentheses contained within it are balanced; appearance of `|', `(' or
1672       `~' does not negate the effect.  Note that qualifiers  will  be  recog‐
1673       nised  in  this form even if a bare glob qualifier exists at the end of
1674       the pattern, for example `*(#q*)(.)' will recognise executable  regular
1675       files if both options are set; however, mixed syntax should probably be
1676       avoided for the sake of clarity.
1677
1678       A qualifier may be any one of the following:
1679
1680       /      directories
1681
1682       F      `full' (i.e. non-empty) directories.   Note  that  the  opposite
1683              sense (^F) expands to empty directories and all non-directories.
1684              Use (/^F) for empty directories
1685
1686       .      plain files
1687
1688       @      symbolic links
1689
1690       =      sockets
1691
1692       p      named pipes (FIFOs)
1693
1694       *      executable plain files (0100)
1695
1696       %      device files (character or block special)
1697
1698       %b     block special files
1699
1700       %c     character special files
1701
1702       r      owner-readable files (0400)
1703
1704       w      owner-writable files (0200)
1705
1706       x      owner-executable files (0100)
1707
1708       A      group-readable files (0040)
1709
1710       I      group-writable files (0020)
1711
1712       E      group-executable files (0010)
1713
1714       R      world-readable files (0004)
1715
1716       W      world-writable files (0002)
1717
1718       X      world-executable files (0001)
1719
1720       s      setuid files (04000)
1721
1722       S      setgid files (02000)
1723
1724       t      files with the sticky bit (01000)
1725
1726       fspec  files with access rights matching spec. This spec may be a octal
1727              number optionally preceded by a `=', a `+', or a `-'. If none of
1728              these characters is given, the behavior is the same as for  `='.
1729              The octal number describes the mode bits to be expected, if com‐
1730              bined with a `=', the value  given  must  match  the  file-modes
1731              exactly,  with a `+', at least the bits in the given number must
1732              be set in the file-modes, and with a `-', the bits in the number
1733              must  not be set. Giving a `?' instead of a octal digit anywhere
1734              in the  number  ensures  that  the  corresponding  bits  in  the
1735              file-modes  are  not checked, this is only useful in combination
1736              with `='.
1737
1738              If the qualifier `f' is followed by any other character anything
1739              up  to the next matching character (`[', `{', and `<' match `]',
1740              `}', and `>' respectively, any other character  matches  itself)
1741              is  taken  as a list of comma-separated sub-specs. Each sub-spec
1742              may be either an octal number as described above or  a  list  of
1743              any of the characters `u', `g', `o', and `a', followed by a `=',
1744              a `+', or a `-', followed by a list of  any  of  the  characters
1745              `r',  `w',  `x', `s', and `t', or an octal digit. The first list
1746              of characters specify which access rights are to be checked.  If
1747              a  `u'  is given, those for the owner of the file are used, if a
1748              `g' is given, those of the group are checked,  a  `o'  means  to
1749              test  those  of  other users, and the `a' says to test all three
1750              groups. The `=', `+', and `-' again says how the modes are to be
1751              checked  and  have  the  same meaning as described for the first
1752              form above. The second list of  characters  finally  says  which
1753              access  rights  are to be expected: `r' for read access, `w' for
1754              write access, `x' for the right  to  execute  the  file  (or  to
1755              search a directory), `s' for the setuid and setgid bits, and `t'
1756              for the sticky bit.
1757
1758              Thus, `*(f70?)' gives the files for which the  owner  has  read,
1759              write, and execute permission, and for which other group members
1760              have no rights, independent of the permissions for other  users.
1761              The  pattern `*(f-100)' gives all files for which the owner does
1762              not have execute permission,  and  `*(f:gu+w,o-rx:)'  gives  the
1763              files  for  which  the  owner and the other members of the group
1764              have at least write permission, and for which other users  don't
1765              have read or execute permission.
1766
1767       estring
1768       +cmd   The string will be executed as shell code.  The filename will be
1769              included in the list if and only if the code returns a zero sta‐
1770              tus (usually the status of the last command).  The first charac‐
1771              ter after the `e' will be used as a separator and anything up to
1772              the  next  matching separator will be taken  as the string; `[',
1773              `{', and `<' match `]', `}', and `>',  respectively,  while  any
1774              other  character  matches  itself.  Note that expansions must be
1775              quoted in the string to prevent them from being expanded  before
1776              globbing is done.
1777
1778              During  the  execution  of  string  the filename currently being
1779              tested is available in the parameter REPLY; the parameter may be
1780              altered  to a string to be inserted into the list instead of the
1781              original filename.  In addition, the parameter reply may be  set
1782              to an array or a string, which overrides the value of REPLY.  If
1783              set to an array, the latter is inserted into  the  command  line
1784              word by word.
1785
1786              For   example,  suppose  a  directory  contains  a  single  file
1787              `lonely'.  Then the  expression  `*(e:'reply=(${REPLY}{1,2})':)'
1788              will  cause  the words `lonely1 lonely2' to be inserted into the
1789              command line.  Note the quotation marks.
1790
1791              The form +cmd has the same  effect,  but  no  delimiters  appear
1792              around  cmd.   Instead,  cmd is taken as the longest sequence of
1793              characters following the + that are alphanumeric or  underscore.
1794              Typically cmd will be the name of a shell function that contains
1795              the appropriate test.  For example,
1796
1797                     nt() { [[ $REPLY -nt $NTREF ]] }
1798                     NTREF=reffile
1799                     ls -l *(+nt)
1800
1801              lists all files in the directory that have  been  modified  more
1802              recently than reffile.
1803
1804       ddev   files on the device dev
1805
1806       l[-|+]ct
1807              files having a link count less than ct (-), greater than ct (+),
1808              or equal to ct
1809
1810       U      files owned by the effective user ID
1811
1812       G      files owned by the effective group ID
1813
1814       uid    files owned by user ID id if that is a  number.   Otherwise,  id
1815              specifies a user name: the character after the `u' will be taken
1816              as a separator and the string between it and the  next  matching
1817              separator will be taken as a user name.  The starting separators
1818              `[', `{', and `<' match the final separators `]', `}', and  `>',
1819              respectively;  any other character matches itself.  The selected
1820              files are those owned by this user.  For  example,  `u:foo:'  or
1821              `u[foo]' selects files owned by user `foo'.
1822
1823       gid    like uid but with group IDs or names
1824
1825       a[Mwhms][-|+]n
1826              files  accessed  exactly  n days ago.  Files accessed within the
1827              last n days are selected using a  negative  value  for  n  (-n).
1828              Files accessed more than n days ago are selected by a positive n
1829              value (+n).  Optional unit specifiers `M', `w', `h', `m' or  `s'
1830              (e.g.  `ah5') cause the check to be performed with months (of 30
1831              days), weeks, hours, minutes or seconds instead of days, respec‐
1832              tively.
1833
1834              Any  fractional  part  of the difference between the access time
1835              and the current part in the appropriate units is ignored in  the
1836              comparison.   For  instance,  `echo  *(ah-5)'  would  echo files
1837              accessed within the last five hours, while `echo *(ah+5)'  would
1838              echo  files  accessed  at least six hours ago, as times strictly
1839              between five and six hours are treated as five hours.
1840
1841       m[Mwhms][-|+]n
1842              like the file access qualifier, except that  it  uses  the  file
1843              modification time.
1844
1845       c[Mwhms][-|+]n
1846              like  the  file  access  qualifier, except that it uses the file
1847              inode change time.
1848
1849       L[+|-]n
1850              files less than n bytes (-), more than n bytes (+), or exactly n
1851              bytes  in  length.  If  this  flag is directly followed by a `k'
1852              (`K'), `m' (`M'), or `p' (`P') (e.g. `Lk-50') the check is  per‐
1853              formed  with  kilobytes,  megabytes,  or  blocks  (of 512 bytes)
1854              instead.
1855
1856       ^      negates all qualifiers following it
1857
1858       -      toggles between making the qualifiers  work  on  symbolic  links
1859              (the default) and the files they point to
1860
1861       M      sets the MARK_DIRS option for the current pattern
1862
1863       T      appends a trailing qualifier mark to the filenames, analogous to
1864              the LIST_TYPES option, for the current pattern (overrides M)
1865
1866       N      sets the NULL_GLOB option for the current pattern
1867
1868       D      sets the GLOB_DOTS option for the current pattern
1869
1870       n      sets the NUMERIC_GLOB_SORT option for the current pattern
1871
1872       oc     specifies how the names of the files should be sorted. If c is n
1873              they  are  sorted  by  name  (the  default); if it is L they are
1874              sorted depending on the size (length) of the files;  if  l  they
1875              are sorted by the number of links; if a, m, or c they are sorted
1876              by the time of the last access, modification,  or  inode  change
1877              respectively;  if d, files in subdirectories appear before those
1878              in the current directory at each level of the search -- this  is
1879              best combined with other criteria, for example `odon' to sort on
1880              names for files within the same directory; if N, no  sorting  is
1881              performed.   Note  that  a, m, and c compare the age against the
1882              current time, hence the first name in the list is  the  youngest
1883              file.  Also  note  that  the  modifiers  ^  and  -  are used, so
1884              `*(^-oL)' gives a list of all  files  sorted  by  file  size  in
1885              descending  order,  following  any symbolic links.  Unless oN is
1886              used, multiple order specifiers may occur to resolve ties.
1887
1888              oe and o+ are special cases; they are  each  followed  by  shell
1889              code, delimited as for the e glob qualifier and the + glob qual‐
1890              ifier respectively (see above).  The code is executed  for  each
1891              matched  file  with  the  parameter REPLY set to the name of the
1892              file on entry.  The code should modify the  parameter  REPLY  in
1893              some  fashion.   On  return,  the value of the parameter is used
1894              instead of the file name as the string on which to sort.  Unlike
1895              other  sort  operators, oe and o+ may be repeated, but note that
1896              the maximum number of sort operators of any kind that may appear
1897              in any glob expression is 12.
1898
1899       Oc     like  `o',  but  sorts in descending order; i.e. `*(^oc)' is the
1900              same as `*(Oc)' and `*(^Oc)' is the same as `*(oc)';  `Od'  puts
1901              files in the current directory before those in subdirectories at
1902              each level of the search.
1903
1904       [beg[,end]]
1905              specifies which of the matched filenames should be  included  in
1906              the  returned  list.  The  syntax  is the same as for array sub‐
1907              scripts. beg and the optional end may  be  mathematical  expres‐
1908              sions. As in parameter subscripting they may be negative to make
1909              them count from the last  match  backward.  E.g.:  `*(-OL[1,3])'
1910              gives a list of the names of the three largest files.
1911
1912       More  than one of these lists can be combined, separated by commas. The
1913       whole list matches if at least one of the sublists  matches  (they  are
1914       `or'ed,  the qualifiers in the sublists are `and'ed).  Some qualifiers,
1915       however, affect all matches generated, independent of  the  sublist  in
1916       which  they  are  given.   These are the qualifiers `M', `T', `N', `D',
1917       `n', `o', `O' and the subscripts given in brackets (`[...]').
1918
1919       If a `:' appears in a qualifier list, the remainder of  the  expression
1920       in  parenthesis  is  interpreted  as a modifier (see the section `Modi‐
1921       fiers' in the section `History  Expansion').   Each  modifier  must  be
1922       introduced  by a separate `:'.  Note also that the result after modifi‐
1923       cation does not have to be an existing file.  The name of any  existing
1924       file  can  be  followed  by  a  modifier of the form `(:..)' even if no
1925       actual filename generation is performed, although note that  the  pres‐
1926       ence of the parentheses causes the entire expression to be subjected to
1927       any global pattern matching options such as NULL_GLOB. Thus:
1928
1929              ls *(-/)
1930
1931       lists all directories and symbolic links that point to directories, and
1932
1933              ls *(%W)
1934
1935       lists all world-writable device files in the current directory, and
1936
1937              ls *(W,X)
1938
1939       lists all files in the current directory  that  are  world-writable  or
1940       world-executable, and
1941
1942              echo /tmp/foo*(u0^@:t)
1943
1944       outputs  the basename of all root-owned files beginning with the string
1945       `foo' in /tmp, ignoring symlinks, and
1946
1947              ls *.*~(lex|parse).[ch](^D^l1)
1948
1949       lists all files having a link count of one whose names  contain  a  dot
1950       (but  not  those  starting  with  a  dot, since GLOB_DOTS is explicitly
1951       switched off) except for lex.c, lex.h, parse.c and parse.h.
1952
1953              print b*.pro(#q:s/pro/shmo/)(#q.:s/builtin/shmiltin/)
1954
1955       demonstrates how colon modifiers and other qualifiers  may  be  chained
1956       together.   The ordinary qualifier `.' is applied first, then the colon
1957       modifiers in order from left to right.  So if EXTENDED_GLOB is set  and
1958       the  base  pattern matches the regular file builtin.pro, the shell will
1959       print `shmiltin.shmo'.
1960
1961
1962
1963zsh 4.3.10                       June 1, 2009                       ZSHEXPN(1)
Impressum