ZSHPARAM(1) | General Commands Manual | ZSHPARAM(1) |
zshparam - zsh parameters
A parameter has a name, a value, and a number of attributes. A name may be any sequence of alphanumeric characters and underscores, or the single characters `*', `@', `#', `?', `-', `$', or `!'. A parameter whose name begins with an alphanumeric or underscore is also referred to as a variable.
The attributes of a parameter determine the type of its value, often referred to as the parameter type or variable type, and also control other processing that may be applied to the value when it is referenced. The value type may be a scalar (a string, an integer, or a floating point number), an array (indexed numerically), or an associative array (an unordered set of name-value pairs, indexed by name, also referred to as a hash).
Named scalar parameters may have the exported, -x, attribute, to copy them into the process environment, which is then passed from the shell to any new processes that it starts. Exported parameters are called environment variables. The shell also imports environment variables at startup time and automatically marks the corresponding parameters as exported. Some environment variables are not imported for reasons of security or because they would interfere with the correct operation of other shell features.
Parameters may also be special, that is, they have a predetermined meaning to the shell. Special parameters cannot have their type changed or their readonly attribute turned off, and if a special parameter is unset, then later recreated, the special properties will be retained.
To declare the type of a parameter, or to assign a string or numeric value to a scalar parameter, use the typeset builtin.
The value of a scalar parameter may also be assigned by writing:
name=value
In scalar assignment, value is expanded as a single string, in which the elements of arrays are joined together; filename expansion is not performed unless the option GLOB_ASSIGN is set.
When the integer attribute, -i, or a floating point attribute, -E or -F, is set for name, the value is subject to arithmetic evaluation. Furthermore, by replacing `=' with `+=', a parameter can be incremented or appended to. See the section `Array Parameters' and Arithmetic Evaluation (in zshmisc(1)) for additional forms of assignment.
Note that assignment may implicitly change the attributes of a parameter. For example, assigning a number to a variable in arithmetic evaluation may change its type to integer or float, and with GLOB_ASSIGN assigning a pattern to a variable may change its type to an array.
To reference the value of a parameter, write `$name' or `${name}'. See Parameter Expansion in zshexpn(1) for complete details. That section also explains the effect of the difference between scalar and array assignment on parameter expansion.
To assign an array value, write one of:
set -A name value ...
name=(value ...)
name=([key]=value ...)
If no parameter name exists, an ordinary array parameter is created. If the parameter name exists and is a scalar, it is replaced by a new array.
In the third form, key is an expression that will be evaluated in arithmetic context (in its simplest form, an integer) that gives the index of the element to be assigned with value. In this form any elements not explicitly mentioned that come before the largest index to which a value is assigned are assigned an empty string. The indices may be in any order. Note that this syntax is strict: [ and ]= must not be quoted, and key may not consist of the unquoted string ]=, but is otherwise treated as a simple string. The enhanced forms of subscript expression that may be used when directly subscripting a variable name, described in the section Array Subscripts below, are not available.
The syntaxes with and without the explicit key may be mixed. An implicit key is deduced by incrementing the index from the previously assigned element. Note that it is not treated as an error if latter assignments in this form overwrite earlier assignments.
For example, assuming the option KSH_ARRAYS is not set, the following:
array=(one [3]=three four)
causes the array variable array to contain four elements one, an empty string, three and four, in that order.
In the forms where only value is specified, full command line expansion is performed.
In the [key]=value form, both key and value undergo all forms of expansion allowed for single word shell expansions (this does not include filename generation); these are as performed by the parameter expansion flag (e) as described in zshparam(1). Nested parentheses may surround value and are included as part of the value, which is joined into a plain string; this differs from ksh which allows the values themselves to be arrays. A future version of zsh may support that. To cause the brackets to be interpreted as a character class for filename generation, and therefore to treat the resulting list of files as a set of values, quote the equal sign using any form of quoting. Example:
name=([a-z]'='*)
To append to an array without changing the existing values, use one of the following:
name+=(value ...)
name+=([key]=value ...)
In the second form key may specify an existing index as well as an index off the end of the old array; any existing value is overwritten by value. Also, it is possible to use [key]+=value to append to the existing value at that index.
Within the parentheses on the right hand side of either form of the assignment, newlines and semicolons are treated the same as white space, separating individual values. Any consecutive sequence of such characters has the same effect.
Ordinary array parameters may also be explicitly declared with:
typeset -a name
Associative arrays must be declared before assignment, by using:
typeset -A name
When name refers to an associative array, the list in an assignment is interpreted as alternating keys and values:
set -A name key value ...
name=(key value ...)
name=([key]=value ...)
Note that only one of the two syntaxes above may be used in any given assignment; the forms may not be mixed. This is unlike the case of numerically indexed arrays.
Every key must have a value in this case. Note that this assigns to the entire array, deleting any elements that do not appear in the list. The append syntax may also be used with an associative array:
name+=(key value ...)
name+=([key]=value ...)
This adds a new key/value pair if the key is not already present, and replaces the value for the existing key if it is. In the second form it is also possible to use [key]+=value to append to the existing value at that key. Expansion is performed identically to the corresponding forms for normal arrays, as described above.
To create an empty array (including associative arrays), use one of:
set -A name
name=()
Individual elements of an array may be selected using a subscript. A subscript of the form `[exp]' selects the single element exp, where exp is an arithmetic expression which will be subject to arithmetic expansion as if it were surrounded by `$((...))'. The elements are numbered beginning with 1, unless the KSH_ARRAYS option is set in which case they are numbered from zero.
Subscripts may be used inside braces used to delimit a parameter name, thus `${foo[2]}' is equivalent to `$foo[2]'. If the KSH_ARRAYS option is set, the braced form is the only one that works, as bracketed expressions otherwise are not treated as subscripts.
If the KSH_ARRAYS option is not set, then by default accesses to an array element with a subscript that evaluates to zero return an empty string, while an attempt to write such an element is treated as an error. For backward compatibility the KSH_ZERO_SUBSCRIPT option can be set to cause subscript values 0 and 1 to be equivalent; see the description of the option in zshoptions(1).
The same subscripting syntax is used for associative arrays, except that no arithmetic expansion is applied to exp. However, the parsing rules for arithmetic expressions still apply, which affects the way that certain special characters must be protected from interpretation. See Subscript Parsing below for details.
A subscript of the form `[*]' or `[@]' evaluates to all elements of an array; there is no difference between the two except when they appear within double quotes. `"$foo[*]"' evaluates to `"$foo[1] $foo[2] ..."', whereas `"$foo[@]"' evaluates to `"$foo[1]" "$foo[2]" ...'. For associative arrays, `[*]' or `[@]' evaluate to all the values, in no particular order. Note that this does not substitute the keys; see the documentation for the `k' flag under Parameter Expansion Flags in zshexpn(1) for complete details. When an array parameter is referenced as `$name' (with no subscript) it evaluates to `$name[*]', unless the KSH_ARRAYS option is set in which case it evaluates to `${name[0]}' (for an associative array, this means the value of the key `0', which may not exist even if there are values for other keys).
A subscript of the form `[exp1,exp2]' selects all elements in the range exp1 to exp2, inclusive. (Associative arrays are unordered, and so do not support ranges.) If one of the subscripts evaluates to a negative number, say -n, then the nth element from the end of the array is used. Thus `$foo[-3]' is the third element from the end of the array foo, and `$foo[1,-1]' is the same as `$foo[*]'.
Subscripting may also be performed on non-array values, in which case the subscripts specify a substring to be extracted. For example, if FOO is set to `foobar', then `echo $FOO[2,5]' prints `ooba'. Note that some forms of subscripting described below perform pattern matching, and in that case the substring extends from the start of the match of the first subscript to the end of the match of the second subscript. For example,
string="abcdefghijklm" print ${string[(r)d?,(r)h?]}
prints `defghi'. This is an obvious generalisation of the rule for single-character matches. For a single subscript, only a single character is referenced (not the range of characters covered by the match).
Note that in substring operations the second subscript is handled differently by the r and R subscript flags: the former takes the shortest match as the length and the latter the longest match. Hence in the former case a * at the end is redundant while in the latter case it matches the whole remainder of the string. This does not affect the result of the single subscript case as here the length of the match is irrelevant.
A subscript may be used on the left side of an assignment like so:
name[exp]=value
In this form of assignment the element or range specified by exp is replaced by the expression on the right side. An array (but not an associative array) may be created by assignment to a range or element. Arrays do not nest, so assigning a parenthesized list of values to an element or range changes the number of elements in the array, shifting the other elements to accommodate the new values. (This is not supported for associative arrays.)
This syntax also works as an argument to the typeset command:
typeset "name[exp]"=value
The value may not be a parenthesized list in this case; only single-element assignments may be made with typeset. Note that quotes are necessary in this case to prevent the brackets from being interpreted as filename generation operators. The noglob precommand modifier could be used instead.
To delete an element of an ordinary array, assign `()' to that element. To delete an element of an associative array, use the unset command:
unset "name[exp]"
If the opening bracket, or the comma in a range, in any subscript expression is directly followed by an opening parenthesis, the string up to the matching closing one is considered to be a list of flags, as in `name[(flags)exp]'.
The flags s, n and b take an argument; the delimiter is shown below as `:', but any character, or the matching pairs `(...)', `{...}', `[...]', or `<...>', may be used, but note that `<...>' can only be used if the subscript is inside a double quoted expression or a parameter substitution enclosed in braces as otherwise the expression is interpreted as a redirection.
The flags currently understood are:
If a search through an ordinary array failed, the search sets the subscript to one past the end of the array, and hence ${array[(r)pattern]} will substitute the empty string. Thus the success of a search can be tested by using the (i) flag, for example (assuming the option KSH_ARRAYS is not in effect):
[[ ${array[(i)pattern]} -le ${#array} ]]
If KSH_ARRAYS is in effect, the -le should be replaced by -lt.
Note that in subscripts with both `r' and `R' pattern characters are active even if they were substituted for a parameter (regardless of the setting of GLOB_SUBST which controls this feature in normal pattern matching). The flag `e' can be added to inhibit pattern matching. As this flag does not inhibit other forms of substitution, care is still required; using a parameter to hold the key has the desired effect:
key2='original key' print ${array[(Re)$key2]}
This flag can also be used to force * or @ to be interpreted as a single key rather than as a reference to all values. It may be used for either purpose on the left side of an assignment.
See Parameter Expansion Flags (zshexpn(1)) for additional ways to manipulate the results of array subscripting.
This discussion applies mainly to associative array key strings and to patterns used for reverse subscripting (the `r', `R', `i', etc. flags), but it may also affect parameter substitutions that appear as part of an arithmetic expression in an ordinary subscript.
To avoid subscript parsing limitations in assignments to associative array elements, use the append syntax:
aa+=('key with "*strange*" characters' 'value string')
The basic rule to remember when writing a subscript expression is that all text between the opening `[' and the closing `]' is interpreted as if it were in double quotes (see zshmisc(1)). However, unlike double quotes which normally cannot nest, subscript expressions may appear inside double-quoted strings or inside other subscript expressions (or both!), so the rules have two important differences.
The first difference is that brackets (`[' and `]') must appear as balanced pairs in a subscript expression unless they are preceded by a backslash (`\'). Therefore, within a subscript expression (and unlike true double-quoting) the sequence `\[' becomes `[', and similarly `\]' becomes `]'. This applies even in cases where a backslash is not normally required; for example, the pattern `[^[]' (to match any character other than an open bracket) should be written `[^\[]' in a reverse-subscript pattern. However, note that `\[^\[\]' and even `\[^[]' mean the same thing, because backslashes are always stripped when they appear before brackets!
The same rule applies to parentheses (`(' and `)') and braces (`{' and `}'): they must appear either in balanced pairs or preceded by a backslash, and backslashes that protect parentheses or braces are removed during parsing. This is because parameter expansions may be surrounded by balanced braces, and subscript flags are introduced by balanced parentheses.
The second difference is that a double-quote (`"') may appear as part of a subscript expression without being preceded by a backslash, and therefore that the two characters `\"' remain as two characters in the subscript (in true double-quoting, `\"' becomes `"'). However, because of the standard shell quoting rules, any double-quotes that appear must occur in balanced pairs unless preceded by a backslash. This makes it more difficult to write a subscript expression that contains an odd number of double-quote characters, but the reason for this difference is so that when a subscript expression appears inside true double-quotes, one can still write `\"' (rather than `\\\"') for `"'.
To use an odd number of double quotes as a key in an assignment, use the typeset builtin and an enclosing pair of double quotes; to refer to the value of that key, again use double quotes:
typeset -A aa typeset "aa[one\"two\"three\"quotes]"=QQQ print "$aa[one\"two\"three\"quotes]"
It is important to note that the quoting rules do not change when a parameter expansion with a subscript is nested inside another subscript expression. That is, it is not necessary to use additional backslashes within the inner subscript expression; they are removed only once, from the innermost subscript outwards. Parameters are also expanded from the innermost subscript first, as each expansion is encountered left to right in the outer expression.
A further complication arises from a way in which subscript parsing is not different from double quote parsing. As in true double-quoting, the sequences `\*', and `\@' remain as two characters when they appear in a subscript expression. To use a literal `*' or `@' as an associative array key, the `e' flag must be used:
typeset -A aa aa[(e)*]=star print $aa[(e)*]
A last detail must be considered when reverse subscripting is performed. Parameters appearing in the subscript expression are first expanded and then the complete expression is interpreted as a pattern. This has two effects: first, parameters behave as if GLOB_SUBST were on (and it cannot be turned off); second, backslashes are interpreted twice, once when parsing the array subscript and again when parsing the pattern. In a reverse subscript, it's necessary to use four backslashes to cause a single backslash to match literally in the pattern. For complex patterns, it is often easiest to assign the desired pattern to a parameter and then refer to that parameter in the subscript, because then the backslashes, brackets, parentheses, etc., are seen only when the complete expression is converted to a pattern. To match the value of a parameter literally in a reverse subscript, rather than as a pattern, use `${(q)name}' (see zshexpn(1)) to quote the expanded value.
Note that the `k' and `K' flags are reverse subscripting for an ordinary array, but are not reverse subscripting for an associative array! (For an associative array, the keys in the array itself are interpreted as patterns by those flags; the subscript is a plain string in that case.)
One final note, not directly related to subscripting: the numeric names of positional parameters (described below) are parsed specially, so for example `$2foo' is equivalent to `${2}foo'. Therefore, to use subscript syntax to extract a substring from a positional parameter, the expansion must be surrounded by braces; for example, `${2[3,5]}' evaluates to the third through fifth characters of the second positional parameter, but `$2[3,5]' is the entire second parameter concatenated with the filename generation pattern `[3,5]'.
The positional parameters provide access to the command-line arguments of a shell function, shell script, or the shell itself; see the section `Invocation', and also the section `Functions'. The parameter n, where n is a number, is the nth positional parameter. The parameter `$0' is a special case, see the section `Parameters Set By The Shell'.
The parameters *, @ and argv are arrays containing all the positional parameters; thus `$argv[n]', etc., is equivalent to simply `$n'. Note that the options KSH_ARRAYS or KSH_ZERO_SUBSCRIPT apply to these arrays as well, so with either of those options set, `${argv[0]}' is equivalent to `$1' and so on.
Positional parameters may be changed after the shell or function starts by using the set builtin, by assigning to the argv array, or by direct assignment of the form `n=value' where n is the number of the positional parameter to be changed. This also creates (with empty values) any of the positions from 1 to n that do not already have values. Note that, because the positional parameters form an array, an array assignment of the form `n=(value ...)' is allowed, and has the effect of shifting all the values at positions greater than n by as many positions as necessary to accommodate the new values.
Shell function executions delimit scopes for shell parameters. (Parameters are dynamically scoped.) The typeset builtin, and its alternative forms declare, integer, local and readonly (but not export), can be used to declare a parameter as being local to the innermost scope.
When a parameter is read or assigned to, the innermost existing parameter of that name is used. (That is, the local parameter hides any less-local parameter.) However, assigning to a non-existent parameter, or declaring a new parameter with export, causes it to be created in the outermost scope.
Local parameters disappear when their scope ends. unset can be used to delete a parameter while it is still in scope; any outer parameter of the same name remains hidden.
Special parameters may also be made local; they retain their special attributes unless either the existing or the newly-created parameter has the -h (hide) attribute. This may have unexpected effects: there is no default value, so if there is no assignment at the point the variable is made local, it will be set to an empty value (or zero in the case of integers). The following:
typeset PATH=/new/directory:$PATH
is valid for temporarily allowing the shell or programmes called from it to find the programs in /new/directory inside a function.
Note that the restriction in older versions of zsh that local parameters were never exported has been removed.
In the parameter lists that follow, the mark `<S>' indicates that the parameter is special. `<Z>' indicates that the parameter does not exist when the shell initializes in sh or ksh emulation mode.
The following parameters are automatically set by the shell:
If this is made local, it is not implicitly set to 0, but may be explicitly set locally.
If this is made local, it is not implicitly set to 0, but may be explicitly set locally.
If this is made local, it is not implicitly set to 0, but may be explicitly set locally.
The values of RANDOM form an intentionally-repeatable pseudo-random sequence; subshells that reference RANDOM will result in identical pseudo-random values unless the value of RANDOM is referenced or seeded in the parent shell in between subshell invocations.
Unlike other special parameters, the type of the SECONDS parameter can be changed using the typeset command. Only integer and one of the floating point types are allowed. For example, `typeset -F SECONDS' causes the value to be reported as a floating point number. The value is available to microsecond accuracy, although the shell may show more or fewer digits depending on the use of typeset. See the documentation for the builtin typeset in zshbuiltins(1) for more details.
Note that it is possible that an interrupt arrives during the execution of the always block; this interrupt is also propagated.
If this is made local, it is not implicitly set to 0, but may be explicitly set locally.
Note that the variable does not give information on syntactic context such as pipelines or subshells. Use $ZSH_SUBSHELL to detect subshells.
The context is one of the following:
The following parameters are used by the shell. Again, `<S>' indicates that the parameter is special and `<Z>' indicates that the parameter does not exist when the shell initializes in sh or ksh emulation mode.
In cases where there are two parameters with an upper- and lowercase form of the same name, such as path and PATH, the lowercase form is an array and the uppercase form is a scalar with the elements of the array joined together by colons. These are similar to tied parameters created via `typeset -T'. The normal use for the colon-separated form is for exporting to the environment, while the array form is easier to manipulate within the shell. Note that unsetting either of the pair will unset the other; they retain their special properties when recreated, and recreating one of the pair will recreate the other.
This parameter may be profitably set in some circumstances, e.g. for slow modems dialing into a communications server, or on a slow wide area network. It should be set to the baud rate of the slowest part of the link for best performance.
The characters must be in the ASCII character set; any attempt to set histchars to characters with a locale-dependent meaning will be rejected with an error message.
Note that HISTORY_IGNORE defines a single pattern: to specify alternatives use the `(first|second|...)' syntax.
Compare the HIST_NO_STORE option or the zshaddhistory hook, either of which would prevent such commands from being added to the interactive history at all. If you wish to use HISTORY_IGNORE to stop history being added in the first place, you can define the following hook:
zshaddhistory() {
emulate -L zsh
## uncomment if HISTORY_IGNORE
## should use EXTENDED_GLOB syntax
# setopt extendedglob
[[ $1 != ${~HISTORY_IGNORE} ]] }
If this is made local, it is not implicitly set to 0, but may be explicitly set locally.
If the parameter is unset, the default is used. Note this has a different effect from setting the parameter to an empty string.
For backward compatibility, if the SUNKEYBOARDHACK option is explicitly set, the value of KEYBOARD_HACK reverts to backquote. If the option is explicitly unset, this variable is set to empty.
These parameters only exist if the installation supports dynamic module loading.
If this is made local, it is not implicitly set to 0, but may be explicitly set locally.
The actions available at the prompt are [nyae]:
A star may be inserted between the percent sign and flags printing time (e.g., `%*E'); this causes the time to be printed in `hh:mm:ss.ttt' format (hours and minutes are only printed if they are not zero). Alternatively, `m' or `u' may be used (e.g., `%mE') to produce time output in milliseconds or microseconds, respectively.
If it contains the single word `all', then all login/logout events are reported. If it contains the single word `notme', then all events are reported as with `all' except $USERNAME.
An entry in this list may consist of a username, an `@' followed by a remote hostname, and a `%' followed by a line (tty). Any of these may be a pattern (be sure to quote this during the assignment to watch so that it does not immediately perform file generation); the setting of the EXTENDED_GLOB option is respected. Any or all of these components may be present in an entry; if a login/logout event matches all of them, it is reported.
For example, with the EXTENDED_GLOB option set, the following:
watch=('^(pws|barts)')
causes reports for activity assoicated with any user other than pws or barts.
NOTE: The `%m' and `%M' escapes will work only if there is a host name field in the utmp on your machine. Otherwise they are treated as ordinary strings.
The test character x may be any one of `l', `n', `m' or `M', which indicate a `true' result if the corresponding escape sequence would return a non-empty value; or it may be `a', which indicates a `true' result if the watched user has logged in, or `false' if he has logged out. Other characters evaluate to neither true nor false; the entire expression is omitted in this case.
If the result is `true', then the true-text is formatted according to the rules above and printed, and the false-text is skipped. If `false', the true-text is skipped and the false-text is formatted and printed. Either or both of the branches may be empty, but both separators must be present in any case.
This two-element array contains the terminal escape sequences for enabling and disabling the feature. These escape sequences are used to enable bracketed paste when ZLE is active and disable it at other times. Unsetting the parameter has the effect of ensuring that bracketed paste remains disabled.
These variables can contain the sets of characters that will cause the suffix to be removed. If ZLE_REMOVE_SUFFIX_CHARS is set, those characters will cause the suffix to be removed; if ZLE_SPACE_SUFFIX_CHARS is set, those characters will cause the suffix to be removed and replaced by a space.
If ZLE_REMOVE_SUFFIX_CHARS is not set, the default behaviour is equivalent to:
ZLE_REMOVE_SUFFIX_CHARS=$' \t\n;&|'
If ZLE_REMOVE_SUFFIX_CHARS is set but is empty, no characters have this behaviour. ZLE_SPACE_SUFFIX_CHARS takes precedence, so that the following:
ZLE_SPACE_SUFFIX_CHARS=$'&|'
causes the characters `&' and `|' to remove the suffix but to replace it with a space.
To illustrate the difference, suppose that the option AUTO_REMOVE_SLASH is in effect and the directory DIR has just been completed, with an appended /, following which the user types `&'. The default result is `DIR&'. With ZLE_REMOVE_SUFFIX_CHARS set but without including `&' the result is `DIR/&'. With ZLE_SPACE_SUFFIX_CHARS set to include `&' the result is `DIR &'.
Note that certain completions may provide their own suffix removal or replacement behaviour which overrides the values described here. See the completion system documentation in zshcompsys(1).
Typically this will be used to set the value to 0 so that the prompt appears flush with the right hand side of the screen. This is not the default as many terminals do not handle this correctly, in particular when the prompt appears at the extreme bottom right of the screen. Recent virtual terminals are more likely to handle this case correctly. Some experimentation is necessary.
February 3, 2019 | zsh 5.7.1 |