GNU Info

Info Node: (zsh.info)Parameter Expansion

(zsh.info)Parameter Expansion


Next: Command Substitution Prev: Process Substitution Up: Expansion
Enter node , (file) or (file)node

Parameter Expansion
===================

The character `$' is used to introduce parameter expansions.  See Note:
Parameters for a description of parameters, including arrays,
associative arrays, and subscript notation to access individual array
elements.

In the expansions discussed below that require a pattern, the form of
the pattern is the same as that used for filename generation; see Note:
Filename Generation.  Note that these patterns, along with the
replacement text of any substitutions, are themselves subject to
parameter expansion, command substitution, and arithmetic expansion.
In addition to the following operations, the colon modifiers described
in Note: Modifiers in Note: History Expansion can be applied:  for
example, ${i:s/foo/bar/} performs string substitution on the expansion
of parameter $i.

${NAME}
     The value, if any, of the parameter NAME is substituted.  The
     braces are required if the expansion is to be followed by a
     letter, digit, or underscore that is not to be interpreted as part
     of NAME.  In addition, more complicated forms of substitution
     usually require the braces to be present; exceptions, which only
     apply if the option KSH_ARRAYS is not set, are a single subscript
     or any colon modifiers appearing after the name, or any of the
     characters `^', `=', `~', `#' or `+' appearing before the name,
     all of which work with or without braces.

     If NAME is an array parameter, and the KSH_ARRAYS option is not
     set, then the value of each element of NAME is substituted, one
     element per word.  Otherwise, the expansion results in one word
     only; with KSH_ARRAYS, this is the first element of an array.  No
     field splitting is done on the result unless the SH_WORD_SPLIT
     option is set.

${+NAME}
     If NAME is the name of a set parameter `1' is substituted,
     otherwise `0' is substituted.

${NAME:-WORD}
     If NAME is set and is non-null then substitute its value;
     otherwise substitute WORD. If NAME is missing, substitute WORD.

${NAME:=WORD}
${NAME::=WORD}
     In the first form, if NAME is unset or is null then set it to
     WORD; in the second form, unconditionally set NAME to WORD.  In
     both forms, the value of the parameter is then substituted.

${NAME:?WORD}
     If NAME is set and is non-null then substitute its value;
     otherwise, print WORD and exit from the shell.  Interactive shells
     instead return to the prompt.  If WORD is omitted, then a standard
     message is printed.

${NAME:+WORD}
     If NAME is set and is non-null then substitute WORD; otherwise
     substitute nothing.

If the colon is omitted from one of the above expressions containing a
colon, then the shell only checks whether NAME is set, not whether its
value is null.

In the following expressions, when NAME is an array and the
substitution is not quoted, or if the `(@)' flag or the NAME[@] syntax
is used, matching and replacement is performed on each array element
separately.

${NAME#PATTERN}
${NAME##PATTERN}
     If the PATTERN matches the beginning of the value of NAME, then
     substitute the value of NAME with the matched portion deleted;
     otherwise, just substitute the value of NAME.  In the first form,
     the smallest matching pattern is preferred; in the second form,
     the largest matching pattern is preferred.

${NAME%PATTERN}
${NAME%%PATTERN}
     If the PATTERN matches the end of the value of NAME, then
     substitute the value of NAME with the matched portion deleted;
     otherwise, just substitute the value of NAME.  In the first form,
     the smallest matching pattern is preferred; in the second form,
     the largest matching pattern is preferred.

${NAME:#PATTERN}
     If the PATTERN matches the value of NAME, then substitute the
     empty string; otherwise, just substitute the value of NAME.  If
     NAME is an array the matching array elements are removed (use the
     `(M)' flag to remove the non-matched elements).

${NAME/PATTERN/REPL}
${NAME//PATTERN/REPL}
     Replace the longest possible match of PATTERN in the expansion of
     parameter NAME by string REPL.  The first form replaces just the
     first occurrence, the second form all occurrences.  Both PATTERN
     and REPL are subject to double-quoted substitution, so that
     expressions like ${name/$opat/$npat} will work, but note the usual
     rule that pattern characters in $opat are not treated specially
     unless either the option GLOB_SUBST is set, or $opat is instead
     substituted as ${~opat}.

     The PATTERN may begin with a `#', in which case the PATTERN must
     match at the start of the string, or `%', in which case it must
     match at the end of the string.  The REPL may be an empty string,
     in which case the final `/' may also be omitted.  To quote the
     final `/' in other cases it should be preceded by two backslashes
     (i.e., a quoted backslash); this is not necessary if the `/'
     occurs inside a substituted parameter.  Note also that the `#' and
     `%' are not active if they occur inside a substituted parameter,
     even at the start.

     The first `/' may be preceded by a `:', in which case the match
     will only succeed if it matches the entire word.  Note also the
     effect of the I and S parameter expansion flags below; however,
     the flags M, R, B, E and N are not useful.

     For example,

          foo="twinkle twinkle little star" sub="t*e" rep="spy"
          print ${foo//${~sub}/$rep}
          print ${(S)foo//${~sub}/$rep}

     Here, the `~' ensures that the text of $sub is treated as a
     pattern rather than a plain string.  In the first case, the longest
     match for t*e is substituted and the result is `spy star', while
     in the second case, the shortest matches are taken and the result
     is `spy spy lispy star'.

${#SPEC}
     If SPEC is one of the above substitutions, substitute the length
     in characters of the result instead of the result itself.  If SPEC
     is an array expression, substitute the number of elements of the
     result.  Note that `^', `=', and `~', below, must appear to the
     left of `#' when these forms are combined.

${^SPEC}
     Turn on the RC_EXPAND_PARAM option for the evaluation of SPEC; if
     the `^' is doubled, turn it off.  When this option is set, array
     expansions of the form FOO${XX}BAR, where the parameter XX is set
     to (A B C), are substituted with `FOOABAR FOOBBAR FOOCBAR' instead
     of the default `FOOA B CBAR'.

     Internally, each such expansion is converted into the equivalent
     list for brace expansion.  E.g., ${^var} becomes
     {$var[1],$var[2],...}, and is processed as described in Note:
     Brace Expansion below.  If word splitting is also in effect the
     $var[N] may themselves be split into different list elements.

${=SPEC}
     Perform word splitting using the rules for SH_WORD_SPLIT during the
     evaluation of SPEC, but regardless of whether the parameter
     appears in double quotes; if the `=' is doubled, turn it off.
     This forces parameter expansions to be split into separate words
     before substitution, using IFS as a delimiter.  This is done by
     default in most other shells.

     Note that splitting is applied to WORD in the assignment forms of
     SPEC _before_ the assignment to NAME is performed.  This affects
     the result of array assignments with the A flag.

${~SPEC}
     Turn on the GLOB_SUBST option for the evaluation of SPEC; if the
     `~' is doubled, turn it off.  When this option is set, the string
     resulting from the expansion will be interpreted as a pattern
     anywhere that is possible, such as in filename expansion and
     filename generation and pattern-matching contexts like the right
     hand side of the `=' and `!=' operators in conditions.

If a ${...} type parameter expression or a $(...) type command
substitution is used in place of NAME above, it is expanded first and
the result is used as if it were the value of NAME.  Thus it is
possible to perform nested operations:  ${${foo#head}%tail} substitutes
the value of $foo with both `head' and `tail' deleted.  The form with
$(...) is often useful in combination with the flags described next;
see the examples below.  Each NAME or nested ${...} in a parameter
expansion may also be followed by a subscript expression as described in
Note: Array Parameters.

Note that double quotes may appear around nested expressions, in which
case only the part inside is treated as quoted; for example,
${(f)"$(foo)"} quotes the result of $(foo), but the flag `(f)' (see
below) is applied using the rules for unquoted expansions.  Note
further that quotes are themselves nested in this context; for example,
in "${(@f)"$(foo)"}", there are two sets of quotes, one surrounding the
whole expression, the other (redundant) surrounding the $(foo) as
before.

Parameter Expansion Flags
-------------------------

If the opening brace is directly followed by an opening parenthesis,
the string up to the matching closing parenthesis will be taken as a
list of flags.  In cases where repeating a flag is meaningful, the
repetitions need not be consecutive; for example, `(q%q%q)' means the
same thing as the more readable `(%%qqq)'.  The following flags are
supported:

%
     Expand all % escapes in the resulting words in the same way as in
     in prompts (see Note: Prompt Expansion). If this flag is given
     twice, full prompt expansion is done on the resulting words,
     depending on the setting of the PROMPT_PERCENT, PROMPT_SUBST and
     PROMPT_BANG options.

@
     In double quotes, array elements are put into separate words.
     E.g., `"${(@)foo}"' is equivalent to `"${foo[@]}"' and
     `"${(@)foo[1,2]}"' is the same as `"$foo[1]" "$foo[2]"'.  This is
     distinct from _field splitting_ by the the f, s or z flags, which
     still applies within each array element.

A
     Create an array parameter with `${...=...}', `${...:=...}' or
     `${...::=...}'.  If this flag is repeated (as in `AA'), create an
     associative array parameter.  Assignment is made before sorting or
     padding.  The NAME part may be a subscripted range for ordinary
     arrays; the WORD part _must_ be converted to an array, for example
     by using `${(AA)=NAME=...}' to activate field splitting, when
     creating an associative array.

c
     With ${#NAME}, count the total number of characters in an array,
     as if the elements were concatenated with spaces between them.

C
     Capitalize the resulting words.  `Words' in this case refers to
     sequences of alphanumeric characters separated by
     non-alphanumerics, _not_ to words that result from field splitting.

e
     Perform _parameter expansion_, _command substitution_ and
     _arithmetic expansion_ on the result. Such expansions can be
     nested but too deep recursion may have unpredictable effects.

f
     Split the result of the expansion to lines. This is a shorthand
     for `ps:\n:'.

F
     Join the words of arrays together using newline as a separator.
     This is a shorthand for `pj:\n:'.

i
     With o or O, sort case-independently.

k
     If NAME refers to an associative array, substitute the _keys_
     (element names) rather than the values of the elements.  Used with
     subscripts (including ordinary arrays), force indices or keys to be
     substituted even if the subscript form refers to values.  However,
     this flag may not be combined with subscript ranges.

L
     Convert all letters in the result to lower case.

o
     Sort the resulting words in ascending order.

O
     Sort the resulting words in descending order.

P
     This forces the value of the parameter NAME to be interpreted as a
     further parameter name, whose value will be used where
     appropriate. If used with a nested parameter or command
     substitution, the result of that will be taken as a parameter name
     in the same way.  For example, if you have `foo=bar' and
     `bar=baz', the strings ${(P)foo}, ${(P)${foo}}, and ${(P)$(echo
     bar)} will be expanded to `baz'.

q
     Quote the resulting words with backslashes. If this flag is given
     twice, the resulting words are quoted in single quotes and if it is
     given three times, the words are quoted in double quotes. If it is
     given four times, the words are quoted in single quotes preceded
     by a $.

Q
     Remove one level of quotes from the resulting words.

t
     Use a string describing the type of the parameter where the value
     of the parameter would usually appear. This string consists of
     keywords separated by hyphens (`-'). The first keyword in the
     string describes the main type, it can be one of `scalar',
     `array', `integer', `float' or `association'. The other keywords
     describe the type in more detail:

    local
          for local parameters

    left
          for left justified parameters

    right_blanks
          for right justified parameters with leading blanks

    right_zeros
          for right justified parameters with leading zeros

    lower
          for parameters whose value is converted to all lower case
          when it is expanded

    upper
          for parameters whose value is converted to all upper case
          when it is expanded

    readonly
          for readonly parameters

    tag
          for tagged parameters

    export
          for exported parameters

    unique
          for arrays which keep only the first occurrence of duplicated
          values

    hide
          for parameters with the `hide' flag

    special
          for special parameters defined by the shell

U
     Convert all letters in the result to upper case.

v
     Used with k, substitute (as two consecutive words) both the key
     and the value of each associative array element.  Used with
     subscripts, force values to be substituted even if the subscript
     form refers to indices or keys.

V
     Make any special characters in the resulting words visible.

w
     With ${#NAME}, count words in arrays or strings; the s flag may be
     used to set a word delimiter.

W
     Similar to w with the difference that empty words between repeated
     delimiters are also counted.

X
     With this flag parsing errors occurring with the Q and e flags or
     the pattern matching forms such as `${NAME#PATTERN}' are reported.
     Without the flag they are silently ignored.

z
     Split the result of the expansion into words using shell parsing to
     find the words, i.e. taking into account any quoting in the value.

     Note that this is done very late, as for the `(s)' flag. So to
     access single words in the result, one has to use nested
     expansions as in `${${(z)foo}[2]}'. Likewise, to remove the quotes
     in the resulting words one would do: `${(Q)${(z)foo}}'.

The following flags (except p) are followed by one or more arguments as
shown.  Any character, or the matching pairs `(...)', `{...}', `[...]',
or `<...>', may be used in place of a colon as delimiters, but note
that when a flag takes more than one argument, a matched pair of
delimiters must surround each argument.

p
     Recognize the same escape sequences as the print builtin in string
     arguments to any of the flags described below.

j:STRING:
     Join the words of arrays together using STRING as a separator.
     Note that this occurs before field splitting by the SH_WORD_SPLIT
     option.

l:EXPR::STRING1::STRING2:
     Pad the resulting words on the left.  Each word will be truncated
     if required and placed in a field EXPR characters wide.  The space
     to the left will be filled with STRING1 (concatenated as often as
     needed) or spaces if STRING1 is not given.  If both STRING1 and
     STRING2 are given, this string is inserted once directly to the
     left of each word, before padding.

r:EXPR::STRING1::STRING2:
     As l, but pad the words on the right and insert STRING2 on the
     right.

s:STRING:
     Force field splitting (see the option SH_WORD_SPLIT) at the
     separator STRING.  Note that a STRING of two or more characters
     means all must all match in sequence; this differs from the
     treatment of two or more characters in the IFS parameter.

The following flags are meaningful with the ${...#...} or ${...%...}
forms.  The S and I flags may also be used with the ${.../...} forms.

S
     Search substrings as well as beginnings or ends; with # start from
     the beginning and with % start from the end of the string.  With
     substitution via ${.../...} or ${...//...}, specifies non-greedy
     matching, i.e. that the shortest instead of the longest match
     should be replaced.

I:EXPR:
     Search the EXPRth match (where EXPR evaluates to a number).  This
     only applies when searching for substrings, either with the S
     flag, or with ${.../...} (only the EXPRth match is substituted) or
     ${...//...} (all matches from the EXPRth on are substituted).  The
     default is to take the first match.

     The EXPRth match is counted such that there is either one or zero
     matches from each starting position in the string, although for
     global substitution matches overlapping previous replacements are
     ignored.  With the ${...%...} and ${...%%...} forms, the starting
     position for the match moves backwards from the end as the index
     increases, while with the other forms it moves forward from the
     start.

     Hence with the string
          which switch is the right switch for Ipswich?
     substitutions of the form ${(SI:N:)string#w*ch} as N increases
     from 1 will match and remove `which', `witch', `witch' and `wich';
     the form using `##' will match and remove `which switch is the
     right switch for Ipswich', `witch is the right switch for
     Ipswich', `witch for Ipswich' and `wich'. The form using `%' will
     remove the same matches as for `#', but in reverse order, and the
     form using `%%' will remove the same matches as for `##' in reverse
     order.

B
     Include the index of the beginning of the match in the result.

E
     Include the index of the end of the match in the result.

M
     Include the matched portion in the result.

N
     Include the length of the match in the result.

R
     Include the unmatched portion in the result (the _R_est).

Rules
-----

Here is a summary of the rules for substitution; this assumes that
braces are present around the substitution, i.e. ${...}.  Some
particular examples are given below.  Note that the Zsh Development
Group accepts _no responsibility_ for any brain damage which may occur
during the reading of the following rules.

1. _Nested Substitution_
     If multiple nested ${...} forms are present, substitution is
     performed from the inside outwards.  At each level, the
     substitution takes account of whether the current value is a
     scalar or an array, whether the whole substitution is in double
     quotes, and what flags are supplied to the current level of
     substitution, just as if the nested substitution were the
     outermost.  The flags are not propagated up to enclosing
     substitutions; the nested substitution will return either a scalar
     or an array as determined by the flags, possibly adjusted for
     quoting.  All the following steps take place where applicable at
     all levels of substitution.  Note that, unless the `(P)' flag is
     present, the flags and any subscripts apply directly to the value
     of the nested substitution; for example, the expansion ${${foo}}
     behaves exactly the same as ${foo}.

2. _Parameter Subscripting_
     If the value is a raw parameter reference with a subscript, such as
     ${VAR[3]}, the effect of subscripting is applied directly to the
     parameter.  Subscripts are evaluated left to right; subsequent
     subscripts apply to the scalar or array value yielded by the
     previous subscript.  Thus if var is an array, ${var[1][2]} is the
     second character of the first word, but ${var[2,4][2]} is the
     entire third word (the second word of the range of words two
     through four of the original array).  Any number of subscripts may
     appear.

3. _Parameter Name Replacement_
     The effect of any (P) flag, which treats the value so far as a
     parameter name and replaces it with the corresponding value, is
     applied.

4. _Double-Quoted Joining_
     If the value after this process is an array, and the substitution
     appears in double quotes, and no (@) flag is present at the current
     level, the words of the value are joined with the first character
     of the parameter $IFS, by default a space, between each word
     (single word arrays are not modified).  If the (j) flag is
     present, that is used for joining instead of $IFS.

5. _Nested Subscripting_
     Any remaining subscripts (i.e. of a nested substitution) are
     evaluated at this point, based on whether the value is an array or
     a scalar.  As with 2., multiple subscripts can appear.  Note that
     ${foo[2,4][2]} is thus equivalent to ${${foo[2,4]}[2]} and also to
     "${${(@)foo[2,4]}[2]}" (the nested substitution returns an array in
     both cases), but not to "${${foo[2,4]}[2]}" (the nested
     substitution returns a scalar because of the quotes).

6. _Modifiers_
     Any modifiers, as specified by a trailing `#', `%', `/' (possibly
     doubled) or by a set of modifiers of the form :... (see Note:
     Modifiers in Note: History Expansion), are applied to the words
     of the value at this level.

7. _Forced Joining_
     If the `(j)' flag is present, or no `(j)' flag is present but the
     string is to be split as given by rules 8. or 9., and joining did
     not take place at step 4., any words in the value are joined
     together using the given string or the first character of $IFS if
     none.  Note that the `(F)' flag implicitly supplies a string for
     joining in this manner.

8. _Forced Splitting_
     If one of the `(s)', `(f)' or `(z)' flags are present, or the `='
     specifier was present (e.g. ${=VAR}), the word is split on
     occurrences of the specified string, or (for = with neither of the
     two flags present) any of the characters in $IFS.

9. _Shell Word Splitting_
     If no `(s)', `(f)' or `=' was given, but the word is not quoted
     and the option SH_WORD_SPLIT is set, the word is split on
     occurrences of any of the characters in $IFS.  Note this step, too,
     takes place at all levels of a nested substitution.

10. _Re-Evaluation_
     Any `(e)' flag is applied to the value, forcing it to be
     re-examined for new parameter substitutions, but also for command
     and arithmetic substitutions.

11. _Padding_
     Any padding of the value by the `(l.FILL.)' or `(r.FILL.)' flags
     is applied.

12. _Semantic Joining_
     In contexts where expansion semantics requires a single word to
     result, all words are rejoined with the first character of IFS
     between.  So in `${(P)${(f)lines}}' the value of ${lines} is split
     at newlines, but then must be joined again before the P flag can
     be applied.

     If a single word is not required, this rule is skipped.

Examples
--------

The flag f is useful to split a double-quoted substitution line by
line.  For example, ${(f)"$(<FILE)"} substitutes the contents of FILE
divided so that each line is an element of the resulting array.
Compare this with the effect of $(<FILE) alone, which divides the file
up by words, or the same inside double quotes, which makes the entire
content of the file a single string.

The following illustrates the rules for nested parameter expansions.
Suppose that $foo contains the array (bar baz):

"${(@)${foo}[1]}"
     This produces the result b.  First, the inner substitution
     "${foo}", which has no array (@) flag, produces a single word
     result "bar baz".  The outer substitution "${(@)...[1]}" detects
     that this is a scalar, so that (despite the `(@)' flag) the
     subscript picks the first character.

"${${(@)foo}[1]}"
     This produces the result `bar'.  In this case, the inner
     substitution "${(@)foo}" produces the array `(bar baz)'.  The outer
     substitution "${...[1]}" detects that this is an array and picks
     the first word.  This is similar to the simple case "${foo[1]}".

As an example of the rules for word splitting and joining, suppose $foo
contains the array `(ax1 bx1)'.  Then

${(s/x/)foo}
     produces the words `a', `1 b' and `1'.

${(j/x/s/x/)foo}
     produces `a', `1', `b' and `1'.

${(s/x/)foo%%1*}
     produces `a' and ` b' (note the extra space).  As substitution
     occurs before either joining or splitting, the operation  first
     generates the modified array (ax bx), which is joined to give "ax
     bx", and then split to give `a', ` b' and `'.  The final empty
     string will then be elided, as it is not in double quotes.


automatically generated by info2www version 1.2.2.9