[Contents]   [Back]   [Prev]   [Up]   [Next]   [Forward]  



The types of expansions performed are

History Expansion
Alias Expansion
Process Substitution
Parameter Expansion
Command Substitution
Arithmetic Expansion
Brace Expansion
Filename Expansion
Filename Generation

Expansion is done in the above specified order in five steps. The first is history expansion, which is only performed in interactive shells. The next step is alias expansion, which is done right before the command line is parsed. They are followed by process substitution, parameter expansion, command substitution, arithmetic expansion and brace expansion which are performed in one step in left-to-right fashion. After these expansions, all unquoted occurrences of the characters `\', `'' and `"' are removed, and the result is subjected to filename expansion followed by filename generation.

If the SH_FILE_EXPANSION option is set, the order of expansion is modified for compatibility with sh and ksh. Filename expansion is performed immediately after alias expansion, preceding the set of five expansions mentioned above.

History Expansion

History expansion allows you to use words from previous command lines in the command line you are typing. This simplifies spelling corrections and the repetition of complicated commands or arguments. Command lines are saved in the history list, the size of which is controlled by the HISTSIZE parameter. The most recent command is retained in any case. A history expansion begins with the first character of the histchars parameter which is `!' by default and may occur anywhere on the command line; history expansions do not nest. The `!' can be escaped with `\' or can be enclosed between a pair of single quotes ('') to suppress its special meaning. Double quotes will not work for this.

Input lines containing history expansions are echoed on the terminal after being expanded, but before any other expansions take place or the command gets executed.

Event Designators

An event designator is a reference to a command-line entry in the history list.

Start a history expansion, except when followed by a blank, newline, `=' or `('.
Refer to the previous command. By itself, this expansion repeats the previous command.
Refer to command-line n.
Refer to the current command-line minus n.
Refer to the most recent command starting with str.
Refer to the most recent command containing str.
Refer to the current command line typed in so far. The line is treated as if it were complete up to and including the word before the one with the `!#' reference.
Insulate a history reference from adjacent characters (if necessary).

Word Designators

A word designator indicates which word or words of a given command line will be included in a history reference. A `:' separates the event specification from the word designator. It can be omitted if the word designator begins with a `^', `$', `*', `-' or `%'. Word designators include:

The first input word (command).
The nth argument.
The first argument. That is, 1.
The last argument.
The word matched by (the most recent) ?str search.
A range of words; x defaults to 0.
All the arguments, or a null value if there are none.
Abbreviates `x-$'.
Like `x*' but omitting word $.

Note that a `%' word designator will only work when used as `!%', `!:%' or `!?str?:%', and only when used after a !? expansion. Anything else will result in an error, although the error may not be the most obvious one.


After the optional word designator, you can add a sequence of one or more of the following modifiers, each preceded by a `:'. These modifiers also work on the result of filename generation and parameter expansion, except where noted.

Remove a trailing pathname component, leaving the head.
Remove a trailing suffix of the form `.xxx', leaving the basename.
Remove all but the suffix.
Remove all leading pathname components, leaving the tail.
Print the new command but do not execute it. Only works with history expansion.
Quote the substituted words, escaping further substitutions. Works with history expansion and parameter expansion, though in the second case it is only useful if the resulting text is to be re-evaluated such as by eval.
Like q, but break into words at each blank.
Convert the words to all lowercase.
Convert the words to all uppercase.
(This and the following F, w and W modifier only work with parameter expansion and filename generation.) Repeats the immediately (without a colon) following modifier until the resulting word doesn't change any more.
Like f, but repeats only n times if the expression expr evaluates to n. Any character can be used instead of the `:'; if `(', `[', or `{' is used as the opening delimiter, the closing delimiter should be ')', `]', or `}', respectively.
Makes the immediately following modifier work on each word in the string.
Like w but words are considered to be the parts of the string that are separated by sep. Any character can be used instead of the `:'; opening parentheses are handled specially, see above.
Substitute r for l as described below. Unless preceded immediately by a g, with no colon between, the substitution is done only for the first string that matches l. For arrays and for filename generation, this applies to each word of the expanded text.
Repeat the previous s substitution. Like s, may be preceded immediately by a g. In variable expansion the & must appear inside braces, and in filename generation it must be quoted with a backslash.

The s/l/r/ substitution works as follows. The left-hand side of substitutions are not regular expressions, but character strings. Any character can be used as the delimiter in place of `/'. A backslash quotes the delimiter character. The character `&', in the right-hand-side r, is replaced by the text from the left-hand-side l. The `&' can be quoted with a backslash. A null l uses the previous string either from the previous l or from the contextual scan string s from `!?s'. You can omit the rightmost delimiter if a newline immediately follows r; the rightmost `?' in a context scan can similarly be omitted. Note the same record of the last l and r is maintained across all forms of expansion.

By default, a history reference with no event specification refers to the same line as the previous history reference on that command line, unless it is the first history reference in a command. In that case, a history reference with no event specification always refers to the previous command. However, if the option CSH_JUNKIE_HISTORY is set, then history reference with no event specification will always refer to the previous command.

For example, `!!:1' will always refer to the first word of the previous command, and `!!$' will always refer to the last word of the previous command. And with CSH_JUNKIE_HISTORY set, then `!:1' and `!$' will function in the same manner as `!!:1' and `!!$', respectively. However, if CSH_JUNKIE_HISTORY is unset, then `!:1' and `!$' will refer to the first and last words respectively, of the last command referenced on the current command line. However, if they are the first history reference on the command line, then they refer to the previous command.

The character sequence `^foo^bar' (where `^' is actually the second charcter of the histchars parameter) repeats the last command, replacing the string foo with bar. More precisely, the sequence `^foo^bar^' is synonymous with `!!:s^foo^bar^', hence other modifiers may follow the final `^'.

If the shell encounters the character sequence `!"' in the input, the history mechanism is temporarily disabled until the current list is fully parsed. The `!"' is removed from the input, and any subsequent `!' characters have no special significance.

A less convenient but more comprehensible form of command history support is provided by the fc builtin.

Process Substitution

Each command argument of the form `<(list)', `>(list)' or `=(list)' is subject to process substitution. In the case of the < or > forms, the shell will run process list asynchronously, connected to a named pipe (FIFO). The name of this pipe will become the argument to the command. If the form with > is selected then writing on this file will provide input for list. If < is used, then the file passed as an argument will be a named pipe connected to the output of the list process. For example,

paste <(cut -f1 file1) <(cut -f3 file2) |
tee >(
process1) >(process2) >/dev/null

cuts fields 1 and 3 from the files file1 and file2 respectively, pastes the results together, and sends it to the processes process1 and process2. Note that the file, which is passed as an argument to the command, is a system pipe, so programs that expect to lseek (see man page lseek(2)) on the file will not work. Also note that the previous example can be more compactly and efficiently written (provided the MULTIOS option is set) as:

paste <(cut -f1 file1) <(cut -f3 file2) > >(process1) > >(process2)

The shell uses pipes instead of FIFOs to implement the latter two process substitutions in the above example.

If = is used, then the file passed as an argument will be the name of a temporary file containing the output of the list process. This may be used instead of the < form for a program that expects to lseek (see man page lseek(2)) on the input file.

Parameter Expansion

The character `$' is used to introduce parameter expansions. See section 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 section 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 file modifiers described in section Modifiers in section History Expansion can be applied: for example, ${i:s/foo/bar/} performs string substitution on the expansion of parameter $i.

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.

If name is the name of a set parameter `1' is substituted, otherwise `0' is substituted.
If name is set and is non-null then substitute its value; otherwise substitute word. If name is missing, substitute 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.
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.
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.

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.
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.
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).
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. 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.

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'.

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.
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 section Brace Expansion above. If word splitting is also in effect the $var[N] may themselves be split into different list elements.

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.

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.

Note that double quotes may appear around nested substitutions, 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 substitutions. 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. Where arguments are valid, any character, or the matching pairs `(...)', `{...}', `[...]', or `<...>', may be used in place of the colon as delimiters. The following flags are supported:

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 word splitting, when creating an associative array.
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]".
Perform parameter expansion, command substitution and arithmetic expansion on the result. Such expansions can be nested but too deep recursion may have unpredictable effects.
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 tt${(P)$(echo bar)} will be expanded to `baz'.
Sort the resulting words in ascending order.
Sort the resulting words in descending order.
With o or O, sort case-independently.
Convert all letters in the result to lower case.
Convert all letters in the result to upper case.
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.
With ${#name}, count the total number of characters in an array, as if the elements were concatenated with spaces between them.
With ${#name}, count words in arrays or strings; the s flag may be used to set a word delimiter.
Similar to w with the difference that empty words between repeated delimiters are also counted.
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.
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.
Recognize the same escape sequences as the print builtin in string arguments to any of the flags described below.
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.
As l, but pad the words on the right and insert string2 on the right.
Join the words of arrays together using string as a separator. Note that this occurs before field splitting by the SH_WORD_SPLIT option.
Join the words of arrays together using newline as a separator. This is a shorthand for `pj:\n:'.
Force field splitting (see the option SH_WORD_SPLIT) at the separator string. Splitting only occurs in places where an array value is valid.
Split the result of the expansion to lines. This is a shorthand for `ps:\n:'.
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', or `association'. The other keywords describe the type in more detail:

for local parameters
for left justified parameters
for right justified parameters with leading blanks
for right justified parameters with leading zeros
for parameters whose value is converted to all lower case when it is expanded
for parameters whose value is converted to all upper case when it is expanded
for readonly parameters
for tagged parameters
for exported parameters
for arrays which keep only the first occurrence of duplicated values

The following flags are meaningful with the ${...#...}, ${...%...}, or ${.../...} forms.

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 that the shortest instead of the longest match should be replaced.
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 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.
Include the matched portion in the result.
Include the unmatched portion in the result (the Rest).
Include the index of the beginning of the match in the result.
Include the index of the end of the match in the result.
Include the length of the match in the result.


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 section Modifiers in section 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)' or `(f)' 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, take 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.


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):

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.
The 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

produces the words `a', `1 b' and `1'.
produces `a', `1', `b' and `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.

Command Substitution

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

Arithmetic Expansion

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

Brace Expansion

A string of the form `foo{xx,yy,zz}bar' is expanded to the individual words `fooxxbar', `fooyybar' and `foozzbar'. Left-to-right order is preserved. This construct may be nested. Commas may be quoted in order to include them literally in a word.

An expression of the form `{n1..n2}', where n1 and n2 are integers, is expanded to every number between n1 and n2 inclusive. If either number begins with a zero, all the resulting numbers will be padded with leading zeroes to that minimum width. If the numbers are in decreasing order the resulting sequence will also be in decreasing order.

If a brace expression matches none of the above forms, it is left unchanged, unless the BRACE_CCL option is set. In that case, it is expanded to a sorted list of the individual characters between the braces, in the manner of a search set. `-' is treated specially as in a search set, but `^' or `!' as the first character is treated normally.

Filename Expansion

Each word is checked to see if it begins with an unquoted `~'. If it does, then the word up to a `/', or the end of the word if there is no `/', is checked to see if it can be substituted in one of the ways described here. If so, then the `~' and the checked portion are replaced with the appropriate substitute value.

A `~' by itself is replaced by the value of $HOME. A `~' followed by a `+' or a `-' is replaced by the value of $PWD or $OLDPWD, respectively.

A `~' followed by a number is replaced by the directory at that position in the directory stack. `~0' is equivalent to `~+', and `~1' is the top of the stack. `~+' followed by a number is replaced by the directory at that position in the directory stack. `~+0' is equivalent to `~+', and `~+1' is the top of the stack. `~-' followed by a number is replaced by the directory that many positions from the bottom of the stack. `~-0' is the bottom of the stack. The PUSHD_MINUS option exchanges the effects of `~+' and `~-' where they are followed by a number.

A `~' followed by anything not already covered is looked up as a named directory, and replaced by the value of that named directory if found. Named directories are typically home directories for users on the system. They may also be defined if the text after the `~' is the name of a string shell parameter whose value begins with a `/'. It is also possible to define directory names using the -d option to the hash builtin.

In certain circumstances (in prompts, for instance), when the shell prints a path, the path is checked to see if it has a named directory as its prefix. If so, then the prefix portion is replaced with a `~' followed by the name of the directory. The shortest way of referring to the directory is used, with ties broken in favour of using a named directory, except when the directory is / itself. The variables $PWD and $OLDPWD are never abbreviated in this fashion.

If a word begins with an unquoted `=' and the EQUALS option is set, the remainder of the word is taken as the name of a command or alias. If a command exists by that name, the word is replaced by the full pathname of the command. If an alias exists by that name, the word is replaced with the text of the alias.

Filename expansion is performed on the right hand side of a parameter assignment, including those appearing after commands of the typeset family. In this case, the right hand side will be treated as a colon-separated list in the manner of the PATH parameter, so that a `~' or an `=' following a `:' is eligible for expansion. All such behaviour can be disabled by quoting the `~', the `=', or the whole expression (but not simply the colon); the EQUALS option is also respected.

If the option MAGIC_EQUAL_SUBST is set, any unquoted shell argument in the form `identifier=expression' becomes eligible for file expansion as described in the previous paragraph. Quoting the first `=' also inhibits this.

Filename Generation

If a word contains an unquoted instance of one of the characters `*', `(', `|', `<', `[', or `?', it is regarded as a pattern for filename generation, unless the GLOB option is unset. If the EXTENDED_GLOB option is set, the `^' and `#' characters also denote a pattern; otherwise they are not treated specially by the shell.

The word is replaced with a list of sorted filenames that match the pattern. If no matching pattern is found, the shell gives an error message, unless the NULL_GLOB option is set, in which case the word is deleted; or unless the NOMATCH option is unset, in which case the word is left unchanged.

In filename generation, the character `/' must be matched explicitly; also, a `.' must be matched explicitly at the beginning of a pattern or after a `/', unless the GLOB_DOTS option is set. No filename generation pattern matches the files `.' or `..'. In other instances of pattern matching, the `/' and `.' are not treated specially.

Glob Operators

Matches any string, including the null string.
Matches any character.
Matches any of the enclosed characters. Ranges of characters can be specified by separating two characters by a `-'. A `-' or `]' may be matched by including it as the first character in the list. There are also several named classes of characters, in the form `[:name:]' with the following meanings: `[:alnum:]' alphanumeric, `[:alpha:]' alphabetic, `[:blank:]' space or tab, `[:cntrl:]' control character, `[:digit:]' decimal digit, `[:graph:]' printable character except whitespace, `[:lower:]' lowercase letter, `[:print:]' printable character, `[:punct:]' printable character neither alphanumeric nor whitespace, `[:space:]' whitespace character, `[:upper:]' uppercase letter, `[:xdigit:]' hexadecimal digit. These use the macros provided by the operating system to test for the given character combinations, including any modifications due to local language settings: see man page ctype(3). Note that the square brackets are additional to those enclosing the whole set of characters, so to test for a single alphanumeric character you need `[[:alnum:]]'. Named character sets can be used alongside other types, e.g. `[[:alpha:]0-9]'.
Like [...], except that it matches any character which is not in the given set.
Matches any number in the range x to y, inclusive. Either of the numbers may be omitted to make the range open-ended; hence `<->' matches any number.
Matches the enclosed pattern. This is used for grouping. If the KSH_GLOB option is set, then a `@', `*', `+', `?' or `!' immediately preceding the `(' is treated specially, as detailed below. Note that grouping cannot currently extend over multiple directories: a `/' separating a directory terminates processing of the current group; processing resumes after the end of the group.
Matches either x or y. This operator has lower precedence than any other. The `|' character must be within parentheses, to avoid interpretation as a pipeline.
(Requires EXTENDED_GLOB to be set.) Matches anything except the pattern x. This has a higher precedence than `/', so `^foo/bar' will search directories in `.' except `./foo' for a file named `bar'.
(Requires EXTENDED_GLOB to be set.) Match anything that matches the pattern x but does not match y. This has lower precedence than any operator except `|', so `*/*~foo/bar' will search for all files in all directories in `.' and then exclude `foo/bar' if there was such a match. Multiple patterns can be excluded by `foo~(bar|baz)'. In the exclusion pattern (y), `/' and `.' are not treated specially the way they usually are in globbing.
(Requires EXTENDED_GLOB to be set.) Matches zero or more occurrences of the pattern x. This operator has high precedence; `12#' is equivalent to `1(2#)', rather than `(12)#'.
(Requires EXTENDED_GLOB to be set.) Matches one or more occurrences of the pattern x. This operator has high precedence; `12##' is equivalent to `1(2##)', rather than `(12)##'.

ksh-like Glob Operators

If the KSH_GLOB option is set, the effects of parentheses can be modified by a preceding `@', `*', `+', `?' or `!'. This character need not be unquoted to have special effects, but the `(' must be.

Match the pattern in the parentheses. (Like `(...)'.)
Match any number of occurrences. (Like `(...)#'.)
Match at least one occurrence. (Like `(...)##'.)
Match zero or one occurrence. (Like `(|...)'.)
Match anything but the expression in parentheses. (Like `(^(...))'.)

Globbing Flags

There are various flags which affect any text to their right up to the end of the enclosing group or to the end of the pattern; they require the EXTENDED_GLOB option. All take the form (#X) where X may have one of the following forms:

Case insensitive: upper or lower case characters in the pattern match upper or lower case characters.
Lower case characters in the pattern match upper or lower case characters; upper case characters in the pattern still only match upper case characters.
Case sensitive: locally negates the effect of i or l from that point on.
Approximate matching: num errors are allowed in the string matched by the pattern. The rules for this are described in the next subsection.

For example, the test string fooxx can be matched by the pattern (#i)FOOXX, but not by (#l)FOOXX, (#i)FOO(#I)XX or ((#i)FOOX)X. The string (#ia2)readme specifies case-insensitive matching of readme with up to two errors.

When using the ksh syntax for grouping both KSH_GLOB and EXTENDED_GLOB must be set and the left parenthesis should be preceded by @. Note also that the flags do not affect letters inside [...] groups, in other words (#i)[a-z] still matches only lowercase letters. Finally, note that when examining whole paths case-insensitively every directory must be searched for all files which match, so that a pattern of the form (#i)/foo/bar/... is potentially slow.

Approximate Matching

When matching approximately, the shell keeps a count of the errors found, which cannot exceed the number specified in the (#anum) flags. Four types of error are recognised:

Different characters, as in fooxbar and fooybar.
Transposition of characters, as in banana and abnana.
A character missing in the target string, as with the pattern road and target string rod.
An extra character appearing in the target string, as with stove and strove.

Thus, the pattern (#a3)abcd matches dcba, with the errors occurring by using the first rule twice and the second once, grouping the string as [d][cb][a] and [a][bc][d].

Non-literal parts of the pattern must match exactly, including characters in character ranges: hence (#a1)??? matches strings of length four, by applying rule 4 to an empty part of the pattern, but not strings of length two, since all the ? must match. Other characters which must match exactly are initial dots in filenames (unless the GLOB_DOTS option is set), and all slashes in filenames, so that a/bc is two errors from ab/c (the slash cannot be transposed with another character). Similarly, errors are counted separately for non-contiguous strings in the pattern, so that (ab|cd)ef is two errors from aebf.

When using exclusion via the ~ operator, approximate matching is treated entirely separately for the excluded part and must be activated separately. Thus, (#a1)README~READ_ME matches READ.ME but not READ_ME, as the trailing READ_ME is matched without approximation. However, (#a1)README~(#a1)READ_ME does not match any pattern of the form READ?ME as all such forms are now excluded.

Apart from exclusions, there is only one overall error count; however, the maximum errors allowed may be altered locally, and this can be delimited by grouping. For example, (#a1)cat((#a0)dog)fox allows one error in total, which may not occur in the dog section, and the pattern (#a1)cat(#a0)dog(#a1)fox is equivalent.

Recursive Globbing

A pathname component of the form `(foo/)#' matches a path consisting of zero or more directories matching the pattern foo. As a shorthand, `**/' is equivalent to `(*/)#'. Thus:

ls (*/)#bar


ls **/bar

does a recursive directory search for files named `bar', not following symbolic links. To follow links, use `***/'.

Glob Qualifiers

Patterns used for filename generation may end in a list of qualifiers enclosed in parentheses. The qualifiers specify which filenames that otherwise match the given pattern will be inserted in the argument list.

If the option BARE_GLOB_QUAL is set, then a trailing set of parentheses containing no `|' or `(' characters (or `~' if it is special) is taken as a set of glob qualifiers. A glob subexpression that would normally be taken as glob qualifiers, for example `(^x)', can be forced to be treated as part of the glob pattern by doubling the parentheses, for example `((^x))'.

A qualifier may be any one of the following:

plain files
symbolic links
named pipes (FIFOs)
executable plain files (0100)
device files (character or block special)
block special files
character special files
owner-readable files (0400)
owner-writable files (0200)
owner-executable files (0100)
group-readable files (0040)
group-writable files (0020)
group-executable files (0010)
world-readable files (0004)
world-writable files (0002)
world-executable files (0001)
setuid files (04000)
setgid files (02000)
files with the sticky bit (01000)
files with access rights matching spec. This spec may be a octal number optionally preceded by a `=', a `+', or a `-'. If none of these characters is given, the behavior is the same as for `='. The octal number describes the mode bits to be expected, if combined with a `=', the value given must match the file-modes exactly, with a `+', at least the bits in the given number must be set in the file-modes, and with a `-', the bits in the number must not be set. Giving a `?' instead of a octal digit anywhere in the number ensures that the corresponding bits in the file-modes are not checked, this is only useful in combination with `='.

If the qualifier `f' is followed by any other character anything up to the next matching character (`[', `{', and `<' match `]', `}', and `>' respectively, any other character matches itself) is taken as a list of comma-separated sub-specs. Each sub-spec may be either a octal number as described above or a list of any of the characters `u', `g', `o', and `a', followed by a `=', a `+', or a `-', followed by a list of any of the characters `r', `w', `x', `s', and `t', or a octal digit. The first list of characters specify which access rights are to be checked. If a `u' is given, those for the owner of the file are used, if a `g' is given, those of the group are checked, a `o' means to test those of other users, and the `a' says to test all three groups. The `=', `+', and `-' again says how the modes are to be checked and have the same meaning as described for the first form above. The second list of characters finally says which access rights are to be expected: `r' for read access, `w' for write access, `x' for the right to execute the file (or to search a directory), `s' for the setuid and setgid bits, and `t' for the sticky bit.

Thus, `*(f70?)' gives the files for which the owner has read, write, and execute permission, and for which other group members have no rights, independent of the permissions for other users. The pattern `*(f-100)' gives all files for which the owner does not have execute permission, and `*(f:gu+w,o-rx:)' gives the files for which the owner and the other members of the group have at least write permission, and for which other users don't have read or execute permission.

files on the device dev
files having a link count less than ct (-), greater than ct (+), or is equal to ct
files owned by the effective user ID
files owned by the effective group ID
files owned by user ID id if it is a number, if not, than the character after the `u' will be used as a separator and the string between it and the next matching separator (`[', `{', and `<' match `]', `}', and `>' respectively, any other character matches itself) will be taken as a user name, and the user ID of this user will be taken (e.g. `u:foo:' or `u[foo]' for user `foo')
like uid but with group IDs or names
files accessed exactly n days ago. Files accessed within the last n days are selected using a negative value for n (-n). Files accessed more than n days ago are selected by a positive n value (+n). Optional unit specifiers `M', `w', `h', `m' or `s' (e.g. `ah5') cause the check to be performed with months (of 30 days), weeks, hours, minutes or seconds instead of days, respectively. For instance, `echo *(ah-5)' would echo files accessed within the last five hours.
like the file access qualifier, except that it uses the file modification time.
like the file access qualifier, except that it uses the file inode change time.
files less than n bytes (-), more than n bytes (+), or exactly n bytes in length. If this flag is directly followed by a `k' (`K'), `m' (`M'), or `p' (`P') (e.g. `Lk-50') the check is performed with kilobytes, megabytes, or blocks (of 512 bytes) instead.
negates all qualifiers following it
toggles between making the qualifiers work on symbolic links (the default) and the files they point to
sets the MARK_DIRS option for the current pattern
appends a trailing qualifier mark to the filenames, analogous to the LIST_TYPES option, for the current pattern (overrides M)
sets the NULL_GLOB option for the current pattern
sets the GLOB_DOTS option for the current pattern
specifies how the names of the files should be sorted. If c is n they are sorted by name (the default), if it is L they are sorted depending on the size (length) of the files, if l they are sorted by the number of links, and if a, m, and c they are sorted by the time of the last access, modification, or inode change respectively. Note that a, m, and c compare the age against the current time, hence the first name in the list is the the youngest file. Also note that the modifiers ^ and - are used, so `*(^-oL)' gives a list of all files sorted by file size in descending order, following any symbolic links.
like `o', but sorts in descending order; i.e. `*(^oc)' is the same as `*(Oc)' and `*(^Oc)' is the same as `*(oc)'
specifies which of the matched filenames should be included in the returned list. The syntax is the same as for array subscripts. beg and the optional end may be mathematical expressions. As in parameter subscripting they may be negative to make them count from the last match backward. E.g.: `*(-OL[1,3])' gives a list of the names of the three largest files.

More than one of these lists can be combined, separated by commas. The whole list matches if at least one of the sublists matches (they are `or'ed, the qualifiers in the sublists are `and'ed).

If a `:' appears in a qualifier list, the remainder of the expression in parenthesis is interpreted as a modifier (see section Modifiers in section History Expansion). Note that each modifier must be introduced by a separate `:'. Note also that the result after modification does not have to be an existing file. The name of any existing file can be followed by a modifier of the form `(:..)' even if no actual filename generation is performed. Thus:

ls *(-/)

lists all directories and symbolic links that point to directories, and

ls *(%W)

lists all world-writable device files in the current directory, and

ls *(W,X)

lists all files in the current directory that are world-writable or world-executable, and

echo /tmp/foo*(u0^@:t)

outputs the basename of all root-owned files beginning with the string `foo' in /tmp, ignoring symlinks, and

ls *.*~(lex|parse).[ch](^D^l1)

lists all files having a link count of one whose names contain a dot (but not those starting with a dot, since GLOB_DOTS is explicitly switched off) except for lex.c, lex.h, parse.c and parse.h.

[Contents]   [Back]   [Prev]   [Up]   [Next]   [Forward]